Guidance on the BufferedImage.getSubimage(int x, i

2019-06-28 08:43发布

问题:

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

  1. Read in the image using the ImageIO.read(File file) method
  2. Split the images up using the getSubimage() method as follows:

bufferedImage.getSubimage(300, 300, bufferedImage.getWidth() / columns, bufferedImage.getHeight() / rows);

  1. 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!

回答1:

This is a bug with Java. I believe it is fixed in JDK 7 but I am not 100% sure (I think the actually fix was reviewed sometime in september)

http://bugs.sun.com/view_bug.do?bug_id=6795544