I'm currently attempting to split an image, and I ran into a snitch and I have no idea why it's happening.
Here's a quick pseudo code breakdown of my function
- Read in the image using the ImageIO.read(File file) method
- Split the images up using the getSubimage() method as follows:
bufferedImage.getSubimage(300, 300, bufferedImage.getWidth() / columns, bufferedImage.getHeight() / rows);
- Write it to the images directory using the ImageIO.write() method.
The problem is that the int x and int y parameters don't seem to be read correctly by the program. For example, with 300, 300 as the arguments above, but it doesn't seem to crop from the coordinates 300, 300, but rather from 0, 0 regardless of what values you input.
Any suggestions!
Thanks!
Btw, here's the code in my method:
public static void splitImage(String imageFileName, String format, int rows, int columns) {
// Load the image file
File imageFile = new File(imageFileName);
try {
BufferedImage bufferedImage = ImageIO.read(imageFile);
// Split the image up into corresponding number of sub-images
BufferedImage[][] splitImages = new BufferedImage[rows][columns];
for (int i = 0; i < splitImages.length; i++) {
for (int j = 0; j < splitImages[i].length; j++) {
splitImages[i][j] = bufferedImage.getSubimage(bufferedImage.getWidth() / columns * i, bufferedImage.getHeight() / rows * j,
bufferedImage.getWidth() / columns, bufferedImage.getHeight() / rows);
}
}
System.out.println(bufferedImage.getWidth() / columns + "\n" + bufferedImage.getHeight() / rows);
splitImages[0][0] = bufferedImage.getSubimage(300, 300,
bufferedImage.getWidth() / columns * 2, bufferedImage.getHeight() / rows * 2);
// Write that into the images directory
for (int i = 0; i < splitImages.length; i++) {
for (int j = 0; j < splitImages[i].length; j++) {
imageName++;
ImageIO.write(splitImages[i][j], format, new File("images/" + imageName + "." + format));
}
}
ImageIO.write(splitImages[0][0], format, new File("images/" + imageName + "." + format));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "The image file doesn't exist!");
}
}
It seems that it wasn't the method's problem as it was the file format's problem. With GIFs, it didn't work. With JPEGs, it worked fine.
Can somebody explain why?
Thanks!