gpt4 book ai didi

java - 使用 BufferedImage 在 Java 中创建图像

转载 作者:行者123 更新时间:2023-11-30 09:11:17 30 4
gpt4 key购买 nike

我正在尝试使用 BufferedImage 中的 setRGB() 方法使用给定的 2D 像素阵列(行和列)重新创建图像。

下面是代码:

BufferedImage bufferedImage = new BufferedImage(reconstructedJPEG[0].length, reconstructedJPEG.length, BufferedImage.TYPE_INT_RGB);
//loop through redPixels[][] array
for(int row=0; row<redPixels.length; row++){
for(int col=0; col<redPixels[0].length; col++){
//call setRGB() on redPixels
bufferedImage.setRGB(col, row, (redPixels[row][col]));
}
}

上面的代码有效,但我不确定如何设置绿色和蓝色像素阵列?现在,它是一个非常暗淡的暗红色/紫色图像,看起来不像原始图像。

此外,是否还有其他方法可以将这些数组形成一维图像(将其原始像素、红+绿+蓝分量合并为一个整数?

谢谢,任何帮助都会很棒。

最佳答案

使用按位运算符将 3 个 channel (红色、绿色和蓝色)的各个颜色值组合到一个像素中:

int rgb = (redValue & 0xff) << 16 | (greenValue & 0xff) << 8 | (blueValue & 0xff);

然后以合成值作为参数调用setRGB:

bufferedImage.setRGB(col, row, rgb);

按位运算语句乍一看可能很麻烦,但它做了以下事情:

  • 获取每个 channel 值并使用 & 0xff 掩码使其成为基于 8 位范围的值 (0, 255)(格式 BufferedImage.TYPE_INT_RGB 期望 channel 为 8 位值)

    redValue & 0xff, greenValue & 0xff, blueValue & 0xff

  • 使用以下布局将 channel 值打包成一个 32 位整数:

    enter image description here

关于java - 使用 BufferedImage 在 Java 中创建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176202/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com