Android -- 将NV21图像保存成JPEG


//保存一张照片
String fileName = "IMG_" + String.valueOf(index) + ".jpg";  //jpeg文件名定义
File sdRoot = Environment.getExternalStorageDirectory();    //系统路径
String dir = "/jpeg/";   //文件夹名
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, width, height, null);   //将NV21 data保存成YuvImage
       //图像压缩
       image.compressToJpeg(
               new Rect(0, 0, image.getWidth(), image.getHeight()),
               70, filecon);   // 将NV21格式图片,以质量70压缩成Jpeg,并得到JPEG数据流

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

该方法,常常在 Camera.PreviewCallback中采用:

@Override
public void onPreviewFrame(byte[] data, Camera camera) {

}



将NV21数据压缩成JPEG,并得到JPEG byte数据,解压JPEG byte数据成一张Bitmap

@Override
public void onPreviewFrame(byte[] bytes, Camera camera) {

    YuvImage image = new YuvImage(bytes, ImageFormat.NV21, width, height, null);            //ImageFormat.NV21  640 480
    ByteArrayOutputStream outputSteam = new ByteArrayOutputStream();
    image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 70, outputSteam); // 将NV21格式图片,以质量70压缩成Jpeg,并得到JPEG数据流
    byte[] jpegData = outputSteam.toByteArray();                                                //从outputSteam得到byte数据

    Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap bmp = BitmapFactory.decodeStream(jpegData, null, options);
}


http://my.oschina.net/eclipse88/blog/80115

你可能感兴趣的:(Android,Java)