1 14 package org.wings.externalizer; 15 16 import Acme.JPM.Encoders.GifEncoder; 17 import com.keypoint.PngEncoder; 18 import org.apache.commons.logging.Log; 19 import org.apache.commons.logging.LogFactory; 20 import org.wings.io.Device; 21 import org.wings.io.DeviceOutputStream; 22 23 import java.awt.*; 24 import java.util.Collection ; 25 26 31 public class ImageExternalizer implements Externalizer { 32 33 private final transient static Log log = LogFactory.getLog(ImageExternalizer.class); 34 35 public static final String FORMAT_PNG = "png"; 36 public static final String FORMAT_GIF = "gif"; 37 38 private static final String [] SUPPORTED_FORMATS = {FORMAT_PNG, FORMAT_GIF}; 39 private static final Class [] SUPPORTED_CLASSES = {Image.class}; 40 41 public static final ImageExternalizer SHARED_GIF_INSTANCE = new ImageExternalizer(FORMAT_GIF); 42 public static final ImageExternalizer SHARED_PNG_INSTANCE = new ImageExternalizer(FORMAT_PNG); 43 44 protected String format; 45 46 protected final String [] supportedMimeTypes = new String [1]; 47 48 public ImageExternalizer() { 49 this(FORMAT_PNG); 50 } 51 52 public ImageExternalizer(String format) { 53 this.format = format; 54 checkFormat(); 55 56 supportedMimeTypes[0] = getMimeType(null); 57 } 58 59 protected void checkFormat() { 60 for (int i = 0; i < SUPPORTED_FORMATS.length; i++) { 61 if (SUPPORTED_FORMATS[i].equals(format)) 62 return; 63 } 64 throw new IllegalArgumentException ("Unsupported Format " + format); 65 } 66 67 public String getExtension(Object obj) { 68 return format; 69 } 70 71 public String getMimeType(Object obj) { 72 return "image/" + format; 73 } 74 75 public int getLength(Object obj) { 76 return -1; 77 } 78 79 public boolean isFinal(Object obj) { 80 return false; 81 } 82 83 public Class [] getSupportedClasses() { 84 return SUPPORTED_CLASSES; 85 } 86 87 public String [] getSupportedMimeTypes() { 88 return supportedMimeTypes; 89 } 90 91 public void write(Object obj, Device out) 92 throws java.io.IOException { 93 Image img = (Image) obj; 94 if (FORMAT_PNG.equals(format)) 95 writePNG(img, out); 96 else 97 writeGIF(img, out); 98 } 99 100 103 public void writeGIF(Image img, Device out) 104 throws java.io.IOException { 105 GifEncoder encoder = new GifEncoder(img, new DeviceOutputStream(out), 106 true); 107 encoder.encode(); 108 } 109 110 113 public void writePNG(Image img, Device out) 114 throws java.io.IOException { 115 PngEncoder png = new PngEncoder(img, PngEncoder.ENCODE_ALPHA, 116 PngEncoder.FILTER_NONE, 6); 117 byte[] pngbytes = png.pngEncode(); 118 if (pngbytes == null) { 119 log.fatal("null image"); 120 } else { 121 out.write(pngbytes); 122 } 123 out.flush(); 124 } 125 126 public Collection getHeaders(Object obj) { 127 return null; 128 } 129 } 130 131 132 | Popular Tags |