gpt4 book ai didi

java - 保存文件之前 Graphic2D 旋转

转载 作者:行者123 更新时间:2023-11-30 01:56:58 25 4
gpt4 key购买 nike

我使用 g2d 创建此图像:

enter image description here

这是代码:

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° anticlok,以便蓝色方 block 出现在左下角:

enter image description here

所以我添加这个:

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。将“正常”内容渲染到第一个内容,然后使用第二个内容来绘制第一个内容,但要进行旋转变换...因为变换使我的头陷入了😝

using your code draw a black image

您可能需要提供一个可以围绕图像旋转的 anchor ,否则它将围绕左上角/左上角进行评级

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

关于java - 保存文件之前 Graphic2D 旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com