Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Iterator;
- import javax.imageio.*;
- import javax.imageio.stream.*;
- import java.awt.image.*;
- public class ImageFileSizeReducer {
- public static void reduceImageQuality(int sizeThreshold, String srcImg, String destImg) throws Exception {
- float quality = 1.0f;
- File file = new File(srcImg);
- long fileSize = file.length();
- if (fileSize <= sizeThreshold) {
- System.out.println("Image file size is under threshold");
- return;
- }
- Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
- ImageWriter writer = (ImageWriter)iter.next();
- ImageWriteParam iwp = writer.getDefaultWriteParam();
- iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
- FileInputStream inputStream = new FileInputStream(file);
- BufferedImage originalImage = ImageIO.read(inputStream);
- IIOImage image = new IIOImage(originalImage, null, null);
- float percent = 0.1f; // 10% of 1
- while (fileSize > sizeThreshold) {
- if (percent >= quality) {
- percent = percent * 0.1f;
- }
- quality -= percent;
- File fileOut = new File(destImg);
- if (fileOut.exists()) {
- fileOut.delete();
- }
- FileImageOutputStream output = new FileImageOutputStream(fileOut);
- writer.setOutput(output);
- iwp.setCompressionQuality(quality);
- writer.write(null, image, iwp);
- File fileOut2 = new File(destImg);
- long newFileSize = fileOut2.length();
- if (newFileSize == fileSize) {
- // cannot reduce more, return
- break;
- } else {
- fileSize = newFileSize;
- }
- System.out.println("quality = " + quality + ", new file size = " + fileSize);
- output.close();
- }
- writer.dispose();
- }
- public static void main(String[] args) throws Exception {
- String srcPath = args[0];
- String destPath = args[1];
- int maxSize = Integer.parseInt(args[2]);
- reduceImageQuality(maxSize, srcPath, destPath);
- System.out.println("DONE");
- }
- }
Add Comment
Please, Sign In to add comment