0

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)
1
  • Trying to access array element at index 77120 where as array has elements till 76800, you can try initialise array with length 77120 or more Commented Apr 3, 2021 at 1:18

1 Answer 1

1

You're using an int array. Each pixel takes up 4 bytes then; RGB covers 3 of em, and the 4th is discarded. That way, it's 1 int = 1 pixel, vs. some bizarro packing algorithm.

Fix it by not using int arrays, or by manually injecting a 4th ignored byte.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.