List of usage examples for java.awt Graphics2D dispose
public abstract void dispose();
From source file:com.isti.traceview.common.TraceViewChartPanel.java
/** * Handles a 'mouse released' event. On Windows, we need to check if this is a popup trigger, * but only if we haven't already been tracking a zoom rectangle. * //from w w w. ja v a 2s .c o m * @param e * information about the event. */ public void mouseReleased(MouseEvent e) { if (this.zoomRectangle != null) { boolean hZoom = false; boolean vZoom = false; if (this.orientation == PlotOrientation.HORIZONTAL) { hZoom = this.rangeZoomable; vZoom = this.domainZoomable; } else { hZoom = this.domainZoomable; vZoom = this.rangeZoomable; } boolean zoomTrigger1 = hZoom && Math.abs(e.getX() - this.zoomPoint.getX()) >= this.zoomTriggerDistance; boolean zoomTrigger2 = vZoom && Math.abs(e.getY() - this.zoomPoint.getY()) >= this.zoomTriggerDistance; if (zoomTrigger1 || zoomTrigger2) { if ((hZoom && (e.getX() < this.zoomPoint.getX())) || (vZoom && (e.getY() < this.zoomPoint.getY()))) { restoreAutoBounds(); } else { double x, y, w, h; Rectangle2D screenDataArea = getScreenDataArea((int) this.zoomPoint.getX(), (int) this.zoomPoint.getY()); // for mouseReleased event, (horizontalZoom || verticalZoom) // will be true, so we can just test for either being false; // otherwise both are true if (!vZoom) { x = this.zoomPoint.getX(); y = screenDataArea.getMinY(); w = Math.min(this.zoomRectangle.getWidth(), screenDataArea.getMaxX() - this.zoomPoint.getX()); h = screenDataArea.getHeight(); } else if (!hZoom) { x = screenDataArea.getMinX(); y = this.zoomPoint.getY(); w = screenDataArea.getWidth(); h = Math.min(this.zoomRectangle.getHeight(), screenDataArea.getMaxY() - this.zoomPoint.getY()); } else { x = this.zoomPoint.getX(); y = this.zoomPoint.getY(); w = Math.min(this.zoomRectangle.getWidth(), screenDataArea.getMaxX() - this.zoomPoint.getX()); h = Math.min(this.zoomRectangle.getHeight(), screenDataArea.getMaxY() - this.zoomPoint.getY()); } Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h); zoom(zoomArea); } this.zoomPoint = null; this.zoomRectangle = null; } else { // Erase the zoom rectangle Graphics2D g2 = (Graphics2D) getGraphics(); drawZoomRectangle(g2); g2.dispose(); this.zoomPoint = null; this.zoomRectangle = null; } } else if (e.isPopupTrigger()) { if (this.popup != null) { displayPopupMenu(e.getX(), e.getY()); } } }
From source file:com.lizardtech.expresszip.model.Job.java
private void exportTile(TileExport t, String jobName, String format, int counter) throws Exception { if (shutdown) throw new RuntimeException("Cancelled"); ReferencedEnvelope tileBounds = null; Rectangle imageBounds = null; double minx = Math.min(t.bounds.getLeft(), t.bounds.getRight()); double maxx = Math.max(t.bounds.getLeft(), t.bounds.getRight()); double miny = Math.min(t.bounds.getTop(), t.bounds.getBottom()); double maxy = Math.max(t.bounds.getTop(), t.bounds.getBottom()); logger.info(String.format("Adding tile %d x: %f - %f, y: %f - %f", counter, minx, maxx, miny, maxy)); if (jobParams.isProjectedCRS(CRS.decode(jobParams.getMapProjection()))) { tileBounds = new ReferencedEnvelope(t.bounds.getLeft(), t.bounds.getRight(), t.bounds.getTop(), t.bounds.getBottom(), CRS.decode(jobParams.getMapProjection())); } else {//from ww w . j ava 2s . c o m tileBounds = new ReferencedEnvelope(minx, maxx, miny, maxy, CRS.decode(jobParams.getMapProjection())); } // Set view point on map MapViewport viewport = new MapViewport(tileBounds); viewport.setCoordinateReferenceSystem(CRS.decode(jobParams.getMapProjection())); // Create the bound for the image imageBounds = new Rectangle(0, 0, t.width, t.height); // Set up an ImageBuffer to write image to logger.info( String.format("Allocating BufferedImage of size %d x %d", imageBounds.width, imageBounds.height)); int bufferType = BufferedImage.TYPE_INT_RGB; if (extensions.valueOf(format) == extensions.png) bufferType = BufferedImage.TYPE_INT_ARGB; BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, bufferType); Graphics2D graphics = image.createGraphics(); // Render the unclipped image MapContent map = new MapContent(); map.setViewport(viewport); WebMapServer wms = new WebMapServer(MapModel.getPrivateServerURL(), getWMSTimeOut()); WMSLayer wmsLayer = null; for (ExpressZipLayer l : jobParams.getEnabledLayers()) { if (l instanceof RasterLayer && l.projectionIsSupported(jobParams.getMapProjection())) { if (wmsLayer == null) wmsLayer = new WMSLayer(wms, l.getGeoToolsLayer()); else wmsLayer.addLayer(l.getGeoToolsLayer()); } } if (wmsLayer != null) map.addLayer(wmsLayer); GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); renderer.addRenderListener(new RenderListener() { @Override public void featureRenderer(SimpleFeature feature) { } @Override public void errorOccurred(Exception e) { logger.error("Streaming Renderer for tile failed (" + e.getMessage() + ")"); throw new RuntimeException(e); } }); try { renderer.paint(graphics, imageBounds, tileBounds); } finally { try { // clean up graphics.dispose(); } catch (Exception e) { } try { map.dispose(); } catch (Exception e) { } } // Clip the image to the shapefile if (cropFile != null) { FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = getFeatureSource(cropFile); GridCoverage2D clippedCoverage = (GridCoverage2D) clipImageToFeatureSource(image, tileBounds, featureSource); if (null == clippedCoverage) { logger.info("Tile does not intersect shapefile. Skipping."); return; } BufferedImage matted = mattCroppedImage(image, clippedCoverage, bufferType); image = matted; } // Save the image String fileBase = ""; File fileToSave = null; try { do { fileBase = jobName; if (counter > 0) fileBase = fileBase + "_" + counter; fileToSave = new File(exportDir, fileBase + "." + format); counter++; } while (!fileToSave.createNewFile()); logger.info(String.format("Writing image %s", fileToSave.getAbsolutePath())); GridCoverageFactory factory = new GridCoverageFactory(); GridCoverage2D coverage = factory.create("LT", image, tileBounds); AbstractGridCoverageWriter coverageWriter = null; GeneralParameterValue[] formatParam = null; if (format.equals(extensions.tif.toString())) { ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()) .setValue(geoTiffWPs); coverageWriter = new GeoTiffWriter(fileToSave); formatParam = (GeneralParameterValue[]) params.values().toArray(new GeneralParameterValue[1]); } else { ParameterValueGroup params = new WorldImageFormat().getWriteParameters(); params.parameter(WorldImageFormat.FORMAT.getName().toString()).setValue(format); formatParam = new GeneralParameterValue[] { params.parameter(WorldImageFormat.FORMAT.getName().toString()) }; coverageWriter = new WorldImageWriter(fileToSave); } try { coverageWriter.write(coverage, formatParam); } finally { try { coverageWriter.dispose(); } catch (Exception e) { } try { coverage.dispose(true); } catch (Exception e) { } } } catch (Exception e) { logger.error( String.format("FAILED writing image %s (%s)", fileToSave.getAbsolutePath(), e.getMessage())); throw new RuntimeException(e); } // Gather up fileBase.* (include world and prj filenames) for zip file for (File child : exportDir.listFiles()) { String childName = child.getName(); String baseName = FilenameUtils.getBaseName(childName); if (child.isFile() && baseName.equals(fileBase)) { String extension = FilenameUtils.getExtension(childName); extension.toLowerCase(); if (extension.length() == 4 && extension.endsWith("w")) { extension = extension.substring(0, 1) + extension.substring(2); File renamedChild = new File(exportDir, baseName + "." + extension); child.renameTo(renamedChild); child = renamedChild; } outputTiles.add(child.getName()); } } }
From source file:net.geoprism.dashboard.DashboardMap.java
private BufferedImage getLegendTitleImage(DashboardLayer layer) { FontMetrics fm;//from www .ja v a2s .com int textWidth; int textHeight; int textBoxHorizontalPadding = 4; int textBoxVerticalPadding = 4; int borderWidth = 2; int paddedTitleHeight; int paddedTitleWidth; int titleLeftPadding = textBoxHorizontalPadding; BufferedImage newLegendTitleBase; Graphics2D newLegendTitleBaseGraphic = null; try { // Build the Font object Font titleFont = new Font(layer.getName(), Font.BOLD, 14); // Build variables for base legend graphic construction try { newLegendTitleBase = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); newLegendTitleBaseGraphic = newLegendTitleBase.createGraphics(); newLegendTitleBaseGraphic.setFont(titleFont); fm = newLegendTitleBaseGraphic.getFontMetrics(); textHeight = fm.getHeight(); textWidth = fm.stringWidth(layer.getName()); paddedTitleWidth = textWidth + (textBoxHorizontalPadding * 2) + (borderWidth * 2); paddedTitleHeight = textHeight + (textBoxVerticalPadding * 2) + (borderWidth * 2); } finally { // dispose of temporary graphics context if (newLegendTitleBaseGraphic != null) { newLegendTitleBaseGraphic.dispose(); } } titleLeftPadding = ((paddedTitleWidth / 2) - ((textWidth + (textBoxHorizontalPadding * 2) + (borderWidth * 2)) / 2)) + textBoxHorizontalPadding; newLegendTitleBase = new BufferedImage(paddedTitleWidth, paddedTitleHeight, BufferedImage.TYPE_INT_ARGB); newLegendTitleBaseGraphic = newLegendTitleBase.createGraphics(); newLegendTitleBaseGraphic.drawImage(newLegendTitleBase, 0, 0, null); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); newLegendTitleBaseGraphic.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); newLegendTitleBaseGraphic.setFont(titleFont); // draw title text fm = newLegendTitleBaseGraphic.getFontMetrics(); newLegendTitleBaseGraphic.setColor(Color.WHITE); newLegendTitleBaseGraphic.drawString(layer.getName(), titleLeftPadding, fm.getAscent() + textBoxVerticalPadding); newLegendTitleBaseGraphic.drawImage(newLegendTitleBase, 0, 0, null); } finally { if (newLegendTitleBaseGraphic != null) { newLegendTitleBaseGraphic.dispose(); } } return newLegendTitleBase; }
From source file:com.moviejukebox.plugin.DefaultImagePlugin.java
/** * Draw the appropriate HD logo onto the image file * * @param movie The source movie/* w w w . j a va2 s . com*/ * @param bi The original image * @param addOtherLogo Do we need to draw the TV logo as well? * @return The new image file */ private BufferedImage drawLogoHD(Movie movie, BufferedImage bi, Boolean addOtherLogo) { // If the movie isn't high definition, then quit if (!movie.isHD()) { return bi; } String logoFilename; File logoFile; // Determine which logo to use. if (highdefDiff) { if (movie.isHD1080()) { // Use the 1080p logo logoFilename = FILENAME_HD1080; } else { // Otherwise use the 720p logoFilename = FILENAME_HD720; } } else { // We don't care, so use the default HD logo. logoFilename = FILENAME_HD; } logoFile = new File(getResourcesPath() + logoFilename); if (!logoFile.exists()) { LOG.debug("Missing HD logo ({}) using default {}", logoFilename, FILENAME_HD); logoFilename = FILENAME_HD; } try { BufferedImage biHd = GraphicTools.loadJPEGImage(getResourcesPath() + logoFilename); Graphics2D g2d = bi.createGraphics(); if (addOtherLogo && (movie.isTVShow())) { // Both logos are required, so put the HD logo on the LEFT g2d.drawImage(biHd, 5, bi.getHeight() - biHd.getHeight() - 5, null); LOG.debug("Drew HD logo ({}) on the left", logoFilename); } else { // Only the HD logo is required so set it in the centre g2d.drawImage(biHd, bi.getWidth() / 2 - biHd.getWidth() / 2, bi.getHeight() - biHd.getHeight() - 5, null); LOG.debug("Drew HD logo ({}) in the middle", logoFilename); } g2d.dispose(); } catch (FileNotFoundException ex) { LOG.warn("Failed to load {}{}, please ensure it is valid", overlayResources, logoFilename); } catch (IOException ex) { LOG.warn( "Failed drawing HD logo to thumbnail file. Please check that {} is in the resources directory.", logoFilename); } return bi; }
From source file:com.moviejukebox.plugin.DefaultImagePlugin.java
/** * Draw the TV logo onto the image file//from w w w . j a v a 2 s. c om * * @param movie The source movie * @param bi The original image * @param addOtherLogo Do we need to draw the HD logo as well? * @return The new image file */ private BufferedImage drawLogoTV(Movie movie, BufferedImage bi, Boolean addOtherLogo) { if (movie.isTVShow()) { try { BufferedImage biTV = GraphicTools.loadJPEGImage(getResourcesPath() + FILENAME_TV); Graphics2D g2d = bi.createGraphics(); if (addOtherLogo && movie.isHD()) { // Both logos are required, so put the TV logo on the RIGHT g2d.drawImage(biTV, bi.getWidth() - biTV.getWidth() - 5, bi.getHeight() - biTV.getHeight() - 5, null); LOG.debug("Drew TV logo on the right"); } else { // Only the TV logo is required so set it in the centre g2d.drawImage(biTV, bi.getWidth() / 2 - biTV.getWidth() / 2, bi.getHeight() - biTV.getHeight() - 5, null); LOG.debug("Drew TV logo in the middle"); } g2d.dispose(); } catch (FileNotFoundException ex) { LOG.warn(LOG_FAILED_TO_LOAD, FILENAME_TV); } catch (IOException error) { LOG.warn( "Failed drawing TV logo to thumbnail file: Please check that {} is in the resources directory.", FILENAME_TV); LOG.error(SystemTools.getStackTrace(error)); } } return bi; }
From source file:net.groupbuy.util.ImageUtils.java
/** * ?//from w w w.j a v a2 s. com * * @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.igormaznitsa.mindmap.swing.panel.MindMapPanel.java
@Override @SuppressWarnings("unchecked") public void paintComponent(final Graphics g) { final Graphics2D gfx = (Graphics2D) g.create(); try {//w w w. java 2 s .c o m final String error = this.errorText; Utils.prepareGraphicsForQuality(gfx); if (error != null) { drawErrorText(gfx, this.getSize(), error); } else { revalidate(); drawOnGraphicsForConfiguration(gfx, this.config, this.model, true, this.selectedTopics); drawDestinationElement(gfx, this.config); } paintChildren(g); if (this.draggedElement != null) { this.draggedElement.draw(gfx); } else if (this.mouseDragSelection != null) { gfx.setColor(COLOR_MOUSE_DRAG_SELECTION); gfx.fill(this.mouseDragSelection.asRectangle()); } } finally { gfx.dispose(); } }
From source file:org.gumtree.vis.awt.JChartPanel.java
@Override public Image getImage() { BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); // gc2.setBackground(Color.white); g2.setPaint(Color.white);//from www .java 2 s. com g2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight())); if (getChart() != null) { Image chartImage = getChart().createBufferedImage((int) getWidth(), (int) getHeight()); g2.drawImage(chartImage, 0, 0, this); ChartMaskingUtilities.drawMasks(g2, getScreenDataArea(), maskList, null, getChart()); } g2.dispose(); return image; }
From source file:com.isti.traceview.common.TraceViewChartPanel.java
/** * Implementation of the MouseMotionListener's method. * // w w w . java 2 s .c om * @param e * the event. */ public void mouseMoved(MouseEvent e) { Graphics2D g2 = (Graphics2D) getGraphics(); if (this.horizontalAxisTrace) { drawHorizontalAxisTrace(g2, e.getX()); } if (this.verticalAxisTrace) { drawVerticalAxisTrace(g2, e.getY()); } g2.dispose(); Object[] listeners = this.chartMouseListeners.getListeners(ChartMouseListener.class); if (listeners.length == 0) { return; } Insets insets = getInsets(); int x = (int) ((e.getX() - insets.left) / this.scaleX); int y = (int) ((e.getY() - insets.top) / this.scaleY); ChartEntity entity = null; if (this.info != null) { EntityCollection entities = this.info.getEntityCollection(); if (entities != null) { entity = entities.getEntity(x, y); } } // we can only generate events if the panel's chart is not null // (see bug report 1556951) if (this.chart != null) { ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity); for (int i = listeners.length - 1; i >= 0; i -= 1) { ((ChartMouseListener) listeners[i]).chartMouseMoved(event); } } }
From source file:com.el.ecom.utils.ImageUtils.java
/** * ?/*from w w w . ja v a2 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.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); } } } }