开发者

Java - Add padding to large images

开发者 https://www.devze.com 2023-03-15 14:20 出处:网络
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

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()+paddi开发者_如何学Pythonng, img.getWidth()+padding);
g2.drawImage(img, img.getHeight(),img.getWidth(), null);
...


There is no direct way to solve this. Working with large images in Java consumes a lot of memory.

Some alternatives are:

  1. Pre-process your images with the netpbm library http://netpbm.sourceforge.net/. To pad an image use a command like:

    pngtopnm OldWorld.png | pnmpad -black 48 -left 48 -top 48 | pnmtopng > padded.png
    
  2. 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.

  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号