Save an Image as a GIF or JPEG fileTag(s): AWT

Take a look at the following package : for JPEG for GIF can display BMP and save as GIF or TIFF

With JDK1.2, Sun introduces a new package called JIMI (available for download at their Web site. With this package, it's easy to convert a Java Image to a JPEG image file.

double w = 200.0;
double h = 200.0;
BufferedImage image = new BufferedImage(

Graphics2D g = (Graphics2D)image.getGraphics();

try {
   File f = new File("myimage.jpg");
   JimiRasterImage jrf = Jimi.createRasterImage(image.getSource());
   Jimi.putImage("image/jpeg",jrf,new FileOutputStream(f));
catch (JimiException je) {
Another way is to use the undocumented com.sun.image.codec.jpeg package.
//  [JDK1.2]
//  img is a Java Image
BufferedImage bimg = null;
int w = img.getWidth(null);
int h = img.getHeight(null);
int [] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img,0,0,w,h,pixels,0,w);
try { 
catch(InterruptedException ie) { 

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

// Encode as a JPEG
FileOutputStream fos = new FileOutputStream("out.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);

Since JDK1.4.2, javax.imageio.ImageIO lets you save and restore Images to disk in a platform independent format. "png" and "jpeg" format are supported. With ImageIO, instead of Image you use BufferedImage which is a subclass of Image.

import javax.imageio.*;
import java.awt.image.*;
public class FileOperations {
    public static BufferedImage readImageFromFile(File file) 
       throws IOException
    public static void writeImageToJPG
       (File file,BufferedImage bufferedImage) 
          throws IOException

blog comments powered by Disqus