簡體   English   中英

將 javax.swing.ImageIcon 對象轉換為 org.pdfclown.documents.contents.entities.Image

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

我正在嘗試將javax.swing.ImageIcon轉換為org.pdfclown.documents.contents.entities.Image以便我可以在 PDF Clown 從我的 Swing 應用程序創建的 PDF 文件中顯示圖像。

我需要一個 ImageIcon,因為源圖像需要可序列化,以便我可以將我的圖像作為序列化文件存儲為更大、更復雜的數據模型的一部分。

當我查看PDF ClownAPI 時,我注意到Image接受 3 個輸入;

  1. String路徑。 - 無法工作,因為ImageIcon沒有路徑。
  2. File . - 無法工作,因為磁盤上不存在ImageIcon
  3. IInputStream參考

這意味着唯一可行的方法是使用IInputStream 它是一個接口,因此構造具有該類型的 Object 的唯一方法是使用FileInputStream Reference 這接受RandomAccessFile Reference的本機 Java 類。 這是另一個死胡同,因為它只接受FileString

解決方案必須是將ImageIcon作為圖像寫入磁盤,然后將其讀回。 我對此的擔憂是我需要在輸出之前使用路徑來存儲用戶不會限制訪問的圖像。

我可以在不先寫入磁盤的情況下執行此操作嗎?

我創建了這個類來執行演員表;

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM