Search code examples
javagraphics2d

Graphics2D rotate before saving file


I create this image with g2d:

enter image description here

Here is the code:

BufferedImage bufferedImage = new BufferedImage(408, 408, BufferedImage.TYPE_INT_RGB);    
Graphics2D g2d = bufferedImage.createGraphics();
List<Pixel> pixels = cacheRepo.findAll();
pixels.stream().forEach(pixel -> {
    g2d.setColor(getColorFromPixel(pixel));
    g2d.fillRect(getPos(pixel.getPosition().x), getPos(pixel.getPosition().y), 20, 20);
});

Now I am trying to rotate it 90° anticlok so that the bleu square appear on the lower left:

enter image description here

So I add this:

g2d.rotate(Math.toRadians(90));
g2d.drawRenderedImage(bufferedImage, null);

But the rotation doesn't occur (I still have the same image).

Here is the complete piece of code, with the part that save image:

 // Constructs a BufferedImage of one of the predefined image types.
    BufferedImage bufferedImage = new BufferedImage(408, 408, BufferedImage.TYPE_INT_RGB);
    // Create a graphics which can be used to draw into the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();
    List<Pixel> pixels = cacheRepo.findAll();
    pixels.stream().forEach(pixel -> {
        g2d.setColor(getColorFromPixel(pixel));
        g2d.fillRect(getPos(pixel.getPosition().x), getPos(pixel.getPosition().y), 20, 20);
    });
    g2d.rotate(Math.toRadians(90));
    g2d.drawRenderedImage(bufferedImage, null);
    g2d.dispose();
    // Save as PNG
    File file = new File("myimage.png");
    try {
        ImageIO.write(bufferedImage, "png", file);
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution

  • Transformations should be applied BEFORE any operations you want to be effected by them, transformations won't affect anything that was done before it...

    BufferedImage bufferedImage = new BufferedImage(408, 408, BufferedImage.TYPE_INT_RGB);
    // Create a graphics which can be used to draw into the buffered image
    Graphics2D g2d = bufferedImage.createGraphics();
    g2d.rotate(Math.toRadians(90));
    List<Pixel> pixels = cacheRepo.findAll();
    pixels.stream().forEach(pixel -> {
        g2d.setColor(getColorFromPixel(pixel));
        g2d.fillRect(getPos(pixel.getPosition().x), getPos(pixel.getPosition().y), 20, 20);
    });
    //g2d.rotate(Math.toRadians(90));
    // Not sure what you're hoping to achieve here
    //g2d.drawRenderedImage(bufferedImage, null);
    g2d.dispose();
    

    If you prefer, use two BufferedImages. Render the "normal" content to the first, then use the second to paint the first, but with a rotation transformation ... because transformations do my head in 😝

    using your code draw a black image

    You probably need to supply a anchor point around which the image can be rotated, otherwise it will be rated about the top/left corner

    And you'll forgive me, but it's not like this kind of think hasn't been asked before