'java.awt.image.BufferedImage.getSubimage ignores x,y coordinates (jdk-11.0.9.11-hotspot)
I'm trying to divide a jpg file into 8x8 sub images. My output gives me 64 identical png files, seemingly all with coordinates (0,0). According to an older issue Issues with cropping an image using java image.getSubimage this was once a bug which was solved by upgrading to java 7. I'm using jdk-11.0.9.11-hotspot.
My code:
public static void main(String[] args) throws Exception {
int columnCount = 8;
int rowCount = 8;
String fileName = args[0];//e.g. C:\picturetest\mypicture.jpg
String fileNameNoExt = fileName.substring(0, fileName.lastIndexOf("."));
BufferedImage image = ImageIO.read(new File(fileName));
int heightFragment = image.getHeight() / rowCount;
int widthFragment = image.getWidth() / columnCount;
for (int x = 0; x < columnCount; x++) {
for (int y = 0; y < rowCount; y++) {
ImageIO.write(image
.getSubimage(x, y, widthFragment, heightFragment), "jpg", new File(fileNameNoExt + "-(" + x + "," + y + ").png"));
}
}
}
Solution 1:[1]
They are not all starting at (0,0) - but they are starting at the positions (0,0); (0,1); (0,2) and so on until the last starts at (7,7).
You want to increase the top/left coordinates not by 1, but by widthFragment and heightFragment.
One way to do this is:
for (int x = 0; x < columnCount; x++) {
for (int y = 0; y < rowCount; y++) {
ImageIO.write(image
.getSubimage(x*widthFragment, y*heightFragment, widthFragment, heightFragment), "jpg", new File(fileNameNoExt + "-(" + x + "," + y + ").png"));
}
}
Or you change the step sizes for x and y:
for (int x = 0; x < image.getWidth(); x += widthFragment) {
for (int y = 0; y < image.getHeight(); y += heightFragment) {
ImageIO.write(image
.getSubimage(x, y, widthFragment, heightFragment), "jpg", new File(fileNameNoExt + "-(" + x/widthFragment + "," + y/heightFragment + ").png"));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
