If you try to write a BufferedImage on disk using ImageIO.write you will see that the result image will have a DPI of 96 regardless of the source image's DPI!
In order to keep the source DPI or set your own DPI you need to write your image using JPEGImageEncoder class.
In order to keep the source DPI or set your own DPI you need to write your image using JPEGImageEncoder class.
File inputFile = new File("source.jpg");
File outputFile = new File("new.jpg");
// create input buffered image
BufferedImage image = ImageIO.read(inputFile);
// create jpegEncode for output image
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(outputFile));
// create jpeg encoder from getting defaul value from input buffered
// image
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
// setting up density unit paramter
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
// setting up jpeg encode parameter
jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
// set quality parameter
jpegEncodeParam.setQuality(0.75f, false);
// set X-resolution
jpegEncodeParam.setXDensity(X_DPI);
// set Y-resolution
jpegEncodeParam.setYDensity(Y_DPI);
// encode output image
jpegEncoder.encode(image, jpegEncodeParam);
// flush the buffer image
image.flush();
File outputFile = new File("new.jpg");
// create input buffered image
BufferedImage image = ImageIO.read(inputFile);
// create jpegEncode for output image
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(outputFile));
// create jpeg encoder from getting defaul value from input buffered
// image
JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
// setting up density unit paramter
jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
// setting up jpeg encode parameter
jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
// set quality parameter
jpegEncodeParam.setQuality(0.75f, false);
// set X-resolution
jpegEncodeParam.setXDensity(X_DPI);
// set Y-resolution
jpegEncodeParam.setYDensity(Y_DPI);
// encode output image
jpegEncoder.encode(image, jpegEncodeParam);
// flush the buffer image
image.flush();
2 comments:
Thanks mate.
Exactly what I needed!
:) You're welcome
Post a Comment