代码之家  ›  专栏  ›  技术社区  ›  Tyvain

保存文件前先旋转graphics2d

  •  0
  • Tyvain  · 技术社区  · 6 年前

    我用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度,使布鲁广场出现在左下角:

    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();
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   MadProgrammer    6 年前

    转换应该在您希望受其影响的任何操作之前应用,转换不会影响之前所做的任何操作…

    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 . 将“正常”内容渲染到第一个,然后使用第二个来绘制第一个,但使用旋转变换…因为我的脑袋在变形

    使用代码绘制黑色图像

    您可能需要提供一个可以旋转图像的定位点,否则将在顶部/左角进行评级。

    你会原谅我的,但这种想法以前从来没有人问过。