使用PDFBox将图像转换为byte[]

3
我正在使用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();
    } 

如果我在 document.close(); 上方写上 ImageIOUtil.writeImage(image , fileName+".jpg" ,300);,程序会在项目路径中创建一个jpg文件。我需要将它放在一个byte[]数组中而不是创建一个文件。这个可行吗?
1个回答

4

可以使用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));

ByteOutputStream使用的是哪个库?是 com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; 吗? - Munchmallow
我的错,应该是java.io.ByteArrayOutputStream,这是Java核心类,已更新答案... - Adam
非常感谢。现在我得考虑如何从HBase中获取它,并将其显示为搜索列表中的图像。 - Munchmallow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接