【问题标题】:output image is black in android输出图像在android中是黑色的
【发布时间】:2016-03-31 19:07:39
【问题描述】:

我首先尝试将 jpg 转换为 rgb 值数组,然后尝试将相同的数组还原为 jpg

picw = selectedImage.getWidth();
pich = selectedImage.getHeight();

int[] pix = new int[picw * pich];

selectedImage.getPixels(pix, 0, picw, 0, 0, picw, pich);
int R, G, B;

for (int y = 0; y < pich; y++) {
        for (int x = 0; x < picw; x++) {
            int index = y * picw + x;
            R = (pix[index] >> 16) & 0xff;
            G = (pix[index] >> 8) & 0xff;
            B = pix[index] & 0xff;
            pix[index] = (R << 16) | (G << 8) | B;
        }
    }

到目前为止,一切都很好(我通过记录数组进行了检查),但是当我创建位图以将其压缩为 jpg 时,输出为黑色图像。

Bitmap bmp = Bitmap.createBitmap(pix, picw, pich,Bitmap.Config.ARGB_8888);
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(folder,"Wonder.jpg");
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

请帮助我进一步移动,谢谢

【问题讨论】:

  • 您似乎缺少每个像素的一个字节数据:alpha。
  • @KompjoeFriek,请你详细解释一下,我不知道。
  • Alpha 控制像素可见的程度,从 0(不可见)到 255(完全可见或不透明)。当您使用 pix[index] = (R &lt;&lt; 16) | (G &lt;&lt; 8) | B; 更改像素时,您将 alpha 的值保留为 0。
  • @KompjoeFriek,那么我如何在这段代码中添加这个 Alpha。
  • 你可以googleRGBA格式

标签: java android bitmap fileoutputstream


【解决方案1】:

首先让我解释一下这些数据是如何按像素存储的:

每个像素都有 32 位数据来存储一个值:Alpha、Red、Green 和 Blue。这些值中的每一个都只有 8 位(或一个字节)。 (还有很多其他的存储颜色信息的格式,但是你指定的是ARGB_8888)。

在这种格式中,白色是0xffffffff,黑色是0xff000000

所以,就像我在 cmets 中所说的那样,alpha 似乎丢失了。像0x00ff0000 这样没有任何 alpha 的红色像素将不可见。

Alpha 可以通过先存储来添加:

A = (pix[index] >> 24) & 0xff;

虽然该值可能是 255(因为 JPEG 没有 alpha),但我认为这样使用它是明智的,以防您决定使用另一种具有 alpha 的格式。

那么你应该把 alpha 放回去:

pix[index] = (A << 24) | (R << 16) | (G << 8) | B;

这应该将完全相同的值写入它已经包含的pix[index],而不是更改任何内容。但它会给您留下原始图像,而不仅仅是黑色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多