【问题标题】:Draw Graphics2D Shape onto an Image在图像上绘制 Graphics2D 形状
【发布时间】:2018-07-23 06:45:36
【问题描述】:

以下是一个更大程序的 sn-p,其目标是在图像上绘制一个红色圆圈。

我用来完成此任务的资源来自以下网站

Create a BufferedImage from an Image

Drawing on a BufferedImage

这就是我所拥有的

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class main {
    public static void main(String[] args) throws IOException {
        Image img = new ImageIcon("colorado.jpg").getImage();
        BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bi.getGraphics();



        g2d.setColor(Color.red);
        g2d.fill(new Ellipse2D.Float(0, 0, 100, 100));

        g2d.drawImage(img, 0,0,null);
        g2d.dispose();

        ImageIO.write(bi, "jpg", new File("new.jpg"));
        }

    }

但是,当代码运行时,创建的输出图像是输入图像的精确副本,没有任何更改。

【问题讨论】:

  • 将绘画视为真实世界的画布。如果你画一些东西,然后在上面画,你想看看先画的是什么

标签: java image awt bufferedimage graphics2d


【解决方案1】:

通过软件绘画类似于在现实世界中的画布上绘画。如果你画了一些东西,然后在它上面画,它会在先画的东西上画。做事的顺序很重要。

因此,在您的原始代码中,您必须绘制图像和椭圆...

g2d.drawImage(img, 0,0,null);
g2d.fill(new Ellipse2D.Float(0, 0, 100, 100));

现在,说了这么多。有一个更简单的解决方案。而不是使用有问题的ImageIcon。您可以使用ImageIO.read 来加载图像。直接的好处是,你会得到一个BufferedImage

//Image img = new ImageIcon("colorado.jpg").getImage();
//BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
BufferedImage bi = ImageIO.read(new File("colorado.jpg"));
Graphics2D g2d = bi.createGraphics();

g2d.setColor(Color.red);
g2d.fill(new Ellipse2D.Float(0, 0, 100, 100));
g2d.dispose();

ImageIO.write(bi, "jpg", new File("new.jpg"));

另外,看看Reading/Loading an Image

【讨论】:

  • @haraldK 是的,复制粘贴
猜你喜欢
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多