Example usage for org.apache.pdfbox.pdmodel.graphics.image PDImage getImage

List of usage examples for org.apache.pdfbox.pdmodel.graphics.image PDImage getImage

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.graphics.image PDImage getImage.

Prototype

BufferedImage getImage() throws IOException;

Source Link

Document

Returns the content of this image as an AWT buffered image with an (A)RGB color space.

Usage

From source file:edu.ist.psu.sagnik.research.pdfbox2playground.javatest.ExtractImages.java

License:Apache License

/**
 * Writes the image to a file with the filename + an appropriate suffix, like "Image.jpg".
 * The suffix is automatically set by the
 * @param filename the filename//w  ww. ja v  a  2  s  .com
 * @throws IOException When somethings wrong with the corresponding file.
 */
private void write2file(PDImage pdImage, String filename, boolean directJPEG) throws IOException {
    String suffix = pdImage.getSuffix();
    if (suffix == null) {
        suffix = "png";
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename + "." + suffix);
        BufferedImage image = pdImage.getImage();
        if (image != null) {
            if ("jpg".equals(suffix)) {
                String colorSpaceName = pdImage.getColorSpace().getName();
                if (directJPEG || PDDeviceGray.INSTANCE.getName().equals(colorSpaceName)
                        || PDDeviceRGB.INSTANCE.getName().equals(colorSpaceName)) {
                    // RGB or Gray colorspace: get and write the unmodifiedJPEG stream
                    //InputStream data = pdImage.getColor.getPartiallyFilteredStream(JPEG);
                    //IOUtils.copy(data, out);
                    //IOUtils.closeQuietly(data);
                    BufferedImage b = pdImage.getImage();
                    ImageIOUtil.writeImage(b, "jpg", out);
                } else {
                    // for CMYK and other "unusual" colorspaces, the JPEG will be converted
                    ImageIOUtil.writeImage(image, suffix, out);
                }
            } else {
                ImageIOUtil.writeImage(image, suffix, out);
            }
        }
        out.flush();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}