【问题标题】:How to draw points and save the output image in Java?如何在 Java 中绘制点并保存输出图像?
【发布时间】:2017-02-16 11:46:08
【问题描述】:

我正在尝试使用 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();
        }}

提前谢谢你

【问题讨论】:

标签: java swing jpanel bufferedimage javax.imageio


【解决方案1】:

您不需要任何 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。或者你可以用你想要的任何颜色填充图像背景。此外,正如 cmets 中提到的 - 并非所有图像类型都适用于不同的输出图像格式。

另外,以防万一 - 所有图像和组件的坐标都从左上角开始([0,0] 坐标)。

如果您想将桌面 Swing 应用程序 UI 的一部分保存到图像文件中,您将需要使用 Swing 组件提供的方法将它们绘制到从图像中检索的图形上。

【讨论】:

  • 这正是我所需要的。谢谢,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多