Android 将相机预览帧数据转化成bitmap保存成图片
2018-05-08 本文已影响0人
Beck766
首先格式化成YUV格式
try {
//格式成YUV格式
YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, camera.getParameters().getPreviewSize().width,
camera.getParameters().getPreviewSize().height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, camera.getParameters().getPreviewSize().width,
camera.getParameters().getPreviewSize().height), 100, baos);
Bitmap bitmap = bytes2Bimap(baos.toByteArray());
Log.i(TAG, "onNext: " + bitmap);
saveImage(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
转换成Bitmap
public Bitmap bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
保存在pic目录下
public void saveImage(Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), "pic");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
附带图片压缩方法
private Bitmap getBitmap(String path){
try {
FileInputStream is = new FileInputStream(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[100 * 1024];
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true;
options.inSampleSize = 4;
options.inInputShareable = true;
return BitmapFactory.decodeStream(is, null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
图片镜像旋转方法
public static Bitmap convert(Bitmap bitmap, boolean mIsFrontalCamera) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap newbBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
Canvas cv = new Canvas(newbBitmap);
android.graphics.Matrix m = new android.graphics.Matrix();
m.postScale(1, -1); //镜像垂直翻转
if (mIsFrontalCamera) {
m.postScale(-1, 1); // 镜像水平翻转
}
// m.postRotate(-90); //旋转-90度
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, w, h, m, true);
cv.drawBitmap(bitmap2,
new Rect(0, 0, bitmap2.getWidth(), bitmap2.getHeight()),
new Rect(0, 0, w, h), null);
return newbBitmap;
}