写灰度图出错

Error in writing a grayscale image

在下面的代码中,我尝试读取灰度图像,将像素值存储在二维数组中,然后用不同的名称重写图像。 代码是

    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

如何消除这个写灰度图的错误?

我发现了这个:"ArrayStoreException -- if an element in the src array could not be stored into the dest array because of a type mismatch." http://www.tutorialspoint.com/java/lang/system_arraycopy.htm

两个想法:

  1. 您正在将一个整数数组复制到一个字节数组中。
  2. 这不属于例外情况,但尺寸是否正确? arr是二维数组,raster1是一维数组。

而且您不能只更改二维数组中的字节数组而忽略您正在调用的方法的输出。

像这样将 int[][] arr 更改为 byte[] arr

    byte[] arr = new byte[width * height * 4];
    for (int i = 0, z = 0; i < width; i++) {
        for (int j = 0; j < height; j++, z += 4) {
            int v = getSample(i, j, 0);
            for (int k = 3; k >= 0; --k) {
                arr[z + k] = (byte)(v & 0xff);
                v >>= 8;
            }
        }
    }