2016-05-03 87 views
-1

我试图将javax.swing.ImageIcon投射到org.pdfclown.documents.contents.entities.Image,以便我可以在我的Swing中显示由PDF Clown创建的PDF文件中的图像应用。将javax.swing.ImageIcon对象投射到org.pdfclown.documents.contents.entities.Image

我需要ImageIcon,因为源图像需要可序列化,以便我可以将图像作为序列化文件存储,作为更大,更复杂的数据模型的一部分。

当我看API for PDF Clown我注意到Image接受3输入;

  1. String path。 - 不会工作,因为ImageIcon没有路径。
  2. File。 - 不能工作,因为ImageIcon在磁盘上不存在。
  3. IInputStreamReference

这意味着唯一可行的方法是使用一个IInputStream。它是一个接口,因此构建该类型对象的唯一方法是使用FileInputStreamReference。这接受一个本地Java类RandomAccessFileReference。这是另一个死胡同,因为它只接受FileString

解决方案必须将ImageIcon作为映像写入磁盘,然后再读回。我对此的担忧是,我需要使用路径来存储输出之前的图像,用户不会限制访问权限。

我可以在不首先写入磁盘的情况下执行此操作吗?

+3

我对这个API并不熟悉,但它看起来像'Buffer'实现了'IInputStream',并且接受了更灵活的构造函数参数。 – resueman

回答

1

我创建了这个类来执行演员;

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; 
    } 

}