拍摄图像后需要裁剪位图。放
public static void cropToJpeg2(final byte[] jpeg, final AspectRatio targetRatio, final int jpegCompression, final CameraUtils.BitmapCallback callback) {
final Handler ui = new Handler();
WorkerHandler.run(new Runnable() {
@Override
public void run() {
Bitmap image = decodeBitmap(jpeg, Integer.MAX_VALUE, Integer.MAX_VALUE);
Rect cropRect = computeCrop(image.getWidth(), image.getHeight(), targetRatio);
final Bitmap crop = Bitmap.createBitmap(image, cropRect.left, cropRect.top, cropRect.width(), cropRect.height());
image.recycle();
ByteArrayOutputStream out = new ByteArrayOutputStream();
crop.compress(Bitmap.CompressFormat.JPEG, jpegCompression, out);
ui.post(new Runnable() {
@Override
public void run() {
callback.onBitmapReady(crop);
}
});
}
});
}
计算作物功能
private static Rect computeCrop(int currentWidth, int currentHeight, AspectRatio targetRatio) {
AspectRatio currentRatio = AspectRatio.of(currentWidth, currentHeight);
logger.e("CropHelper", "computeCrop: currentRatio " + currentRatio);
logger.e("CropHelper", "computeCrop: targetRatio " + targetRatio);
int x, y, width, height;
if (currentRatio.toFloat() > targetRatio.toFloat()) {
height = currentHeight;
width = (int) (height * targetRatio.toFloat());
y = 0;
x = (currentWidth - width) / 2;
} else {
width = currentWidth;
height = (int) (width / targetRatio.toFloat());
// y = (currentHeight - height) / 2;
y = 0; //change above line for crop exact image from camera (remove heading).
x = 0;
}
return new Rect(x, y, x + width, y + height);
}
检查
WorkerHandler class
.
注:-
decodeBitmap
函数在Exif计算后返回位图以进行旋转。