http://www.thebuzzmedia.com/downloads/software/imgscalr/javadoc/org/imgscalr/Scalr.html
package com.paul.image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
public class ImageFileSizeReducer {
private static String srcPic = "E:/PAUL/WORK/WORDSPACES/WORKSPACE1/Test1/data/pic1.jpg";
private static String destPic = "E:/PAUL/WORK/WORDSPACES/WORKSPACE1/Test1/data/pic3.jpg";
public static void reduceImageQuality(int sizeThreshold, byte[] srcImg,
String destPic) throws Exception {
float quality = 1.0f;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
ByteArrayInputStream inputStream = new ByteArrayInputStream(srcImg);
long fileSize = srcImg.length;
BufferedImage originalImage = ImageIO.read(inputStream);
IIOImage image = new IIOImage(originalImage, null, null);
float percent = 0.8f; // 10% of 1
while (fileSize > sizeThreshold) {
if (percent >= quality) {
percent = percent * 0.1f;
}
quality -= percent;
iwp.setCompressionQuality(quality);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// ImageOutputStream imageos = ImageIO.createImageOutputStream(out);
File file = new File(destPic);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
writer.write(null, image, iwp);
output.close(); // or imageos.flush();
// destImg = output.length();
long newFileSize = output.length();
if (newFileSize == fileSize) {
// createNewPic(quality);
// cannot reduce more, return
break;
} else {
fileSize = newFileSize;
}
System.out.println("quality = " + quality + ", new file size = "
+ fileSize);
}
writer.dispose();
}
public static void main(String[] args) throws Exception {
try {
BufferedImage originalImage = ImageIO.read(new File(srcPic));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
ImageFileSizeReducer.reduceImageQuality(20000,imageInByte,destPic);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}