Example usage for java.awt AlphaComposite getInstance

List of usage examples for java.awt AlphaComposite getInstance

Introduction

In this page you can find the example usage for java.awt AlphaComposite getInstance.

Prototype

public static AlphaComposite getInstance(int rule, float alpha) 

Source Link

Document

Creates an AlphaComposite object with the specified rule and the constant alpha to multiply with the alpha of the source.

Usage

From source file:nl.b3p.imagetool.ImageTool.java

public static BufferedImage drawGeometries(BufferedImage bi, CombineImageSettings settings, int srid, Bbox bbox,
        int width, int height) throws Exception {
    List wktGeoms = settings.getWktGeoms();
    if (wktGeoms == null || wktGeoms.size() <= 0) {
        return bi;
    }/*  ww w  .  j  ava2  s. c  om*/
    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    //        BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gbi = newBufIm.createGraphics();
    gbi.drawImage(bi, 0, 0, null);
    for (int i = 0; i < wktGeoms.size(); i++) {
        gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        CombineImageWkt ciw = (CombineImageWkt) wktGeoms.get(i);
        Color color = settings.getDefaultWktGeomColor();
        if (ciw.getColor() != null) {
            color = ciw.getColor();
        }
        gbi.setColor(color);
        String wktGeom = ciw.getWktGeom();
        Geometry geom = geometrieFromText(wktGeom, srid);
        Shape shape = createImage(geom, srid, bbox, width, height);
        Point centerPoint = null;
        if (geom instanceof Polygon) {
            gbi.fill(shape);
        } else if (geom instanceof com.vividsolutions.jts.geom.Point) {
            centerPoint = calculateCenter(shape, srid, bbox, width, height);
            gbi.draw(new Ellipse2D.Double(centerPoint.getX(), centerPoint.getY(), 4, 4));
        } else {
            gbi.setStroke(new BasicStroke(3));
            gbi.draw(shape);
        }
        if (ciw.getLabel() != null) {
            if (centerPoint == null) {
                centerPoint = calculateCenter(shape, srid, bbox, width, height);
            }
            gbi.setColor(Color.black);
            gbi.drawString(ciw.getLabel(), (float) centerPoint.getX(), (float) centerPoint.getY());
        }
    }
    gbi.dispose();
    return newBufIm;
}

From source file:nl.b3p.viewer.image.ImageTool.java

public static BufferedImage drawGeometries(BufferedImage bi, CombineImageSettings settings, int srid, Bbox bbox,
        int width, int height) throws Exception {
    List wktGeoms = settings.getWktGeoms();
    if (wktGeoms == null || wktGeoms.size() <= 0) {
        return bi;
    }/* ww w  .ja va  2  s  .com*/
    BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
    //        BufferedImage newBufIm = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D gbi = newBufIm.createGraphics();
    gbi.drawImage(bi, 0, 0, null);
    for (int i = 0; i < wktGeoms.size(); i++) {
        gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
        CombineImageWkt ciw = (CombineImageWkt) wktGeoms.get(i);
        Color color = settings.getDefaultWktGeomColor();
        if (ciw.getColor() != null) {
            color = ciw.getColor();
        }
        gbi.setColor(color);
        String wktGeom = ciw.getWktGeom();
        Geometry geom = geometrieFromText(wktGeom, srid);
        Shape shape = createImage(geom, srid, bbox, width, height);
        Point centerPoint = null;
        if (geom instanceof Polygon) {
            gbi.fill(shape);
        } else if (geom instanceof com.vividsolutions.jts.geom.Point) {
            centerPoint = calculateCenter(shape, srid, bbox, width, height);
            gbi.fill(new Ellipse2D.Double(centerPoint.getX(), centerPoint.getY(), 8, 8));
        } else {
            float strokeWidth = ciw.getStrokeWidth() != null ? ciw.getStrokeWidth() : 3f;
            gbi.setStroke(new BasicStroke(strokeWidth));
            gbi.draw(shape);
        }
        if (ciw.getLabel() != null) {
            if (centerPoint == null) {
                centerPoint = calculateCenter(shape, srid, bbox, width, height);
            }
            gbi.setColor(Color.black);
            gbi.drawString(ciw.getLabel(), (float) centerPoint.getX(), (float) centerPoint.getY());
        }
    }
    gbi.dispose();
    return newBufIm;
}

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (mTimeFrame == null) {
        renderNoInfoView(g);/* w w  w. j  av  a  2s .  c  om*/
    } else {
        updateSize();
        LongRange startRange = mTimeFrame.getStartRange();
        LongRange arriveRange = mTimeFrame.getArriveRange();
        HashMap<LongRange, TimeSpan> startRanges = mTimeFrame
                .startTimespansToRangesMap(AnyTribe.getSingleton());
        HashMap<LongRange, TimeSpan> arriveRanges = mTimeFrame.arriveTimespansToRangesMap(null);
        long minValue = startRange.getMinimumLong();
        long maxValue = arriveRange.getMaximumLong();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(new TexturePaint(STROKED, new Rectangle(0, 0, 3, 3)));
        g2d.fillRect(0, 0, getWidth(), getHeight());

        //draw frame around the entire range
        renderRange(new LongRange(startRange.getMinimumLong(), arriveRange.getMaximumLong()), startRange,
                arriveRange, false, false, g2d, null, popupInfo);
        g2d.setColor(Constants.DS_BACK);
        popupInfo.clear();
        //fill start range
        renderRange(startRange, startRange, arriveRange, true, false, g2d, null, popupInfo);
        //fill arrive range
        renderRange(arriveRange, startRange, arriveRange, false, true, g2d, null, popupInfo);
        Paint p = g2d.getPaint();
        Iterator<LongRange> rangeKeys = startRanges.keySet().iterator();
        while (rangeKeys.hasNext()) {
            LongRange currentRange = rangeKeys.next();

            TimeSpan spanForRange = startRanges.get(currentRange);
            if (spanForRange != null) {
                if (spanForRange.isValidAtEveryDay()) {
                    g2d.setPaint(new TexturePaint(DAILY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                } else if (spanForRange.isValidAtExactTime()) {
                    g2d.setPaint(new TexturePaint(EXACT_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                } else {
                    g2d.setPaint(new TexturePaint(ONE_DAY_START_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
                }
            }
            renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo);
        }

        Composite c = g2d.getComposite();
        rangeKeys = arriveRanges.keySet().iterator();
        while (rangeKeys.hasNext()) {
            LongRange currentRange = rangeKeys.next();
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
            g2d.setPaint(new TexturePaint(ARRIVE_FRAME_FILL, new Rectangle(0, 0, 3, 3)));
            TimeSpan spanForRange = arriveRanges.get(currentRange);
            renderRange(currentRange, startRange, arriveRange, false, false, g2d, spanForRange, popupInfo);
        }
        g2d.setComposite(c);
        g2d.setPaint(p);
        renderDayMarkers(minValue, maxValue, g2d);
        renderPopup(popupInfo, g2d);
    }
}

From source file:org.tsho.dmc2.core.chart.AbstractDmcPlot.java

public void drawPlot(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) {
    Object originalAntialiasHint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);

    if (plotAntialias) {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    } else {//  ww  w. j a v  a2 s.c  om
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    }

    Composite originalComposite = g2.getComposite();
    if (alpha == true) {
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha()));
    }

    /* if automatic bounds... */
    if (!isNoData()) {
        if (this instanceof DmcRenderablePlot) {
            DmcPlotRenderer renderer;
            renderer = ((DmcRenderablePlot) this).getPlotRenderer();
            if (renderer != null) {
                renderer.initialize();
            }
        }
    }

    g2.setStroke(stroke);
    g2.setPaint(paint);
    render(g2, dataArea, info); /** This is where the computations method is called.*/
    g2.setComposite(originalComposite);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, originalAntialiasHint);
}

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

public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);/*from w  w  w .  java  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:org.openmeetings.app.data.record.BatikMethods.java

public void drawThickLine2D(Graphics2D g2d, double x1, double y1, double x2, double y2, int width, Color c,
        double xObj, double yObj, float alpha) throws Exception {
    g2d.setPaint(c);/*from  ww w. ja  v  a  2 s .c o  m*/

    int[] rules = new int[8];

    //all possible Compositing Rules:
    rules[0] = AlphaComposite.SRC_OVER;
    rules[1] = AlphaComposite.DST_OVER;
    rules[2] = AlphaComposite.CLEAR;
    rules[3] = AlphaComposite.SRC;
    rules[4] = AlphaComposite.SRC_IN;
    rules[5] = AlphaComposite.DST_IN;
    rules[6] = AlphaComposite.SRC_OUT;
    rules[7] = AlphaComposite.DST_OUT;

    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, alpha));
    g2d.setStroke(new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
    Line2D line = new Line2D.Double(x1 + xObj, y1 + yObj, x2 + xObj, y2 + yObj);
    g2d.draw(line);
}

From source file:org.kalypsodeegree_impl.graphics.displayelements.RasterDisplayElement_Impl.java

private void paintGrid(final Graphics2D g, final IGeoGrid grid, final GeoTransform projection,
        final String mapSRS, final IProgressMonitor monitor)
        throws GeoGridException, CoreException, FilterEvaluationException {
    /* Progress monitor. */
    final SubMonitor progress = SubMonitor.convert(monitor, "Painting grid", 100);

    /* Get the envelope of the surface of the grid (it is transformed). */
    final GM_Polygon gridSurface = grid.getSurface(mapSRS);

    final Composite oldAlphaComposite = g.getComposite();
    try {//from  w w  w.ja  va2 s  . co m
        final JTSTransformer map2GridTransformer = new JTSTransformer(mapSRS, grid.getSourceCRS());

        final float opacity = getOpacity();
        if (!Double.isNaN(opacity))
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

        paintRaster(g, grid, projection, gridSurface, mapSRS, map2GridTransformer,
                progress.newChild(95, SubMonitor.SUPPRESS_NONE));
    } catch (final FactoryException | TransformException e) {
        final IStatus status = new Status(IStatus.ERROR, KalypsoDeegreePlugin.getID(),
                "Failed to initialize geo transformer", e); //$NON-NLS-1$
        throw new CoreException(status);
    } finally {
        g.setComposite(oldAlphaComposite);
    }

    // TODO Tricky: apply opacityFactor to imageOutline as well?
    final RasterSymbolizer symbolizer = (RasterSymbolizer) getSymbolizer();
    final Symbolizer imageOutline = symbolizer.getImageOutline();
    paintImageOutline(g, gridSurface, projection, imageOutline, progress.newChild(5, SubMonitor.SUPPRESS_NONE));
}

From source file:org.polymap.service.geoserver.spring.PipelineMapProducer.java

public void writeTo(final OutputStream out) throws ServiceException, IOException {
    Timer timer = new Timer();

    // single layer? -> request ENCODED_IMAGE
    if (mapContext.getLayerCount() == 1) {
        MapLayer mapLayer = mapContext.getLayers()[0];
        ILayer layer = loader.findLayer(mapLayer);
        try {//from  ww w  . j  a v  a 2 s.  c om
            Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.ENCODED_IMAGE);

            ProcessorRequest request = prepareProcessorRequest();
            pipeline.process(request, new ResponseHandler() {
                public void handle(ProcessorResponse pipeResponse) throws Exception {

                    HttpServletResponse response = GeoServerWms.response.get();
                    if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                        log.info("Response: 304!");
                        response.setStatus(304);
                    } else {
                        long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                        // allow caches and browser clients to cache for 1h
                        //response.setHeader( "Cache-Control", "public,max-age=3600" );
                        if (lastModified > 0) {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Last-Modified", lastModified);
                        } else {
                            response.setHeader("Cache-Control", "no-cache,must-revalidate");
                            response.setDateHeader("Expires", 0);
                        }

                        byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                        int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                        out.write(chunk, 0, len);
                    }
                }
            });
            log.debug("    flushing response stream. (" + timer.elapsedTime() + "ms)");
            out.flush();
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    // multiple layers -> render into one image
    else {
        List<Job> jobs = new ArrayList();
        final Map<MapLayer, Image> images = new HashMap();

        // run jobs for all layers
        for (final MapLayer mapLayer : mapContext.getLayers()) {
            final ILayer layer = loader.findLayer(mapLayer);
            // job
            UIJob job = new UIJob(getClass().getSimpleName() + ": " + layer.getLabel()) {
                protected void runWithException(IProgressMonitor monitor) throws Exception {
                    try {
                        // XXX this excludes Cache304 (which support EncodedImageResponse only)
                        Pipeline pipeline = loader.getOrCreatePipeline(layer, LayerUseCase.IMAGE);

                        GetMapRequest targetRequest = prepareProcessorRequest();
                        pipeline.process(targetRequest, new ResponseHandler() {
                            public void handle(ProcessorResponse pipeResponse) throws Exception {
                                Image layerImage = ((ImageResponse) pipeResponse).getImage();
                                images.put(mapLayer, layerImage);
                            }
                        });
                    } catch (Exception e) {
                        // XXX put a special image in the map
                        log.warn("", e);
                        images.put(mapLayer, null);
                        throw e;
                    }
                }
            };
            job.schedule();
            jobs.add(job);
        }

        // join jobs
        for (Job job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                // XXX put a special image in the map
                log.warn("", e);
            }
        }

        // put images together (MapContext order)
        Graphics2D g = null;
        try {
            // result image
            BufferedImage result = ImageUtils.createImage(mapContext.getMapWidth(), mapContext.getMapHeight(),
                    null, true);
            g = result.createGraphics();

            // rendering hints
            RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
            hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
            g.setRenderingHints(hints);

            for (MapLayer mapLayer : mapContext.getLayers()) {
                Image layerImage = images.get(mapLayer);

                // load image data
                //                  new javax.swing.ImageIcon( image ).getImage();

                ILayer layer = loader.findLayer(mapLayer);
                int rule = AlphaComposite.SRC_OVER;
                float alpha = ((float) layer.getOpacity()) / 100;

                g.setComposite(AlphaComposite.getInstance(rule, alpha));
                g.drawImage(layerImage, 0, 0, null);
            }
            encodeImage(result, out);
        } finally {
            if (g != null) {
                g.dispose();
            }
        }
    }
}

From source file:net.shopxx.util.ImageUtil.java

/**
 * ?// w w w  .  j a v a  2  s.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.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        return;
    }
    if (type == Type.jdk) {
        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 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 / 100.0F));

            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);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 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:iqq.util.ImageUtil.java

/**
 * ?//from w  ww  . j  ava 2s  . c  om
 *
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public synchronized static void addWatermark(File srcFile, File destFile, InputStream watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    //watermarkFile == null || !watermarkFile.exists() || 
    if (!srcFile.exists() || watermarkFile == null || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        Log.println("addWatermark null");
        return;
    }
    if (type == Type.jdk) {
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            if (srcBufferedImage == null) {
                return;
            }
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D 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 / 100.0F));

            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);
            graphics2D.dispose();

            FileOutputStream out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(destBufferedImage);
            param.setQuality((float) DEST_QUALITY / 100, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(destBufferedImage);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 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);
        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();
            }
        }
    }
}