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:net.filterlogic.util.imaging.ToTIFF.java

/**
 * //from  w w  w.jav a 2s .  c om
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream ios = null;
        BufferedImage img = null;

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Cache image./*from   ww  w  .jav  a 2s.  c  o  m*/
 * 
 * @param mf
 *          the media file
 * @return the file the cached file
 * @throws Exception
 */
public static Path cacheImage(Path originalFile) throws Exception {
    MediaFile mf = new MediaFile(originalFile);
    Path cachedFile = ImageCache.getCacheDir()
            .resolve(getMD5(originalFile.toString()) + "." + Utils.getExtension(originalFile));
    if (!Files.exists(cachedFile)) {
        // check if the original file exists && size > 0
        if (!Files.exists(originalFile)) {
            throw new FileNotFoundException("unable to cache file: " + originalFile + "; file does not exist");
        }
        if (Files.size(originalFile) == 0) {
            throw new EmptyFileException(originalFile);
        }

        // recreate cache dir if needed
        // rescale & cache
        BufferedImage originalImage = null;
        try {
            originalImage = createImage(originalFile);
        } catch (Exception e) {
            throw new Exception("cannot create image - file seems not to be valid? " + originalFile);
        }

        // calculate width based on MF type
        int desiredWidth = originalImage.getWidth(); // initialize with fallback
        switch (mf.getType()) {
        case FANART:
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
            break;

        case POSTER:
            if (originalImage.getHeight() > 500) {
                desiredWidth = 350;
            }
            break;

        case EXTRAFANART:
        case THUMB:
        case BANNER:
        case GRAPHIC:
            desiredWidth = 300;
            break;

        default:
            break;
        }

        // special handling for movieset-fanart or movieset-poster
        if (mf.getFilename().startsWith("movieset-fanart") || mf.getFilename().startsWith("movieset-poster")) {
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
        }

        Point size = calculateSize(desiredWidth, (int) (originalImage.getHeight() / 1.5),
                originalImage.getWidth(), originalImage.getHeight(), true);
        BufferedImage scaledImage = null;

        if (Globals.settings.getImageCacheType() == CacheType.FAST) {
            // scale fast
            scaledImage = Scalr.resize(originalImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        } else {
            // scale with good quality
            scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        }
        originalImage = null;

        ImageWriter imgWrtr = null;
        ImageWriteParam imgWrtrPrm = null;

        // here we have two different ways to create our thumb
        // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
        // b) a scaled down png (with transparency) which we can store without any more modifying as png
        if (hasTransparentPixels(scaledImage)) {
            // transparent image -> png
            imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
            imgWrtrPrm = imgWrtr.getDefaultWriteParam();

        } else {
            // non transparent image -> jpg
            // convert to rgb
            BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            ColorConvertOp xformOp = new ColorConvertOp(null);
            xformOp.filter(scaledImage, rgb);
            imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
            imgWrtrPrm = imgWrtr.getDefaultWriteParam();
            imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
            imgWrtrPrm.setCompressionQuality(0.80f);

            scaledImage = rgb;
        }

        FileImageOutputStream output = new FileImageOutputStream(cachedFile.toFile());
        imgWrtr.setOutput(output);
        IIOImage image = new IIOImage(scaledImage, null, null);
        imgWrtr.write(null, image, imgWrtrPrm);
        imgWrtr.dispose();
        output.flush();
        output.close();
        scaledImage = null;
    }

    if (!Files.exists(cachedFile)) {
        throw new Exception("unable to cache file: " + originalFile);
    }

    return cachedFile;
}

From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java

/**
 * This method create thumbImage of the image file given and save it in outFile.
 * Compression quality is also given. thumbBounds is used for calculating the size of the thumb.
 * // w ww . j a v  a  2 s.  c  om
 * @param infile slide image to create thumb
 * @param outfile output thumb file
 * @param compressionQuality the compression quality
 * @param thumbBounds the thumb bounds
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds)
        throws IOException {
    // Retrieve jpg image to be resized
    Image image = ImageIO.read(infile);

    // get original image size for thumb size calculation
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);

    float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight);

    int thumbWidth = (int) (imageWidth * thumbRatio);
    int thumbHeight = (int) (imageHeight * thumbRatio);

    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

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

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

    // Prepare output file
    ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
    writer.setOutput(ios);
    // write to the thumb image 
    writer.write(thumbImage);

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

From source file:org.geowebcache.layer.MetaTile.java

/**
 * Outputs one tile from the internal array of tiles to a provided stream
 * //www  . j  a v  a  2 s  .  co m
 * @param tileIdx
 *            the index of the tile relative to the internal array
 * @param format
 *            the Java name for the format
 * @param resource
 *            the outputstream
 * @return true if no error was encountered
 * @throws IOException
 */
public boolean writeTileToStream(final int tileIdx, Resource target) throws IOException {
    if (tiles == null) {
        return false;
    }
    String format = responseFormat.getInternalName();

    if (log.isDebugEnabled()) {
        log.debug("Thread: " + Thread.currentThread().getName() + " writing: " + tileIdx);
    }

    // TODO should we recycle the writers ?
    // GR: it'd be only a 2% perf gain according to profile   
    Iterator<ImageWriter> it = javax.imageio.ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = it.next();
    ImageWriteParam param = writer.getDefaultWriteParam();

    if (this.formatModifier != null) {
        param = formatModifier.adjustImageWriteParam(param);
    }

    Rectangle tileRegion = tiles[tileIdx];
    RenderedImage tile = createTile(tileRegion.x, tileRegion.y, tileRegion.width, tileRegion.height);
    disposeLater(tile);
    OutputStream outputStream = target.getOutputStream();
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outputStream);
    writer.setOutput(imgOut);
    IIOImage image = new IIOImage(tile, null, null);
    try {
        writer.write(null, image, param);
    } finally {
        imgOut.close();
        writer.dispose();
    }

    return true;
}

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

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi/*from  w  ww  .ja  v  a 2 s.  c o  m*/
 * @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:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) {
    try {/*from  w  ww.ja  v  a 2  s . co  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();
    }

}

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  w w w . j  av a  2  s.  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:net.groupbuy.util.ImageUtils.java

/**
 * ?/*from   w w w .  j  a v a  2  s . c o  m*/
 * 
 * @param srcFile
 *            ?
 * @param destFile
 *            
 * @param watermarkFile
 *            ?
 * @param watermarkPosition
 *            ??
 * @param alpha
 *            ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        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;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                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 {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        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:com.el.ecom.utils.ImageUtils.java

/**
 * ?// ww w . j av  a 2s. co  m
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        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;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                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) {
            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 {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.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 {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.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);
            }
        }
    }
}