2021年4月2日星期五

Problem saving an int array as an image in Java

I am trying to manipulate an image by first manipulating its data elements as bytes, and the saving it back as a RGB. The image size is 320x320x3 (rgb).

import java.io.File;  import java.io.IOException;  import java.awt.image.BufferedImage;  import javax.imageio.ImageIO;  import java.awt.image.DataBufferByte;  import java.io.ByteArrayInputStream;  import java.io.InputStream;  import java.nio.IntBuffer;  import java.nio.ByteBuffer;  import java.nio.ByteOrder;    class sobel_java {      public static void main(String args[]){                    BufferedImage image = null;          try{              image = ImageIO.read(new File("butterfinger.jpg"));              final byte[] image_pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();              final int image_height = image.getHeight();              final int image_width = image.getWidth();              System.out.println(image_height);              System.out.println(image_width);                    BufferedImage out_image = new BufferedImage(image_width, image_height, BufferedImage.TYPE_INT_RGB);              /* Create an int array that contains image_pixels. */                 IntBuffer intBuf = ByteBuffer.wrap(image_pixels).order(ByteOrder.BIG_ENDIAN).asIntBuffer();               int[] array = new int[intBuf.remaining()];              intBuf.get(array);              /* Write the int array to BufferedImage. */              out_image.getRaster().setDataElements(0, 0, image_width, image_height, array);              /* Save the image. */              ImageIO.write(out_image, "jpg", new File("out.jpg"));                              }catch(IOException e){          System.out.println(e);      }      }  }  

In runtime, I get the following error,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: last source index 77120 out of bounds for int[76800]      at java.base/java.lang.System.arraycopy(Native Method)      at java.desktop/sun.awt.image.IntegerInterleavedRaster.setDataElements(IntegerInterleavedRaster.java:425)      at sobel_java.main(sobel_java.java:30)  
https://stackoverflow.com/questions/66926876/problem-saving-an-int-array-as-an-image-in-java April 03, 2021 at 09:07AM

没有评论:

发表评论