繁体   English   中英

如何在Android上调整Yuv图像的大小

[英]How to resize Yuv image on android

请告诉我如何在android上调整yuv图像的大小。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
mCameraView.myuvImage.compressToJpeg(new Rect(0, 0, mCameraView.myuvImage.getWidth(), mCameraView.myuvImage.getHeight()), 100, baos);

compressToJpeg方法将yuv图像转换为jpeg。 但是我写时不会按压缩数字调整转换后的JPEG的大小

mCameraView.myuvImage.compressToJpeg(new Rect(0, 0, mCameraView.myuvImage.getWidth(), mCameraView.myuvImage.getHeight()), 50, baos);

最简单的方法是创建缩放的位图。 首先,将位图转换为位图图像:

ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuvImage = new YuvImage(mCameraView.myuvImage, PictureFormat.NV21, width, height, null);
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 50, out);
byte[] imageBytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);

然后,您可以使用以下命令调整大小:

Bitmap resized = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);

我发现的方法可能不是一个很好的方法,但这至少对我有用:

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();
}

这应该可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM