Example usage for javax.imageio ImageWriter write

List of usage examples for javax.imageio ImageWriter write

Introduction

In this page you can find the example usage for javax.imageio ImageWriter write.

Prototype

public void write(RenderedImage image) throws IOException 

Source Link

Document

Appends a complete image stream consisting of a single image with default metadata and thumbnails to the output.

Usage

From source file:com.sketchy.utils.image.SketchyImage.java

public static void save(SketchyImage sketchyImage, File file) throws Exception {
    if (!file.getParentFile().canWrite()) {
        throw new Exception("Can not write to File: " + file.getPath() + "!");
    }// w  w w  .j a v  a  2s .  c o  m

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not save SketchyImage! Must be a .png file!");
    }

    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png");
    ImageWriter imageWriter = null;
    if (imageWriters.hasNext()) { // Just get first one
        imageWriter = imageWriters.next();
    }
    if (imageWriter == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageOutputStream os = null;
    try {
        os = ImageIO.createImageOutputStream(file);
        imageWriter.setOutput(os);

        ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam();
        IIOMetadata metadata = imageWriter.getDefaultImageMetadata(
                ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY),
                imageWriterParam);

        String metaDataFormatName = metadata.getNativeMetadataFormatName();
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName);

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        IIOMetadataNode physNode = null;
        if (childNodes.getLength() == 0) {
            physNode = new IIOMetadataNode("pHYs");
            physNode.setAttribute("pixelsPerUnitXAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
            physNode.setAttribute("pixelsPerUnitYAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
            physNode.setAttribute("unitSpecifier", "meter"); // always meter
            metaDataNode.appendChild(physNode);
        } else {
            for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) {
                physNode = (IIOMetadataNode) childNodes.item(nodeIdx);
                physNode.setAttribute("pixelsPerUnitXAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
                physNode.setAttribute("pixelsPerUnitYAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
                physNode.setAttribute("unitSpecifier", "meter"); // always meter
                metaDataNode.appendChild(physNode);
            }
        }
        metadata.setFromTree(metaDataFormatName, metaDataNode);
        imageWriter.write(new IIOImage(sketchyImage.image, null, metadata));
        os.flush();
    } catch (Exception e) {
        throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "!  " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.photovault.imginfo.CreateCopyImageCommand.java

/**
 Helper function to save a rendered image to file
 @param instanceFile The file into which the image will be saved
 @param img Image that willb e saved/* ww  w  .ja  v  a2 s.  c o m*/
 @param xmpData XPM metadata packet that should be saved with the image
 @throws PhotovaultException if saving does not succeed
 */
protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException {
    ImageOutputStream out = null;
    log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath());
    try {
        out = new FileImageOutputStream(instanceFile);
    } catch (IOException e) {
        log.error("Error writing image: " + e.getMessage());
        throw new PhotovaultException(e.getMessage());
    }
    if (img.getSampleModel().getSampleSize(0) == 16) {
        log.debug("16 bit image, converting to 8 bits");
        double[] subtract = new double[1];
        subtract[0] = 0;
        double[] divide = new double[1];
        divide[0] = 1. / 256.;
        // Now we can rescale the pixels gray levels:
        ParameterBlock pbRescale = new ParameterBlock();
        pbRescale.add(divide);
        pbRescale.add(subtract);
        pbRescale.addSource(img);
        PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null);
        // Make sure it is a byte image - force conversion.
        ParameterBlock pbConvert = new ParameterBlock();
        pbConvert.addSource(outputImage);
        pbConvert.add(DataBuffer.TYPE_BYTE);
        img = JAI.create("format", pbConvert);
    }

    IIOImage iioimg = new IIOImage(img, null, null);

    /*
     Not all encoders support metadata handling
     */
    Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter imgwriter = null;
    while (writers.hasNext()) {
        imgwriter = (ImageWriter) writers.next();
        if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) {
            // Break on finding the core provider.
            break;
        }
    }
    if (imgwriter == null) {
        System.err.println("Cannot find core JPEG writer!");
    }
    imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() {

        public void warningOccurred(ImageWriter arg0, int arg1, String arg2) {
            log.warn("Warning from ImageWriter: " + arg2);
        }
    });
    ImageWriteParam params = imgwriter.getDefaultWriteParam();
    ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img);
    IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null);

    IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
    NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence");
    if (markerSeqNodes.getLength() > 0) {
        IIOMetadataNode xmpNode = new IIOMetadataNode("unknown");
        xmpNode.setAttribute("MarkerTag", "225");
        xmpNode.setUserObject(xmpData);
        markerSeqNodes.item(0).appendChild(xmpNode);
    }

    try {
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop);
    } catch (Exception e) {
        log.warn("error editing metadata: " + e.getMessage());
        e.printStackTrace();
        throw new PhotovaultException("error setting image metadata: \n" + e.getMessage());
    }

    iioimg.setMetadata(metadata);

    try {
        imgwriter.setOutput(out);
        imgwriter.write(iioimg);
    } catch (IOException e) {
        log.warn("Exception while encoding" + e.getMessage());
        throw new PhotovaultException(
                "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            log.warn("Exception while closing file: " + e.getMessage());
            imgwriter.dispose();
            throw new PhotovaultException(
                    "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());

        }
        imgwriter.dispose();
    }
    log.debug("Exit: saveImage");
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private boolean generateImageThumb(StudyFile file) {

    String fileLocation = file.getFileSystemLocation();
    if (fileLocation == null || fileLocation.trim().equals("")) {
        return false;
    }/*from  ww  w.  j av a  2  s.  c  om*/
    String thumbFileLocation = fileLocation + ".thumb";

    // see if the thumb is already generated and saved:

    if (new File(thumbFileLocation).exists()) {
        return true;
    }

    // let's attempt to generate the thumb:

    // the default size of the thumbnail is 64 pixels horizontally.
    // The number 64 was picked arbitrarily; if a different size is 
    // desired, it can be configured via the dvn.image.thumbnail.size 
    // JVM option.

    Long thumbSize = Long.valueOf(64);

    String thumbSizeOption = System.getProperty("dvn.image.thumbnail.size");

    if (thumbSizeOption != null) {
        Long thumbSizeOptionValue = null;
        try {
            thumbSizeOptionValue = new Long(thumbSizeOption);
        } catch (NumberFormatException nfe) {
            // if the supplied option value is invalid/unparseable, we
            // ignore it and fall back to the default value. 
        }
        if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
            thumbSize = thumbSizeOptionValue;
        }
    }

    // it is also possible to configure the thumbnail size for a 
    // specific dataverse: 

    VDC vdc = file.getStudy().getOwner();

    if (vdc != null) {
        thumbSizeOption = System.getProperty("dvn.image.thumbnail.size." + vdc.getAlias());

        if (thumbSizeOption != null) {
            Long thumbSizeOptionValue = null;
            try {
                thumbSizeOptionValue = new Long(thumbSizeOption);
            } catch (NumberFormatException nfe) {
                // if the supplied option value is invalid/unparseable, we
                // ignore it and fall back to the default value. 
            }
            if (thumbSizeOptionValue != null && thumbSizeOptionValue.longValue() > 0) {
                thumbSize = thumbSizeOptionValue;
            }
        }
    }

    // This is the default location of the "convert" executable from the
    // ImageMagick package. If it's installed in a different locaiton, 
    // it can be configured via the dvn.image.convert.exec JVM option. 

    String imageMagickConvertExec = "/usr/bin/convert";

    String imageMagickConvertExecOption = System.getProperty("dvn.image.convrt.exec");

    if (imageMagickConvertExecOption != null) {
        if (!imageMagickConvertExecOption.trim().equals("")) {
            imageMagickConvertExec = imageMagickConvertExecOption.trim();
        }
    }

    if (new File(imageMagickConvertExec).exists()) {
        String sizeOption = " -size " + thumbSize + "x" + thumbSize + " ";

        String ImageMagickCommandLine = imageMagickConvertExec + sizeOption + fileLocation + " -resize "
                + thumbSize + " -flatten png:" + thumbFileLocation;
        int exitValue = 1;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(ImageMagickCommandLine);
            exitValue = process.waitFor();
        } catch (Exception e) {
            exitValue = 1;
        }

        if (exitValue == 0) {
            return true;
        }
    }

    // For whatever reason, creating the thumbnail with ImageMagick
    // has failed.
    // Let's try again, this time with Java's standard Image
    // library:

    try {
        BufferedImage fullSizeImage = ImageIO.read(new File(fileLocation));

        if (fullSizeImage == null) {
            return false;
        }

        double scaleFactor = (thumbSize.doubleValue()) / (double) fullSizeImage.getWidth(null);
        int thumbHeight = (int) (fullSizeImage.getHeight(null) * scaleFactor);

        // We are willing to spend a few extra CPU cycles to generate
        // better-looking thumbnails, hence the SCALE_SMOOTH flag. 
        // SCALE_FAST would trade quality for speed. 

        java.awt.Image thumbImage = fullSizeImage.getScaledInstance(thumbSize.intValue(), thumbHeight,
                java.awt.Image.SCALE_SMOOTH);

        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        } else {
            return false;
        }

        BufferedImage lowRes = new BufferedImage(thumbSize.intValue(), thumbHeight, BufferedImage.TYPE_INT_RGB);
        lowRes.getGraphics().drawImage(thumbImage, 0, 0, null);

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(thumbFileLocation));
        writer.setOutput(ios);

        // finally, save thumbnail image:
        writer.write(lowRes);
        writer.dispose();

        ios.close();
        thumbImage.flush();
        fullSizeImage.flush();
        lowRes.flush();
        return true;
    } catch (Exception e) {
        // something went wrong, returning "false":
        dbgLog.info("ImageIO: caught an exception while trying to generate a thumbnail for " + fileLocation);

        return false;
    }
}