Encoding an image to a JPEG file : JPEG « 2D Graphics GUI « Java






Encoding an image to a JPEG file

    


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Main {

  public static void main(String[] args) throws Exception {
    BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

    Graphics g = img.getGraphics();
    g.setColor(Color.red);
    g.setFont(new Font("Arial", Font.BOLD, 14));
    g.drawString("Reference", 10, 80);

    int w = 100;
    int h = 100;
    int x = 1;
    int y = 1;
    
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);

    pg.grabPixels();
    BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

    for (int j = 0; j < h; j++) {
      for (int i = 0; i < w; i++) {
        bimg.setRGB(x + i, y + j, pixels[j * w + i]);
      }
    }

    FileOutputStream fout = new FileOutputStream("jpg.jpg");

    JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(fout);
    JPEGEncodeParam enParam = jencoder.getDefaultJPEGEncodeParam(bimg);

    enParam.setQuality(1.0F, true);
    jencoder.setJPEGEncodeParam(enParam);
    jencoder.encode(bimg);

    fout.close();

  }
}

   
    
    
    
  








Related examples in the same category

1.Rescale JPG
2.Get Jpeg Properties
3.Takes a list of JPEG image files and convert them into a QuickTime movie.
4.Performs a jpeg compression of an image
5.Returns all jpg images from a directory in an array
6.Writes an image to an output stream as a JPEG file. The JPEG quality can be specified in percent.