Kad*_*dir 2 java swing bufferedimage jpanel javax.imageio
我试图用 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);
}}
Run Code Online (Sandbox Code Playgroud)
此外,我已经尝试过使用 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();
}}
Run Code Online (Sandbox Code Playgroud)
先感谢您
您不需要任何 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" ) );
}
}
Run Code Online (Sandbox Code Playgroud)
如果您在输出中需要精确的 jpeg 图像,则可能需要使用图像类型。
你得到黑色矩形的原因是你没有用任何东西填充背景并且 JPEG 格式不支持透明图像——如果你想让你的图像透明,例如使用 PNG。或者您可以只用您想要的任何颜色填充图像背景。同样正如评论中提到的那样 - 并非所有图像类型都适用于不同的输出图像格式。
此外,以防万一 - 所有图像和组件的坐标都从左上角([0,0] 坐标)开始。
如果您想将桌面 Swing 应用程序 UI 的一部分保存到图像文件中,您将需要使用 Swing 组件提供的方法将它们绘制到图形上,从图像中检索。
| 归档时间: |
|
| 查看次数: |
3562 次 |
| 最近记录: |