我正在编写一个 PNG 图像,每个像素的值为 15。当我读取书面图像时,我得到的不是 15,而是垃圾值。为什么会这样呢? 因为我想恢复相同的值,所以我选择了无损的 PNG 格式。我仍然得到垃圾值。 这是代码。
public static void main(String args[])
{
BufferedImage img = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB);
int[] RGBarray = null;
int col = 0;
int row = 0;
col = img.getWidth();
row = img.getHeight();
RGBarray = img.getRGB(0,0,col,row,null,0,col); // Now RGBarray has all the values
byte[] data = new byte[512*512];
for(int k = 0; k < 262144; k++)
{
data[k] = 15;
}
int count = 0;
for(int ro = 0; ro < 512 ; ro++)
{
for(int co = 0;co < 512; co++)
{
img.setRGB(co, ro, data[count++]);
}
}
try{
ImageIO.write(img, "png", new File("Test3.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
BufferedImage img1 = null;
File f = new File("Test3.png");
try
{
img1 = ImageIO.read(f);
}
catch(Exception e)
{
e.printStackTrace();
}
int[] RGBarray1 = null;
int col1 = 0;
int row1 = 0;
col1 = img1.getWidth();
row1 = img1.getHeight();
RGBarray1 = img1.getRGB(0,0,col1,row1,null,0,col1); // Now RGBarray has all the values
for( int p = 0; p < 5; p++)
{
for(int j = 0; j < 5 ; j++)
{
System.out.print(img1.getRGB(p,j) + "\t");
}
System.out.println("");
}
}
仅供引用,我已经打印了 5 个值来检查是否会得到 15。但输出是
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
-16777216 -16777216 -16777216 -16777216 -16777216
最佳答案
您正在写入一个byte
并读取int
。试试这个 -
System.out.print((byte)img1.getRGB(p,j) + "\t");
关于java - 为什么读取 png 图像时会出现垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34412730/