Example usage for javax.imageio ImageWriter dispose

List of usage examples for javax.imageio ImageWriter dispose

Introduction

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

Prototype

public void dispose() 

Source Link

Document

Allows any resources held by this object to be released.

Usage

From source file:net.rptools.tokentool.AppActions.java

public static void saveToken(File rptok_file, boolean overwrite) {
    if (rptok_file != null) {
        if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) {
            rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok");
        }/*from  ww w  . j a va  2s.  co m*/

        if (rptok_file.exists() && !overwrite) {
            if (!TokenTool.confirm("File exists.  Overwrite?")) {
                return;
            } else {
                rptok_file.delete();
            }
        }

        String tokenName = FilenameUtils.removeExtension(rptok_file.getName());

        try {
            // Write out the token image first or aka POG image.
            File tokenImageFile = File.createTempFile("tokenImage", ".png");

            // PW: This code addes the pHYs chunk to the
            // output png file with X & Y dpi set.
            BufferedImage tokenImg = TokenTool.getFrame().getComposedToken();
            BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage();

            ImageWriter writer = getImageWriterBySuffix("png");
            // Created object for outputStream so we can properly close it! No longer locks .png files until app closes!
            ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();

            PNGMetadata png = new PNGMetadata();
            // 39.375 inches per meter
            // I'm using the image width for the DPI under
            // the assumption that the token fits within
            // one cell.
            int resX = (int) (tokenImg.getWidth() * 39.375f);
            png.pHYs_pixelsPerUnitXAxis = resX;
            png.pHYs_pixelsPerUnitYAxis = resX;
            png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown"
            png.pHYs_present = true;

            writer.write(null, new IIOImage(tokenImg, null, png), param);
            ios.close();

            // Now write out the Portrait image, here we'll use JPEG to save space
            File portraitImageFile = File.createTempFile("portraitImage", ".jpg");
            writer.reset();
            writer = getImageWriterBySuffix("jpg");
            ios = ImageIO.createImageOutputStream(portraitImageFile);
            writer.setOutput(ios);
            param = writer.getDefaultWriteParam();

            writer.write(null, new IIOImage(portraitImg, null, null), param);
            writer.dispose();
            ios.close();

            // Lets create the token!
            Token _token = new Token();
            Asset tokenImage = null;
            tokenImage = AssetManager.createAsset(tokenImageFile);
            AssetManager.putAsset(tokenImage);
            _token = new Token(tokenName, tokenImage.getId());
            _token.setGMName(tokenName);

            // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool
            //_token.setImageAsset(tokenImage.getName());
            //_token.setImageAsset(tokenImage.getName(), tokenImage.getId());

            // set the image shape
            Image image = ImageIO.read(tokenImageFile);
            _token.setShape(TokenUtil.guessTokenType(image));

            // set the height/width, fixes dragging to stamp layer issue
            _token.setHeight(tokenImg.getHeight());
            _token.setWidth(tokenImg.getWidth());

            // set the portrait image asset
            Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait
            AssetManager.putAsset(portrait);
            _token.setPortraitImage(portrait.getId());

            // Time to write out the .rptok token file...
            PackedFile pakFile = null;
            try {
                pakFile = new PackedFile(rptok_file);
                saveAssets(_token.getAllImageAssets(), pakFile);
                pakFile.setContent(_token);
                BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null);
                pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png"));
                pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION);
                pakFile.save();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (pakFile != null)
                    pakFile.close();
                tokenImageFile.delete();
                portraitImageFile.delete();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
            TokenTool.showError("Unable to write image: " + ioe);
        }
    }
}

From source file:jails.http.converter.BufferedImageHttpMessageConverter.java

public void write(BufferedImage image, MediaType contentType, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    if (contentType == null) {
        contentType = getDefaultContentType();
    }//from ww  w  .  jav  a 2s  .c o  m
    Assert.notNull(contentType,
            "Count not determine Content-Type, set one using the 'defaultContentType' property");
    outputMessage.getHeaders().setContentType(contentType);
    ImageOutputStream imageOutputStream = null;
    ImageWriter imageWriter = null;
    try {
        imageOutputStream = createImageOutputStream(outputMessage.getBody());
        Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString());
        if (imageWriters.hasNext()) {
            imageWriter = imageWriters.next();
            ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
            process(iwp);
            imageWriter.setOutput(imageOutputStream);
            imageWriter.write(null, new IIOImage(image, null, null), iwp);
        } else {
            throw new HttpMessageNotWritableException(
                    "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
        }
    } finally {
        if (imageWriter != null) {
            imageWriter.dispose();
        }
        if (imageOutputStream != null) {
            try {
                imageOutputStream.close();
            } catch (IOException ex) {
                // ignore
            }
        }
    }
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void saveJPG(BufferedImage img, File file) {
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {/*w ww .  ja v a  2 s  . c  om*/
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(1);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(img, null, null);
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.dispose();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi//  www. j ava  2  s. c om
 * @param filename
 * @param dEncRate
 * @param lossless
 * @throws IOException
 */
public static void storeBIAsJP2File(BufferedImage bi, String filename, double dEncRate, boolean lossless)
        throws IOException {

    if (hasJPEG2000FileTag(filename)) {

        IIOImage iioImage = new IIOImage(bi, null, null);

        ImageWriter jp2iw = ImageIO.getImageWritersBySuffix("jp2").next();
        J2KImageWriteParam writeParam = (J2KImageWriteParam) jp2iw.getDefaultWriteParam();

        // Indicates using the lossless scheme or not. It is equivalent to use reversible quantization and 5x3 integer wavelet filters. The default is true.
        writeParam.setLossless(lossless);

        if (lossless)
            writeParam.setFilter(J2KImageWriteParam.FILTER_53); // Specifies which wavelet filters to use for the specified tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters.
        else
            writeParam.setFilter(J2KImageWriteParam.FILTER_97);

        if (!lossless) {
            // The bitrate in bits-per-pixel for encoding. Should be set when lossy compression scheme is used. With the default value Double.MAX_VALUE, a lossless compression will be done.
            writeParam.setEncodingRate(dEncRate);

            // changes in compression rate are done in the following way
            // however JPEG2000 implementation seems not to support this <-- no differences visible
            //                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //                writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            //                writeParam.setCompressionQuality(1.0f);
        }

        ImageOutputStream ios = null;
        try {
            ios = new FileImageOutputStream(new File(filename));
            jp2iw.setOutput(ios);
            jp2iw.write(null, iioImage, writeParam);
            jp2iw.dispose();
            ios.flush();
        } finally {
            if (ios != null)
                ios.close();
        }
    } else
        System.err.println("please name your file as valid JPEG2000 file: ends with .jp2");
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*from   w  ww .  j a v a  2 s  .  c om*/
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.yamj.core.service.file.FileStorageService.java

public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat,
        int quality) throws Exception {
    LOG.debug("Store {} {} image: {}", type, imageFormat, filename);
    String storageFileName = getStorageName(type, filename);
    File outputFile = new File(storageFileName);

    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {//from ww w .  j av  a2s .c  o  m
        if (ImageFormat.PNG == imageFormat) {
            ImageIO.write(bi, "png", outputFile);
        } else {
            float jpegQuality = (float) quality / 100;
            BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            bufImage.createGraphics().drawImage(bi, 0, 0, null, null);

            @SuppressWarnings("rawtypes")
            Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
            writer = (ImageWriter) iter.next();

            ImageWriteParam iwp = writer.getDefaultWriteParam();
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            iwp.setCompressionQuality(jpegQuality);

            output = new FileImageOutputStream(outputFile);
            writer.setOutput(output);
            IIOImage image = new IIOImage(bufImage, null, null);
            writer.write(null, image, iwp);
        }
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                LOG.trace("Failed to close stream: {}", ex.getMessage(), ex);
            }
        }
    }
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);/*ww  w .j a v  a  2s . c o  m*/
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists()) {
        try {
            FileUtils.copyFile(srcFile, destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;

            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(watermarkFile.getPath());
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.groupbuy.util.ImageUtils.java

/**
 * //from   w w  w .  jav  a2  s. co m
 * 
 * @param srcFile
 *            ?
 * @param destFile
 *            
 * @param destWidth
 *            
 * @param destHeight
 *            
 */
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * /*from   ww w.j  a v a 2s. c  o m*/
 * 
 * @param srcFile ?
 * @param destFile 
 * @param destWidth 
 * @param destHeight 
 */
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);

    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) {
    try {/*from w  w w .  j a  v  a 2  s.c  o m*/

        long start = System.currentTimeMillis();

        // Find a jpeg writer
        ImageWriter writer = null;
        Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        }

        // Prepare output file
        ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
        writer.setOutput(ios);

        // Set the compression quality
        ImageWriteParam iwparam = new MyImageWriteParam();
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(compressionQuality);

        // Write the image
        writer.write(null, new IIOImage(bufferedImage, null, null), null);

        // Cleanup
        ios.flush();
        writer.dispose();
        ios.close();

        System.out.println(System.currentTimeMillis() - start);

    } catch (IOException e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }

}