Converting a single column of a BufferedImage into a new BufferedImage

45 Views Asked by At

I want to take a BufferedImage (in this case it is 3600x3600) and take the first column of pixels and create a new BufferedImage out of that (creating an image 1x3600), here is the code I have:

BufferedImage originalImage = ImageUtilities.readImageFile("C:/someImage.png");
int[] columnData = new int[originalImage.getHeight()];
originalImage.getRGB(0, 0, 1, originalImage.getHeight(), columnData, 0, 1);
BufferedImage columnImage = new BufferedImage(1, originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = columnImage.getRaster();
raster.setPixels(0, 0, 1, originalImage.getHeight(), columnData);

But I keep getting the following exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3600
    at java.awt.image.SinglePixelPackedSampleModel.setPixels(Unknown Source)
    at java.awt.image.WritableRaster.setPixels(Unknown Source)

Could someone tell me what am I doing wrong, please?

2

There are 2 best solutions below

0
Reilas On

You can use the Graphics class to copy an area of an image.

Here is an example.
I'm using the following image.
https://apod.nasa.gov/apod/image/2309/STSCI-HST-abell370_1797x2000.jpg.

Here is the JavaDoc for the drawImage method.
Graphics#drawImage (Java SE 20 & JDK 20).

BufferedImage image = ImageIO.read(new File("STSCI-HST-abell370_1797x2000.jpg"));
int w = 1, h = 2000;
BufferedImage cropped = new BufferedImage(w, h, image.getType());
Graphics g = cropped.createGraphics();;
g.drawImage(image, 0, 0, w, h, 0, 0, w, h, null);
g.dispose();
ImageIO.write(cropped, "jpg", new File("STSCI-HST-abell370_cropped.jpg"));
0
cdubbs On

Thank you @MadProgrammer, I ended up using artwork.getSubimage(0,0,1,artwork.getHeight()), which did the trick!