Long story short, I want to get the int[] array of RGB values from a BufferedImage
The original BufferedImage is called startImage, for which the RGB values go into startPixels
Next I have another int array called endPixels, and an image called endImage. When the program is done, endPixels will be dithered from startPixels but for the time being they are identical.
Then I want endPixels to be converted to endImage, which is then written to a file.
Here is the code:
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class DitherMain {
static String imageString = "/IMG_3462.jpg";
BufferedImage startImage, endImage;
int[] startPixels,endPixels;
int width, height;
public static void main(String[] args){
new DitherMain(loadImage(imageString));
}
//this object transforms the old image and writes the new image
DitherMain(BufferedImage img){
//filing the image into startpixels (this works)
startImage = img;
width = img.getWidth();
height = img.getHeight();
startPixels = new int[width*height];
img.getRGB(0, 0, width, height, startPixels, 0, width);
transformPixels();
//putting endPixels in endImage (does not work)
endImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = (WritableRaster) endImage.getData();
raster.setPixels(0,0,width,height,endPixels);
//writing the file for endImage into the harddrive (may or may not work)
File file = new File("/RESULT.png");
try {
ImageIO.write(endImage, "jpg", file);
} catch (IOException e) {
e.printStackTrace();
}
}
void transformPixels(){
//endPixels will one day be different from startPixels, but for now it is idenitcial
endPixels = startPixels;
}
//this method just loads a specific buffered image
public static BufferedImage loadImage(String fileName){
BufferedImage img;
try{
img = ImageIO.read(DitherMain.class.getResource(fileName));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return img;
}
}
And got this error message in the console:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1228800
at java.awt.image.SinglePixelPackedSampleModel.setPixels(Unknown Source)
at java.awt.image.WritableRaster.setPixels(Unknown Source)
at sun.awt.image.SunWritableRaster.setPixels(Unknown Source)
at DitherMain.(DitherMain.java:34)
at DitherMain.main(DitherMain.java:17)
Line 34 is
raster.setPixels(0,0,width,height,endPixels);
But I don’t see what’s wrong with this… does it have to do with storing an ARGB as an int, because I have no idea.
It says some array is going out of bounds. 1228800 is the height*width of the test image I’m using, but I don’t see what should be out of bounds
I really don’t understand what the problem with this code is, but seeing as I’ve never written something like this before I assume there are probably a lot.
In any case, can any of you guys shed some light on this?
Thanks