Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedImage img = ImageIO.read(new File("test.jpg"));
        writeJpegCompressedImage(img, "NEW.jpg");
    }

    private static void writeJpegCompressedImage(BufferedImage image, String outFile) throws IOException {
        float qualityFloat = 1f;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
        imgWriter.setOutput(ioStream);

        JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
        jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(qualityFloat);

        imgWriter.write(null, new IIOImage(image, null, null), jpegParams);

        ioStream.flush();
        ioStream.close();
        imgWriter.dispose();

        OutputStream outputStream = new FileOutputStream(outFile);
        outStream.writeTo(outputStream);

    }
}