简体   繁体   中英

Java - Add padding to large images

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);
...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM