Save as JPEG

From Processing

Revision as of 20:42, 11 June 2010 by PhiLho (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Versions: 1.0+
Contributors: seltar
Started: 2006-03-02


Saving a PImage as Jpeg is easier than it seems... Use saveBytes("filename.jpg", bufferImage(get(0, 0, width, height))) to get the entire applet screen and save it to disk.

Note: You can actually use save() or saveFrame() in Processing for a similar result. The advantages of the code here is that you can do something else of the returned bytes (eg. send it over the network) and you can change the quality parameter (1 here means no compression, you can lower it for smaller files).

Source Code

/**
saveasjpg taken from http://wiki.processing.org/index.php/Save_as_JPEG
@author Yonas Sandbæk
*/
 
import com.sun.image.codec.jpeg.*;
 
byte[] bufferImage(PImage srcimg) {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  BufferedImage img = new BufferedImage(srcimg.width, srcimg.height, 2);
  img = (BufferedImage) createImage(srcimg.width,srcimg.height);
  for (int i = 0; i < srcimg.width; i++)
    for (int j = 0; j < srcimg.height; j++)
      img.setRGB(i, j, srcimg.pixels[j * srcimg.width + i]);
  try {
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam encpar = encoder.getDefaultJPEGEncodeParam(img);
    encpar.setQuality(1, false);
    encoder.setJPEGEncodeParam(encpar);
    encoder.encode(img);
  }
  catch (FileNotFoundException e) {
    System.out.println(e);
  }
  catch (IOException ioe) {
    System.out.println(ioe);
  }
  return out.toByteArray();
}

Downloads

Related Links

Personal tools