首页 > 代码库 > Android -- 几种保存成jpeg文件的形式

Android -- 几种保存成jpeg文件的形式

//1.采用NV21格式 YuvImage类进行保存   效率很高
String fileName = "IMG_"
       + String.valueOf(index) + ".jpg";
File sdRoot = Environment.getExternalStorageDirectory();
String dir = "/picture/";
File mkDir = new File(sdRoot, dir);
if (!mkDir.exists())
{
   mkDir.mkdirs();
}


File pictureFile = new File(sdRoot, dir + fileName);
if (!pictureFile.exists()) {
   try {
       pictureFile.createNewFile();

       FileOutputStream filecon = new FileOutputStream(pictureFile);
       YuvImage image = new YuvImage(data,
               ImageFormat.NV21, size.width, size.height,
               null);

       image.compressToJpeg(
               new Rect(0, 0, image.getWidth(), image.getHeight()),
               70, filecon);   // 将NV21格式图片,以质量70压缩成Jpeg,并得到JPEG数据流

   }catch (IOException e)
   {
       e.printStackTrace();
   }
}


//2.采用Bitmap类
Bitmap bmp = BitmapFactory.decodeFile(pictureFile.getPath());
FileOutputStream fileOutStream = null;
fileOutStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutStream);  //把位图输出到指定的文件中
fileOutStream.flush();
fileOutStream.close();


//3.直接采用保存byte[]数据
FileOutputStream fos = new FileOutputStream(pictureFile.getPath()); // Get file output stream
fos.write(bytes);                                               // Written to the file
fos.close();

Android -- 几种保存成jpeg文件的形式