如何阅读图像,在其上绘制一些东西并保存结果?

时间:2014-03-23 17:36:28

标签: java swing file-io jpanel paintcomponent

我想阅读一些Image,然后在其上绘制一些形状并将形状保存为新文件。我尝试做类似的事情,但它不起作用。

public class Test extends JPanel{

private static BufferedImage br;

public static void main(String[] args) {
    try {
        br=ImageIO.read(new File("rys1.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawImage(br,0,0,this);
    g.drawRect(20, 20, 10, 10);
    g.setColor(Color.BLACK);
    try {
        ImageIO.write(br, "png", new File(("D:\\test\\rys"+2)));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:3)

试试这个。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class DrawShapeOnImage {

    private static BufferedImage br;

    public static void main(String[] args) throws IOException {
        try {
            br = ImageIO.read(new File("resources/1.png"));
            ImageIO.write(getTexturedImage(), "png", new File("resources/2.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage getTexturedImage() {
        BufferedImage tmp = new BufferedImage(br.getWidth(), br.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = tmp.createGraphics();
        g.drawImage(br, 0, 0, null);
        g.setColor(Color.BLACK);
        g.drawRect(20, 20, 10, 10);
        g.dispose();

        return tmp;
    }

}