Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
JpegWriter.java
1 package ij.plugin;
2 import ij.*;
3 import ij.process.*;
4 import ij.gui.*;
5 import ij.io.*;
6 import com.sun.image.codec.jpeg.*;
7 import java.awt.image.*;
8 import java.awt.*;
9 import java.io.*;
10 
14 public class JpegWriter implements PlugIn {
15 
16  public static final int DEFAULT_QUALITY = 75;
17  private static int quality;
18 
19  static {setQuality(ij.Prefs.getInt(ij.Prefs.JPEG, DEFAULT_QUALITY));}
20 
21  public void run(String arg) {
22  ImagePlus imp = IJ.getInstance().getImagePlus();
23  if (imp==null)
24  return;
25  imp.startTiming();
26  saveAsJpeg(imp,arg);
27  IJ.showTime(imp, imp.getStartTime(), "JpegWriter: ");
28  }
29 
30  void saveAsJpeg(ImagePlus imp, OutputStream f) {
31  //IJ.log("saveAsJpeg: "+path);
32  int width = imp.getWidth();
33  int height = imp.getHeight();
34  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
35  try {
36  Graphics g = bi.createGraphics();
37  g.drawImage(imp.getImage(), 0, 0, null);
38  g.dispose();
39  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(f);
40  JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
41  param.setQuality((float)(quality/100.0), true);
42  encoder.encode(bi, param);
43  f.close();
44  }
45  catch (Exception e) {
46  IJ.showMessage("Jpeg Writer", ""+e);
47  }
48  }
49 
50  void saveAsJpeg(ImagePlus imp, String path) {
51  try {
52  FileOutputStream f = new FileOutputStream(path);
53  saveAsJpeg(imp, f);
54  } catch (Exception e) {
55  IJ.showMessage("Jpeg Writer", ""+e);
56  }
57  }
58 
59  public byte[] getJpegContents(ImagePlus imp) {
60  ByteArrayOutputStream f = new ByteArrayOutputStream();
61  saveAsJpeg(imp, f);
62  return f.toByteArray();
63  }
64 
65 
68  public static void setQuality(int jpegQuality) {
69  quality = jpegQuality;
70  if (quality<0) quality = 0;
71  if (quality>100) quality = 100;
72  }
73 
74  public static int getQuality() {
75  return quality;
76  }
77 
78 }