use of org.libjpegturbo.turbojpeg.TJCompressor in project imageio-ext by geosolutions-it.
the class TurboJpegImageWriter method write.
@Override
public void write(IIOMetadata metadata, IIOImage image, ImageWriteParam writeParam) throws IOException {
// Getting image properties
RenderedImage srcImage = image.getRenderedImage();
srcImage = refineImage(srcImage);
final ComponentSampleModel sm = (ComponentSampleModel) srcImage.getSampleModel();
int[] bandOffsets = sm.getBandOffsets();
// Getting image Write params
TurboJpegImageWriteParam param = (TurboJpegImageWriteParam) writeParam;
// use default as needed
if (param == null) {
param = (TurboJpegImageWriteParam) getDefaultWriteParam();
}
final EXIFMetadata exif = param.getExif();
int componentSampling = param.getComponentSubsampling();
final int quality = (int) (param.getCompressionQuality() * 100);
int pf = TJ.PF_RGB;
if (bandOffsets.length == 3) {
if (componentSampling == -1) {
componentSampling = TurboJpegImageWriteParam.DEFAULT_RGB_COMPONENT_SUBSAMPLING;
}
if ((bandOffsets[0] == 2) && (bandOffsets[2] == 0)) {
pf = TJ.PF_BGR;
}
} else if (bandOffsets.length == 1 && componentSampling == -1) {
pf = TJ.PF_GRAY;
componentSampling = TJ.SAMP_GRAY;
} else {
throw new IllegalArgumentException("TurboJPEG won't work with this type of sampleModel");
}
if (componentSampling < 0) {
throw new IOException("Subsampling level not set");
}
final int pixelsize = sm.getPixelStride();
final int width = srcImage.getWidth();
final int height = srcImage.getHeight();
final int pitch = pixelsize * width;
TJCompressor compressor = null;
try {
// final long jsize = TurboJpegUtilities.bufSize(width, height);
Rectangle rect = new Rectangle(srcImage.getMinX(), srcImage.getMinY(), srcImage.getWidth(), srcImage.getHeight());
Raster data = srcImage.getData(rect);
final byte[] inputImageData = ((DataBufferByte) data.getDataBuffer()).getData();
final byte[] outputImageData;
try {
compressor = new TJCompressor();
compressor.setSourceImage(inputImageData, width, pitch, height, pf);
compressor.setJPEGQuality(quality);
compressor.setSubsamp(componentSampling);
outputImageData = compressor.compress(TJ.FLAG_FASTDCT);
} catch (Exception ex) {
throw new IOException("Error in turbojpeg comressor: " + ex.getMessage(), ex);
}
final int imageDataSize = compressor.getCompressedSize();
if (exif != null) {
EXIFUtilities.insertEXIFintoStream(((ImageOutputStreamAdapter) outputStream).getTarget(), outputImageData, imageDataSize, exif);
} else {
outputStream.write(outputImageData, 0, imageDataSize);
}
} finally {
if (compressor != null) {
try {
compressor.close();
} catch (Exception t) {
LOGGER.log(Level.SEVERE, t.getLocalizedMessage(), t);
}
}
}
}
Aggregations