在以下代碼中,我試圖讀取灰度圖像,將像素值存儲在二維數組中,並用不同的名稱重寫圖像。 代碼是寫入灰度圖像時出錯
package dct;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.io.File;
import javax.imageio.ImageIO;
public class writeGrayScale
{
public static void main(String[] args)
{
File file = new File("lightning.jpg");
BufferedImage img = null;
try
{
img = ImageIO.read(file);
}
catch(Exception e)
{
e.printStackTrace();
}
int width = img.getWidth();
int height = img.getHeight();
int[][] arr = new int[width][height];
Raster raster = img.getData();
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
arr[i][j] = raster.getSample(i, j, 0);
}
}
BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY);
byte[] raster1 = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(arr,0,raster1,0,raster1.length);
//
BufferedImage image1 = image;
try
{
File ouptut = new File("grayscale.jpg");
ImageIO.write(image1, "jpg", ouptut);
}
catch(Exception e)
{
e.printStackTrace();
}
}// main
}// class
對於此代碼,錯誤的是
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at dct.writeGrayScale.main(writeGrayScale.java:49)
Java Result: 1
如何消除這種錯誤寫的灰度圖像?
你試圖從一個二維數組複製('INT [] [] arr')轉換成一維('字節[] raster1'),這可能是造成問題的原因。 –
好的......我試着讓byte [] [] ..它的方法的語法錯誤看起來...任何幫助重寫語句「byte [] raster1 =((DataBufferByte)image.getRaster()。getDataBuffer ())。getData();「.. –