gpt4 book ai didi

java - 如何读取图像,在其上绘制内容并保存结果?

转载 作者:行者123 更新时间:2023-12-01 23:07:08 25 4
gpt4 key购买 nike

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

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

}

最佳答案

试试这个。

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

}

关于java - 如何读取图像,在其上绘制内容并保存结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594495/

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