Example usage for javax.imageio ImageWriter setOutput

List of usage examples for javax.imageio ImageWriter setOutput

Introduction

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

Prototype

public void setOutput(Object output) 

Source Link

Document

Sets the destination to the given ImageOutputStream or other Object .

Usage

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

private Element createEmbeddeImage(BufferedImage img) {
    if (img == null) {
        return null;
    }/*  ww w  . j a v a  2 s .  c o  m*/

    int width = img.getWidth();
    int height = img.getHeight();
    ImageWriter iw = ImageWriterFactory.instance().createByFormatName("png"); //$NON-NLS-1$
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192 * 2);
    String sUrl = null;
    try {
        final ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos);
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        iw.setOutput(ios);
        iw.write((IIOMetadata) null, new IIOImage(img, null, null), iwp);
        img.flush();
        ios.close();
        sUrl = SVGImage.BASE64 + new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception ex) {
        logger.log(ex);
    } finally {
        iw.dispose();
    }

    Element elemG = dom.createElement("g"); //$NON-NLS-1$
    elemG.setAttribute("id", "img_" + img.hashCode()); //$NON-NLS-1$//$NON-NLS-2$
    Element elem = dom.createElement("image"); //$NON-NLS-1$
    elem.setAttribute("x", "0"); //$NON-NLS-1$//$NON-NLS-2$
    elem.setAttribute("y", "0"); //$NON-NLS-1$ //$NON-NLS-2$
    elem.setAttribute("width", Integer.toString(width)); //$NON-NLS-1$
    elem.setAttribute("height", Integer.toString(height)); //$NON-NLS-1$
    elem.setAttribute("xlink:href", sUrl); //$NON-NLS-1$
    elemG.appendChild(elem);

    return elemG;
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

@Override
public byte[] writeToStreamAndByteArray(OutputStream outStream) {
    byte[] data = null;
    if (this.renderedimage == null) { // no image available
        return data;
    }/*from ww w.  jav  a 2  s.co m*/
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos);
        writer.setOutput(imageToFile);
        writer.prepareWriteSequence(null);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageToFile.flush();
        imageToFile.close();
        baos.flush();
        data = baos.toByteArray();
        baos.close();
        writer.dispose();
        imageOutStream.close();
    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
    return data;
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

/************************************************************************************
 * Write the renderedimage to an {@link OutputStream}
 * //  w w  w. j a v  a 2  s.c  o m
 * @param outStream the {@link OutputStream} to write to
 ************************************************************************************/
@Override
public void writeToStream(FileOutputStream fos, OutputStream outStream) {
    if (this.renderedimage == null) { // no image available
        return;
    }
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        if (fos != null) {
            ImageOutputStream imageToFile = ImageIO.createImageOutputStream(fos);
            writer.setOutput(imageToFile);
            writer.prepareWriteSequence(null);
            writer.write(null, iioImage, writerParam);
            writer.endWriteSequence();
            imageToFile.flush();
            imageToFile.close();
            fos.flush();
            fos.close();
        }

        // ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // byte [] data = wi.getImageAsByteArray();

        writer.dispose();
        imageOutStream.close();

    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
}

From source file:com.ackpdfbox.app.imageio.ImageIOUtil.java

/**
 * Writes a buffered image to a file using the given image format.
 * Compression is fixed for PNG, GIF, BMP and WBMP, dependent of the quality
 * parameter for JPG, and dependent of bit count for TIFF (a bitonal image
 * will be compressed with CCITT G4, a color image with LZW). Creating a
 * TIFF image is only supported if the jai_imageio library is in the class
 * path./*from   www  . j  a v a2s .  co  m*/
 *
 * @param image the image to be written
 * @param formatName the target format (ex. "png")
 * @param output the output stream to be used for writing
 * @param dpi the resolution in dpi (dots per inch) to be used in metadata
 * @param quality quality to be used when compressing the image (0 &lt;
 * quality &lt; 1.0f)
 * @return true if the image file was produced, false if there was an error.
 * @throws IOException if an I/O error occurs
 */
public static boolean writeImage(BufferedImage image, String formatName, OutputStream output, int dpi,
        float quality) throws IOException {
    ImageOutputStream imageOutput = null;
    ImageWriter writer = null;
    try {
        // find suitable image writer
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
        ImageWriteParam param = null;
        IIOMetadata metadata = null;
        // Loop until we get the best driver, i.e. one that supports
        // setting dpi in the standard metadata format; however we'd also 
        // accept a driver that can't, if a better one can't be found
        while (writers.hasNext()) {
            if (writer != null) {
                writer.dispose();
            }
            writer = writers.next();
            param = writer.getDefaultWriteParam();
            metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                break;
            }
        }
        if (writer == null) {
            LOG.error("No ImageWriter found for '" + formatName + "' format");
            StringBuilder sb = new StringBuilder();
            String[] writerFormatNames = ImageIO.getWriterFormatNames();
            for (String fmt : writerFormatNames) {
                sb.append(fmt);
                sb.append(' ');
            }
            LOG.error("Supported formats: " + sb);
            return false;
        }

        // compression
        if (param != null && param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            if (formatName.toLowerCase().startsWith("tif")) {
                // TIFF compression
                TIFFUtil.setCompressionType(param, image);
            } else {
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }
        }

        if (formatName.toLowerCase().startsWith("tif")) {
            // TIFF metadata
            TIFFUtil.updateMetadata(metadata, image, dpi);
        } else if ("jpeg".equals(formatName.toLowerCase()) || "jpg".equals(formatName.toLowerCase())) {
            // This segment must be run before other meta operations,
            // or else "IIOInvalidTreeException: Invalid node: app0JFIF"
            // The other (general) "meta" methods may not be used, because
            // this will break the reading of the meta data in tests
            JPEGUtil.updateMetadata(metadata, dpi);
        } else {
            // write metadata is possible
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                setDPI(metadata, dpi, formatName);
            }
        }

        // write
        imageOutput = ImageIO.createImageOutputStream(output);
        writer.setOutput(imageOutput);
        writer.write(null, new IIOImage(image, null, metadata), param);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (imageOutput != null) {
            imageOutput.close();
        }
    }
    return true;
}

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// w w w .j a  v  a  2  s.c  om
 @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:org.getobjects.appserver.publisher.GoDefaultRenderer.java

/**
 * Renders a java.awt.BufferedImage to the WOResponse of the given context.
 * Remember to configure:<pre>/*from ww  w .ja v a2  s. com*/
 *   -Djava.awt.headless=true</pre>
 * (thats the VM arguments of the run panel in Eclipse) 
 * 
 * @param _img   - the BufferedImage object to render
 * @param _ctx - the WOContext to render the image in
 * @return null if everything went fine, an Exception otherwise
 */
public Exception renderBufferedImage(BufferedImage _img, WOContext _ctx) {
    // TBD: this method could be improved a lot, but it works well enough for
    //      simple cases

    if (_img == null)
        return new GoInternalErrorException("got no image to render");

    /* find a proper image writer */

    String usedType = null;
    Iterator<ImageWriter> writers;
    ImageWriter writer = null;
    WORequest rq = _ctx.request();
    if (rq != null) {
        // TBD: just iterate over the accepted (image/) types (considering
        //      the value quality) and check each

        if (rq.acceptsContentType("image/png", false /* direct match */)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/png";
        }
        if (writer == null && rq.acceptsContentType("image/gif", false)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/gif")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/gif";
        }
        if (writer == null && rq.acceptsContentType("image/jpeg", false)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/jpeg")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/jpeg";
        }
    }
    if (writer == null) {
        if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null)
            writer = writers.next();
        if (writer != null)
            usedType = "image/png";
    }
    if (writer == null)
        return new GoInternalErrorException("found no writer for image: " + _img);

    /* prepare WOResponse */

    WOResponse r = _ctx.response();
    r.setStatus(WOMessage.HTTP_STATUS_OK);
    r.setHeaderForKey("inline", "content-disposition");
    if (usedType != null)
        r.setHeaderForKey(usedType, "content-type");
    // TBD: do we know the content-length? If not, should we generate to a
    //      buffer to avoid confusing the browser (IE ...)
    r.enableStreaming();

    /* write */

    ImageOutputStream ios = null;
    try {
        ios = ImageIO.createImageOutputStream(rq.outputStream());
    } catch (IOException e) {
        log.warn("could not create image output stream: " + _img);
        return e;
    }

    writer.setOutput(ios);

    try {
        writer.write(null, new IIOImage(_img, null, null), null);
        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        log.warn("failed to write image to stream", e);
        return e;
    }

    return null; /* everything is awesome O */
}

From source file:org.getobjects.appserver.publisher.JoDefaultRenderer.java

/**
 * Renders a java.awt.BufferedImage to the WOResponse of the given context.
 * Remember to configure:<pre>/*from w  w  w  .  j a v  a  2  s.  com*/
 *   -Djava.awt.headless=true</pre>
 * (thats the VM arguments of the run panel in Eclipse) 
 * 
 * @param _img   - the BufferedImage object to render
 * @param _ctx - the WOContext to render the image in
 * @return null if everything went fine, an Exception otherwise
 */
public Exception renderBufferedImage(BufferedImage _img, WOContext _ctx) {
    // TBD: this method could be improved a lot, but it works well enough for
    //      simple cases

    if (_img == null)
        return new JoInternalErrorException("got no image to render");

    /* find a proper image writer */

    String usedType = null;
    Iterator<ImageWriter> writers;
    ImageWriter writer = null;
    WORequest rq = _ctx.request();
    if (rq != null) {
        // TBD: just iterate over the accepted (image/) types (considering
        //      the value quality) and check each

        if (rq.acceptsContentType("image/png", false /* direct match */)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/png";
        }
        if (writer == null && rq.acceptsContentType("image/gif", false)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/gif")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/gif";
        }
        if (writer == null && rq.acceptsContentType("image/jpeg", false)) {
            if ((writers = ImageIO.getImageWritersByMIMEType("image/jpeg")) != null)
                writer = writers.next();
            if (writer != null)
                usedType = "image/jpeg";
        }
    }
    if (writer == null) {
        if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null)
            writer = writers.next();
        if (writer != null)
            usedType = "image/png";
    }
    if (writer == null)
        return new JoInternalErrorException("found no writer for image: " + _img);

    /* prepare WOResponse */

    WOResponse r = _ctx.response();
    r.setStatus(WOMessage.HTTP_STATUS_OK);
    r.setHeaderForKey("inline", "content-disposition");
    if (usedType != null)
        r.setHeaderForKey(usedType, "content-type");
    // TBD: do we know the content-length? If not, should we generate to a
    //      buffer to avoid confusing the browser (IE ...)
    r.enableStreaming();

    /* write */

    ImageOutputStream ios = null;
    try {
        ios = ImageIO.createImageOutputStream(rq.outputStream());
    } catch (IOException e) {
        log.warn("could not create image output stream: " + _img);
        return e;
    }

    writer.setOutput(ios);

    try {
        writer.write(null, new IIOImage(_img, null, null), null);
        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        log.warn("failed to write image to stream", e);
        return e;
    }

    return null; /* everything is awesome O */
}

From source file:lucee.runtime.img.Image.java

private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta)
        throws IOException, ExpressionException {
    if (quality < 0 || quality > 1)
        throw new IOException(
                "quality has an invalid value [" + quality + "], value has to be between 0 and 1");
    if (StringUtil.isEmpty(format))
        format = this.format;
    if (StringUtil.isEmpty(format))
        throw new IOException("missing format");

    BufferedImage im = image();/*from ww  w  . j a v  a2 s .  c o m*/

    //IIOMetadata meta = noMeta?null:metadata(format);
    IIOMetadata meta = noMeta ? null : getMetaData(null);

    ImageWriter writer = null;
    ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format);

    if (iter.hasNext()) {
        writer = iter.next();
    }
    if (writer == null)
        throw new IOException("no writer for format [" + format + "] available, available writer formats are ["
                + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]");

    ImageWriteParam iwp = null;
    if ("jpg".equalsIgnoreCase(format)) {
        ColorModel cm = im.getColorModel();
        if (cm.hasAlpha())
            im = jpgImage(im);
        JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault());
        jiwp.setOptimizeHuffmanTables(true);
        iwp = jiwp;
    } else
        iwp = writer.getDefaultWriteParam();

    setCompressionModeEL(iwp, ImageWriteParam.MODE_EXPLICIT);
    setCompressionQualityEL(iwp, quality);
    writer.setOutput(ios);
    try {
        writer.write(meta, new IIOImage(im, null, meta), iwp);

    } finally {
        writer.dispose();
        ios.flush();
    }
}

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 w  ww .  j  a  v  a 2 s. c  o m*/
    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;
    }
}