Java BufferedImage to JPEG imageToJpeg(BufferedImage image)

Here you can find the source of imageToJpeg(BufferedImage image)

Description

image To Jpeg

License

Open Source License

Declaration

public static byte[] imageToJpeg(BufferedImage image) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;

public class Main {
    public static byte[] imageToJpeg(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {//from   www  .  ja v  a 2  s.  c  o m
            JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO
                    .getImageWritersBySuffix("jpeg").next();
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            imageWriter.setOutput(ios);
            imageWriter.write(image);
            ios.close();
            imageWriter.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os.toByteArray();
    }

    public static void imageToJpeg(BufferedImage image, File jpegFile) {
        try {
            JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO
                    .getImageWritersBySuffix("jpeg").next();
            ImageOutputStream ios = ImageIO
                    .createImageOutputStream(new FileOutputStream(jpegFile));
            imageWriter.setOutput(ios);
            imageWriter.write(image);
            ios.close();
            imageWriter.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. bufferedImage2Jpeg(final BufferedImage img)