我发现的可能不是一个很好的方法,但至少对我有用:
YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null); //create YuvImage instance with initial size
ByteArrayOutputStream bao = new ByteArrayOutputStream();
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), jpegQuality, bao);
我有aspect 设置在外面的值。该值表示乘数,我们将比例减小多少,例如如果aspect == 1,我们使用相同的分辨率。如果 aspect == 2 我们将图像分辨率除以 2 等等。仅在 aspect != 1 的情况下才需要缩放
if (aspect != 1) {
int newWidth = image.getWidth() / aspect;
int newHeight = image.getHeight() / aspect;
byte[] scaledBitmapData = bitmapToByteArray(createScaledBitmap(bao.toByteArray(), newWidth, newHeight));
bao = new ByteArrayOutputStream(scaledBitmapData.length);
bao.write(scaledBitmapData, 0 , scaledBitmapData.length);
image.compressToJpeg(new Rect(0, 0, newWidth, newHeight), jpegQuality, bao);
}
实用方法:
public static Bitmap createScaledBitmap(byte[] bitmapAsData, int width, int height) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapAsData, 0, bitmapAsData.length);
return createScaledBitmap(bitmap, width, height);
}
public static Bitmap createScaledBitmap(Bitmap bitmap, int width, int height) {
return Bitmap.createScaledBitmap(bitmap, width, height, true);
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, blob);
return blob.toByteArray();
}
这应该可以解决问题。