Search code examples
javamultidimensional-arrayrotationsavebufferedimage

Java - Problem with saving buffered image to file rotates 90 degrees


I've been trying to complete a method that saves Color[][] to jpg image files, however the solutions will result in the output file being rotate 90 degrees, I've tried looking for the problem but does not come obvious to me, as well as other people with similar solutions doesn't seem to have the same problems.

Any help is greatly appreciated!

private Color[][] image;  //  assume this field has already been populated

public  void saveImage() {
    BufferedImage saveImage = new BufferedImage(this.image.length, 
                                                this.image[0].length, 
                                                BufferedImage.TYPE_INT_RGB);
    for (int row = 0; row < this.image.length; row++) {
        for (int col = 0; col < this.image[row].length; col++) {
            saveImage.setRGB(row, col, this.image[row][col].getRGB());
        }
    }

    String fName = UIFileChooser.save();
    if (fName==null){return;}

    File toFile = new File(fName+".jpg");

    try {
        ImageIO.write(saveImage,"jpg", toFile);
    }catch (IOException e){UI.println("File save error: "+e);}
}

thanks for the helps, it turns out I just had to flip the dimensions and x/y coordinates, below is the fixed version:

private Color[][] image;  //  assume this field has already been populated

public  void saveImage() {
    BufferedImage saveImage = new BufferedImage(this.image[0].length, 
                                                this.image.length, 
                                                BufferedImage.TYPE_INT_RGB);
    for (int row = 0; row < this.image.length; row++) {
        for (int col = 0; col < this.image[row].length; col++) {
            saveImage.setRGB(col, row, this.image[row][col].getRGB());
        }
    }

    String fName = UIFileChooser.save();
    if (fName==null){return;}

    File toFile = new File(fName+".jpg");

    try {
        ImageIO.write(saveImage,"jpg", toFile);
    }catch (IOException e){UI.println("File save error: "+e);}
}

Solution

  • The signature of the BufferedImage.setRGB method is public void setRGB​(int x, int y, int rgb)

    X comes first, then Y. row equals y and col equals x.

    So change that line to:

    saveImage.setRGB(col, row, this.image[row][col].getRGB());