我目前正在尝试分割一张图片,但遇到了问题,不知道为什么会出现这种情况。
以下是我的函数的伪代码:
- 使用ImageIO.read(File file)方法读取图像
- 使用getSubimage()方法将图像分割如下:
bufferedImage.getSubimage(300, 300, bufferedImage.getWidth() / columns, bufferedImage.getHeight() / rows);
- 使用ImageIO.write()方法将其写入图像目录。
问题在于程序似乎无法正确读取int x和int y参数。例如,使用上述参数300, 300作为参数,但是它似乎不是从坐标300, 300裁剪,而是从0, 0开始裁剪,无论输入什么值都是如此。
有什么建议吗?
谢谢!
顺便说一句,这是我的方法代码:
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!");
}
}
看起来问题不是方法的问题,而是文件格式的问题。使用GIF格式时,它无法正常工作。但使用JPEG格式时,可以正常工作。
有人可以解释一下为什么吗?
谢谢!