Sunday, December 20, 2015

Reading and writing huge PNG files from Java

The PNGJ library allow reading and writing larger PNG files. ImageIO usually needs much more memory due to the use of intermediate image buffers.

Example:

import ar.com.hjg.pngj.*;

BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(ifile)); 
try {
  ImageInfo imi = new ImageInfo(mp.wres, mp.hres, 8, false);
  PngWriter pngw = new PngWriter(os, imi);
  pngw.setCompLevel(9); // tuning
  pngw.setFilterType(FilterType.FILTER_PAETH); // tuning
  ImageLineInt line = new ImageLineInt(imi);
  int pixelIndex = 0;
  for (int row = 0; row < imi.rows; row++) {
    for (int col = 0; col < imi.cols; col++) {
      int sample = gb.pixels[pixelIndex++];
      ImageLineHelper.setPixelRGB8(line, col, (sample & 0xFF0000)>>16, (sample & 0xFF00)>>8, (sample & 0xFF));
    }
    pngw.writeRow(line, row);
  }
  pngw.end();
}
finally {
  os.close();
}

No comments:

Post a Comment