简体   繁体   English

将Graphics2D Shape绘制到图像上

[英]Draw Graphics2D Shape onto an Image

The following is a snippet from a larger program, where the goal is to draw a red circle onto an image. 以下是一个较大程序的摘录,目标是在图像上绘制一个红色圆圈。

The resources I am using to accomplish this are from the following to sites 我用于完成此任务的资源来自以下站点

Create a BufferedImage from an Image 从图像创建BufferedImage

and

Drawing on a BufferedImage 在BufferedImage上绘制

This is what I have 这就是我所拥有的

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

    }

However when the code is ran the outputting image created is an exact copy of the input image with no alterations. 但是,在运行代码时,创建的输出图像是输入图像的精确副本,没有任何更改。

Painting through software is similar to painting on a canvas in the real world. 通过软件绘画类似于在现实世界中的画布上绘画。 If you paint something, then paint over it, it will paint over what was painted first. 如果您绘画某些东西,然后在其上绘画,它将在先绘画的东西上绘画。 The order in which you do things is very important. 做事的顺序非常重要。

So, in your original code, you'd have to paint the image and the ellipse... 因此,在原始代码中,您将不得不绘制图像和椭圆形...

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

Now, having said that. 现在,话虽如此。 There is an easier solution. 有一个更简单的解决方案。 Instead of using ImageIcon , which has issues. 代替使用ImageIcon ,它有问题。 You can just use ImageIO.read to load the image. 您可以只使用ImageIO.read加载图像。 The immediate benefit is, you get a BufferedImage 直接的好处是,您获得了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"));

Also, take a look at Reading/Loading an Image 另外,看看读取/加载图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM