Java - 向大图像添加填充
我需要在大图像周围添加特定的填充,而我当前使用的方法(如下面的代码片段所示)正在耗尽内存。打开 PNG 会立刻占用约 300mb 的内存,而制作一个副本则需要超过 700mb,所以我正在寻找一种方法来做到这一点,而不占用所有可用内存。有什么建议吗?
...
BufferedImage img = ImageIO.read(new File("OldWorld.png"));
BufferedImage img2 = new BufferedImage(img.getHeight()+padding,img.getWidth()+padding, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img2.createGraphics();
g2.setPaint(new Color(0,0,0,0);
g2.fillRect(0, 0, img.getHeight()+padding, img.getWidth()+padding);
g2.drawImage(img, img.getHeight(),img.getWidth(), null);
...
I need to add specific padding around large images and the current method I am using, as seen in the snippet below, is eating up memory. Opening the PNG sucks up ~300mb of memory right off the bat and making a copy of that pushes me past 700mb so I am looking for a way to do this without sucking up all available memory. Any suggestions?
...
BufferedImage img = ImageIO.read(new File("OldWorld.png"));
BufferedImage img2 = new BufferedImage(img.getHeight()+padding,img.getWidth()+padding, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img2.createGraphics();
g2.setPaint(new Color(0,0,0,0);
g2.fillRect(0, 0, img.getHeight()+padding, img.getWidth()+padding);
g2.drawImage(img, img.getHeight(),img.getWidth(), null);
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有直接的方法可以解决这个问题。
在 Java 中处理大图像会消耗大量内存。
一些替代方案是:
使用 netpbm 库预处理图像
http://netpbm.sourceforge.net/。
要填充图像,请使用如下命令:
减少图像中的颜色数量,以便可以使用图像类型
BufferedImage.TYPE_INDEXED
每个像素只有一个字节,而不是四个。使用多个图块而不是单个大图像并工作
一次使用一块瓷砖。然后你就避免了太多的图像
内存中的数据。
There is no direct way to solve this.
Working with large images in Java consumes a lot of memory.
Some alternatives are:
Pre-process your images with the netpbm library
http://netpbm.sourceforge.net/.
To pad an image use a command like:
Reduce the number of colors in your image so that you can use image type
BufferedImage.TYPE_INDEXED
with only one byte per pixel instead of four.Use a several tiles instead of a single large image and work
with one tile at a time. Then you avoid having a lot of image
data in memory.