1 17 package org.apache.geronimo.activation.handlers; 18 19 import java.awt.Graphics2D ; 20 import java.awt.Image ; 21 import java.awt.datatransfer.DataFlavor ; 22 import java.awt.datatransfer.UnsupportedFlavorException ; 23 import java.awt.image.BufferedImage ; 24 import java.awt.image.RenderedImage ; 25 import java.io.IOException ; 26 import java.io.OutputStream ; 27 import java.util.Iterator ; 28 import javax.activation.DataContentHandler ; 29 import javax.activation.DataSource ; 30 import javax.activation.UnsupportedDataTypeException ; 31 import javax.imageio.IIOImage ; 32 import javax.imageio.ImageIO ; 33 import javax.imageio.ImageReader ; 34 import javax.imageio.ImageWriter ; 35 36 39 public class AbstractImageHandler implements DataContentHandler { 40 private final DataFlavor flavour; 41 42 public AbstractImageHandler(DataFlavor flavour) { 43 this.flavour = flavour; 44 } 45 46 public DataFlavor [] getTransferDataFlavors() { 47 return new DataFlavor []{flavour}; 48 } 49 50 public Object getTransferData(DataFlavor dataFlavor, DataSource dataSource) throws UnsupportedFlavorException , IOException { 51 return flavour.equals(dataFlavor) ? getContent(dataSource) : null; 52 } 53 54 public Object getContent(DataSource ds) throws IOException { 55 Iterator i = ImageIO.getImageReadersByMIMEType(ds.getContentType()); 56 if (!i.hasNext()) { 57 throw new UnsupportedDataTypeException (); 58 } 59 ImageReader reader = (ImageReader ) i.next(); 60 return reader.read(0); 61 } 62 63 public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException { 64 Iterator i = ImageIO.getImageWritersByMIMEType(mimeType); 65 if (!i.hasNext()) { 66 throw new UnsupportedDataTypeException (); 67 } 68 ImageWriter writer = (ImageWriter ) i.next(); 69 writer.setOutput(os); 70 71 if (obj instanceof RenderedImage ) { 72 writer.write((RenderedImage ) obj); 73 } else if (obj instanceof BufferedImage ) { 74 BufferedImage buffered = (BufferedImage ) obj; 75 writer.write(new IIOImage (buffered.getRaster(), null, null)); 76 } else if (obj instanceof Image ) { 77 Image image = (Image ) obj; 78 BufferedImage buffered = new BufferedImage (image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); 79 Graphics2D graphics = buffered.createGraphics(); 80 graphics.drawImage(image, 0, 0, null, null); 81 writer.write(new IIOImage (buffered.getRaster(), null, null)); 82 } else { 83 throw new UnsupportedDataTypeException (); 84 } 85 os.flush(); 86 } 87 } 88 | Popular Tags |