Ever run into the problem of wanting to write an image object to disk in a popular format for images ?
With Java 2 platform, image objects or any memory based image representation can be written to disk in the JPEG format. The example shows a simple image created in memory written to disk in the JPEG format. The example makes use of the com.sun.image.codec.jpeg classes to do the encoding. Though it is not a part of the feature set of the Java 2 platform, these classes are still available in the distributed runtime.
Code
/* * This example is from javareference.com * for more information visit, * http://www.javareference.com */ import java.awt.*; import java.awt.image.*; import java.io.*; import com.sun.image.codec.jpeg.*; /* * This class can take a variable number of parameters on the command * line. Program execution begins with the main() method. The class * constructor is not invoked unless an object of type 'Class1' * created in the main() method. * * @author Anand Hariharan([email protected]) */ public class EncodeJPEG { public static void encode(Image img,int x, int y, int w, int h, String absoluteFileName) throws Exception { int[] pixels = new int[w * h]; PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w); try { pg.grabPixels(); } catch (InterruptedException e) { System.err.println("interrupted waiting for pixels!"); return; } if ((pg.getStatus() & ImageObserver.ABORT) != 0) { System.err.println("image fetch aborted or errored"); return; } 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(absoluteFileName); JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(fout); JPEGEncodeParam enParam = jencoder.getDefaultJPEGEncodeParam(bimg); enParam.setQuality(1.0F, true); jencoder.setJPEGEncodeParam(enParam); jencoder.encode(bimg); fout.close(); } public static void main(String [] args) throws Exception { Frame f = new Frame(); f.addNotify(); // CREATE an image in memory to draw on Image img = f.createImage(100,100); Graphics g = img.getGraphics(); g.setColor(Color.red); // Draw whatever is needed. g.fillRect(0, 0, 100,100); g.setColor(Color.black); g.setFont(new Font("Arial", Font.BOLD, 14)); g.drawString("Hello from,",10,25); g.drawString("Java",30,55); g.drawString("Reference",10,80); g.setColor(Color.white); g.drawString("Hello from,",8,22); g.drawString("Java",28,52); g.drawString("Reference",8,77); // Encode into a JPEG String homeDir = System.getProperty("user.home"); System.out.println("Output JPEG ..." + homeDir + File.separator + "jpg.jpg"); encode(img,0,0,100,100, homeDir + File.separator + "jpg.jpg"); f.removeNotify(); f.dispose(); System.exit(0); } }
Demonstration
Following JPEG image is created using above java code.
0