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


Take a look at the following package :

http://www.obrador.com/essentialjpeg/jpeg.htm for JPEG
http://www.acme.com for GIF
http://rsb.info.nih.gov/ij/ 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(
   (int)w,(int)h,BufferedImage.TYPE_INT_RGB);

Graphics2D g = (Graphics2D)image.getGraphics();
g.drawLine(0,0,w,h);

try {
   File f = new File("myimage.jpg");
   JimiRasterImage jrf = Jimi.createRasterImage(image.getSource());
   Jimi.putImage("image/jpeg",jrf,new FileOutputStream(f));
   }
catch (JimiException je) {
   je.printStackTrace();}
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 { 
  pg.grabPixels(); 
  } 
catch(InterruptedException ie) { 
  ie.printStackTrace();
  }

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

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

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 java.io.*;
import javax.imageio.*;
import java.awt.image.*;
 
public class FileOperations {
    
    public static BufferedImage readImageFromFile(File file) 
       throws IOException
    {
        return ImageIO.read(file);
    }
 
    public static void writeImageToJPG
       (File file,BufferedImage bufferedImage) 
          throws IOException
    {
        ImageIO.write(bufferedImage,"jpg",file);
    }
}

blog comments powered by Disqus