I need to reduce the size of image(not the width and height) using Java program. Is their any good API available for this?
I need to reduce the size from 1MB to abou
According to this blog post: http://i-proving.com/2006/07/06/java-advanced-imaging/ you can use the Java Advanced Imaging Library to do what you want. The following sample code should provide you a good starting point. This will resize the image, both in height and width, as well as image quality. Once your image is of the desired file size, you can scale it back up to your desired pixel height and width when you display the image.
// read in the original image from an input stream
SeekableStream s = SeekableStream.wrapInputStream(
inputStream, true);
RenderedOp image = JAI.create("stream", s);
((OpImage)image.getRendering()).setTileCache(null);
// now resize the image
float scale = newWidth / image.getWidth();
RenderedOp resizedImage = JAI.create("SubsampleAverage",
image, scale, scale, qualityHints);
// lastly, write the newly-resized image to an
// output stream, in a specific encoding
JAI.create("encode", resizedImage, outputStream, "PNG", null);
This is the working code
public class ImageCompressor {
public void compress() throws IOException {
File infile = new File("Y:\\img\\star.jpg");
File outfile = new File("Y:\\img\\star_compressed.jpg");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
infile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(outfile));
SeekableStream s = SeekableStream.wrapInputStream(bis, true);
RenderedOp image = JAI.create("stream", s);
((OpImage) image.getRendering()).setTileCache(null);
RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
RenderedOp resizedImage = JAI.create("SubsampleAverage", image, 0.9,
0.9, qualityHints);
JAI.create("encode", resizedImage, bos, "JPEG", null);
}
public static void main(String[] args) throws IOException {
new ImageCompressor().compress();
}
}
This code is Working Great for me. if you need to resize the image then you can
change the x and y scale here JAI.create("SubsampleAverage", image, xscale,yscale, qualityHints);
If your image type is supported by an implementation of ImageWriteParam, you can adjust the quality as shown in this example. Other ImageWriteParam methods, such as getBitRate()
, may allow you to optimize the result.
You can use JAI to increase the compression of a written JPEG without doing any scaling. See http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html