gpt4 book ai didi

java - 无法将 java.awt.image 转换为 int[][][]

转载 作者:行者123 更新时间:2023-11-30 05:15:33 25 4
gpt4 key购买 nike

我已经编写了一个类,用于在 Java 程序中进行图像处理。该类无法正确加载图像,“数据”字段的格式为 [行][列][a=0,r=1,g=2,b=3]。当我尝试加载图像时,数据被 0 填充。

public class Image {
public int[][][] data;

public int width;
public int height;
Image(int width, int height, java.awt.Color color) {
this.data = new int [height][width][4];
}
Image(java.lang.String path) {
this.load(path);
}
public void load(java.lang.String path) {
java.awt.Image image = new javax.swing.ImageIcon(path).getImage();
int[][][] data = new int[image.getHeight(null)][image.getWidth(null)][4];
int[] oneDPix = new int[image.getHeight(null) * image.getWidth(null)];

this.width = image.getWidth(null);
this.height = image.getHeight(null);

java.awt.image.PixelGrabber pixelGrabber = new java.awt.image.PixelGrabber(image, 0, 0, image.getWidth(null), image.getHeight(null), oneDPix, 0, image.getWidth(null));

for(int row = 0; row < image.getHeight(null); row++) {
int[] aRow = new int[image.getWidth(null)];
for(int col = 0; col < image.getWidth(null);col++) {
int element = row * image.getWidth(null) + col;
aRow[col] = oneDPix[element];
}
for(int col = 0;col < image.getWidth(null);col++){
data[row][col][0] = (aRow[col] >> 24)& 0xFF;
data[row][col][1] = (aRow[col] >> 16) & 0xFF;
data[row][col][2] = (aRow[col] >> 8) & 0xFF;
data[row][col][3] = (aRow[col]) & 0xFF;
}
}
this.data = data;
}
public void save(java.lang.String path) throws java.io.IOException{
int[] oneDPix = new int[this.width * this.height * 4];
for(int row = 0, cnt = 0; row < this.height; row++){
for(int col = 0; col < this.width; col++) {
oneDPix[cnt] = ((this.data[row][col][0] << 24)
& 0xFF000000)
| ((this.data[row][col][1] << 16)
& 0x00FF0000)
| ((this.data[row][col][2] << 8)
& 0x0000FF00)
| ((this.data[row][col][3])
& 0x000000FF);
cnt++;
}
}
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit()
.createImage(new java.awt.image.MemoryImageSource
(width, height,oneDPix, 0, width));

java.io.File imagefile = new java.io.File(path);
String ext = ".png";
java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage
(this.width, this.height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
bufferedImage.getGraphics().drawImage(image, 0, 0, null);
javax.imageio.ImageIO.write(bufferedImage, ext,imagefile);

}
}

我做错了什么?

最佳答案

您的第一个问题是您没有启动 PixelGrabber,因此在创建 PixeGrabber 后添加以下内容:

try {
pixelGrabber.grabPixels();
} catch (InterruptedException e) {
e.printStackTrace();
}

第二个问题是当你调用createImage()时,它会创建宽度和高度为-1的图像。所以输出是零长度文件。

编辑。要写入图像,请使用“png”而不是“.png”作为扩展名

关于java - 无法将 java.awt.image 转换为 int[][][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1548602/

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