将 Graphics2D 转换为 Image 或 BufferedImage
我这里有一个小问题。
我有一个小程序,用户可以在其中“绘图”。为此,我使用 java.awt.Graphics2D。 但是,我该如何将用户绘制的图像保存为 JPEG 图像,或者至少将其转换为 BufferedImage 或其他图像?我不知道该怎么做。
谢谢。
I have a little problem here.
I have an applet, where user can "draw" inside it. To do that, I use the java.awt.Graphics2D.
But, how can I do to save the user draw image as a JPEG image, or at least, convert it to a BufferedImage or something? I don't know how to do that.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
让它们通过 Graphics2D 对象直接在 BufferedImage 中绘制,您可以通过 getGraphics() 获取该对象。然后使用 ImageIO.write(...) 将图像输出到您想要的任何文件类型(并且受支持)。 ImageIO API 应该可以帮助您:ImageIO API。
您将遇到的另一个问题是,一旦绘制了图像,他们应该将其保存在哪里?在他们自己的电脑上?如果是这样,并且这是一个小程序,那么该小程序需要“签名”才能拥有写入磁盘的权限。如果您对此不确定,请查看 Google 这篇文章,或者您可能希望单独针对此问题编写一个新问题。
编辑1:代码示例
例如:
Have them draw directly in a BufferedImage by way of it's Graphics2D object which you can get via getGraphics(). Then use
ImageIO.write(...)
to output the image to whatever file type you desire (and that's supported). The ImageIO API should help you with this: ImageIO API.The other issue you'll have is where are they supposed to save the image once it has been drawn? On their own computer? If so and this is an applet program, then the applet will need to be "signed" in order for it to have the permission to write to disk. If you're unsure on this, check out Google, this article, or you may wish to write a new question for this issue alone.
Edit 1: code example
For example:
我就是这样做的,并且效果很好:
仅此而已:)
谢谢大家:)
I do it that way, and works very well:
That's all :)
Thanks everyone :)
使用
Graphics2D
并使用ImageIO
Use the
drawImage
method provided byGraphics2D
and write it usingImageIO
使用自定义绘画方法中的“drawOnImage”示例。然后,要创建面板的图像,您可以使用屏幕图像班级。
Use the "drawOnImage" example from Custom Painting Approaches. Then to create the image of the panel you can use the Screen Image class.
如果您想将 JComponent 的图像绘制到 BufferedImage 上(JApplet 扩展 JComponent):
并将其数据写入 JPEG 文件:
If you'd like to draw JComponent's image onto BufferedImage (JApplet extends JComponent):
And to write its data to JPEG file: