Graphics2D 在保存文件前旋转

Graphics2D rotate before saving file

我用 g2d 创建这个图像:

代码如下:

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);
});

现在我试着将它旋转 90°,使蓝色方块出现在左下方:

所以我添加这个:

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

但是没有发生旋转(我仍然有相同的图像)。

完整代码如下,保存图片部分:

 // 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();
    }

应在您希望受其影响的任何操作之前应用转换,转换不会影响之前完成的任何操作...

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();

如果您愿意,可以使用两个 BufferedImages。将 "normal" 内容渲染到第一个,然后使用第二个来绘制第一个,但要进行旋转变换……因为变换在

中起作用

using your code draw a black image

您可能需要提供一个图像可以围绕其旋转的锚点,否则它将被评为 top/left 角

你会原谅我的,但这种想法以前也不是没问过

  • Rotate a buffered image in Java
  • Rotating Image with AffineTransform
  • How to save rotated buffered image in another buffered image?
  • BufferedImage rotated, change resulting background