将存储为byte[]数组的图像翻转

7
我有一张图像,存储为 byte[] 数组,我想在将其发送到其他地方进行处理之前翻转图像(作为 byte[] 数组)。
我搜索了一下,没有找到简单的解决方案,而不需要操作 byte[] 数组中的每个位。
将 byte[] 数组转换为某种图像类型,使用现有的翻转方法来翻转它,然后将其转换回 byte[] 数组有什么问题吗?
有什么建议吗?
干杯!

“flip”是什么意思? - fge
将图像旋转,使其从“倒立”图像变为“正立”图像。 - LKB
2
将字节数组[]转换为某种图像类型,使用现有的翻转方法进行翻转,然后将其转换回字节数组[],如何处理?是的。将其转换为位图,旋转,然后再转换回数组。 - Voicu
谢谢@Voicu,您知道将byte[]数组转换为Bitmap的最佳方法吗? - LKB
1
添加了一些代码的答案。 - Voicu
2个回答

11

字节数组转换为位图:

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

使用此功能通过提供正确的角度(180)来旋转图像:

public Bitmap rotateImage(int angle, Bitmap bitmapSrc) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(bitmapSrc, 0, 0, 
        bitmapSrc.getWidth(), bitmapSrc.getHeight(), matrix, true);
}

然后回到数组:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] flippedImageByteArray = stream.toByteArray();

我的图像是Gray8格式,从字节数组到位图的转换过程不应该影响格式,对吗?非常感谢您的帮助。 :) - LKB
返回位图时出现空指针异常 - 返回Bitmap.createBitmap(bitmapSource,0,0,bitmapSource.getWidth(),bitmapSource.getHeight(),matrix,true); - LKB
1
你很可能向 rotateImage 方法发送了一个空引用,因为在第一步中该图像无法解码为 Bitmap - Voicu
很有可能是Gray8格式导致的问题。有没有把这些图像转换成PNG/JPEG/GIF格式的机会? - Voicu
是的,我已经在我的字节数组转换为灰度8格式之前插入了字节数组到位图的转换代码,它可以正常工作。 :) - LKB
你不应该解码这张图片。为什么呢?因为你可能会用尽内存,因此在解码时需要将图像缩小。然后你会翻转缩小后的图像。这样最终得到的结果是正确翻转了,但分辨率很差。 - Matthias

0
以下是一种用于翻转以字节数组存储的图像并返回结果字节数组的方法。
private byte[] flipImage(byte[] data, int flip) {
    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    Matrix matrix = new Matrix();
    switch (flip){
        case 1: matrix.preScale(1.0f, -1.0f); break; //flip vertical
        case 2: matrix.preScale(-1.0f, 1.0f); break; //flip horizontal
        default: matrix.preScale(1.0f, 1.0f); //No flip
    }

    Bitmap bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp2.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}

如果您想要一个垂直翻转的图像,则将1作为翻转值传递,对于水平翻转,请传递2。

例如:
@Override
public void onPictureTaken(byte[] data, Camera camera) {
   byte[] verticalFlippedImage = flipImage(data,1);
   byte[] horizontalFlippedImage = flipImage(data,2);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接