Search code examples
javaimageswingpdfpdfclown

casting an javax.swing.ImageIcon object to org.pdfclown.documents.contents.entities.Image


I'm trying to cast a javax.swing.ImageIcon to a org.pdfclown.documents.contents.entities.Image so that I can display images in PDF file created by PDF Clown from my Swing application.

I require a ImageIcon because the source image needs to be serializable so that I can store my image as a serialised file as part of a larger, more complex data model.

When I look at the API for PDF Clown I notice Image accepts 3 inputs;

  1. String path. - Wont work because ImageIcon doesn't have a Path.
  2. File. - Wont work because ImageIcon doesn't exist on disk.
  3. IInputStream stream Reference

This means the only viable method is to use an IInputStream. It is an interface so the only way to construct an Object with that type is to use a FileInputStream Reference. This accepts a native Java class of RandomAccessFile Reference. This is another dead end as it accepts only File and String.

The solution then must be to write the ImageIcon as an image to disk then read it back. My concern with this is that I need to use a path to store the images before output that the user wont have restricted access to.

Can I do this without writing to disk first?


Solution

  • I created this class to perform the cast;

    public class ImageIconToBuffer {
        public static Buffer convert(ImageIcon img) {
            try {
                BufferedImage image = toBufferedImage(img);
    
                byte[] bytes = toByteArray(image);
    
                Buffer buffer = new Buffer(bytes);
                return buffer;
            } catch (IOException e) {
                return null;
            }
        }
    
        public static byte[] toByteArray(BufferedImage image) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();            
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
            encoder.encode(image);   
    
            return baos.toByteArray();
        }
    
        public static BufferedImage toBufferedImage(ImageIcon icon) {
            Image img = icon.getImage();
            BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
    
            Graphics2D bGr = bi.createGraphics();
            bGr.drawImage(img, 0, 0, null);
            bGr.dispose();
    
            return bi;
        }
    
    }