[英]How to draw points and save the output image in Java?
我試圖用x和y坐標繪制一些點,並將輸出保存到圖像文件,但我不能。 (沒有必要在JFrame上看到它們)據我通過搜索學習,我可以創建繪圖並在JFrame上顯示它但我無法將此輸出保存到文件中。
public static void main(String[] args) {
try {
final JFrame frm = new JFrame("Points");
final Panel pnl = new Panel();
pnl.setPreferredSize(new Dimension(1000, 1000));
frm.setContentPane(pnl);
frm.pack();
frm.setVisible(true);
frm.repaint();
Image img;
img = frm.createImage(1000, 1000);
ImageIO.write((RenderedImage) img, "jpeg", new File("C:/.../p.jpeg"));
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (final Exception e) {
e.printStackTrace();
}
}
public static class Panel extends JPanel {
@Override
public void paintComponent(final Graphics g) {
g.setColor(Color.RED);
for (final Point p : CandidatePoints) {
g.fillRect((int) p.getX() * 10, (int) p.getY() * 10, 20, 20);
}}
此外,我嘗試了使用ImageIO的BufferedImage的流行解決方案,但在這種情況下,我無法創建坐標系,而是在圖像文件中有一個黑色矩形。
public static void main(String[] args) {
BufferedImage bimage = new BufferedImage(200, 200,
BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g2d = bimage.createGraphics();
g2d.setColor(Color.red);
for (final Point p : CandidatePoints) {
g2d.fillRect((int) p.getX() * 10, (int) p.getY() * 10, 20, 20);
ImageIO.write(bimage, "jpeg", new File("C:/.../p.jpeg"));
g2d.dispose();
}}
先感謝您
您不需要任何Swing組件來創建映像並將其保存到文件。
這是繪制圓圈並將其保存到文件中的一個小例子:
public class ImageExample
{
public static void main ( String[] args ) throws IOException
{
final BufferedImage image = new BufferedImage ( 1000, 1000, BufferedImage.TYPE_INT_ARGB );
final Graphics2D graphics2D = image.createGraphics ();
graphics2D.setPaint ( Color.WHITE );
graphics2D.fillRect ( 0,0,1000,1000 );
graphics2D.setPaint ( Color.BLACK );
graphics2D.drawOval ( 0, 0, 1000, 1000 );
graphics2D.dispose ();
ImageIO.write ( image, "png", new File ( "C:\\image.png" ) );
}
}
如果您需要輸出上的jpeg圖像,則可能需要使用圖像類型。
你得到黑色矩形的原因是你不用任何東西填充背景,JPEG格式不支持透明圖像 - 如果你想讓你的圖像透明,請使用PNG代替。 或者您可以使用您想要的任何顏色填充圖像背景。 同樣如評論中所述 - 並非所有圖像類型都適用於不同的輸出圖像格式。
此外,以防萬一 - 所有圖像和組件的坐標都從左上角([0,0]坐標)開始。
如果您想將部分桌面Swing應用程序UI保存到圖像文件中,則需要使用Swing組件提供的方法將它們繪制到圖形上,從圖像中檢索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.