簡體   English   中英

使用PDFBox將圖像轉換為byte []

[英]Converting an image to byte[] by using PDFBox

我正在使用PDFBox 2.0。 在解析PDF文檔時,我還希望將第一頁作為圖像保存到hbase以便在搜索結果中使用(我將創建一個搜索列表頁面,如amazon.com的搜索頁面)。

HBase接受byte []變量來存儲(索引)一個值。 我需要將圖像轉換為byte [],然后將其存儲到HBase。 我已經實現了圖像渲染,但是如何將其轉換為byte []?

        PDDocument document = PDDocument.load(file, "");
        BufferedImage image = null;
        try {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            if (document.isEncrypted()) {
                try {
                    System.out.println("Trying to decrypt...);
                    document.setAllSecurityToBeRemoved(true);
                    System.out.println("The file has been decrypted in .");
                }
                catch (Exception e) {
                    throw new Exception("cannot be decrypted. ", e);
                }
            }
            PDPage firstPage = (PDPage) document.getDocumentCatalog().getPages().get(0);
            pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
               // 0 means first page.

            image = pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);                  
            document.close();

    } catch (Exception e) {
            e.printStackTrace();
    } 

如果我寫ImageIOUtil.writeImage(image , fileName+".jpg" ,300); document.close();上方的右上方document.close(); ,程序會在項目路徑中創建一個jpg文件。 我需要將其放入byte []數組中,而不是創建文件。 可能嗎?

這可以通過ImageIO.write(Image,String,OutputStream)完成 ,它可以寫入任意OutputStream而不是磁盤。 ByteArrayOutputStream可以將輸出字節存儲到內存中的數組中。

import java.io.ByteArrayOutputStream;
...
// example image
BufferedImage image = new BufferedImage(4, 3, BufferedImage.TYPE_INT_ARGB);

// to array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", bos);
byte [] output = bos.toByteArray();
System.out.println(Arrays.toString(output));

暫無
暫無

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

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