List of usage examples for java.awt Graphics2D clearRect
public abstract void clearRect(int x, int y, int width, int height);
From source file:net.semanticmetadata.lire.utils.FileUtils.java
public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage, IndexReader reader) throws IOException { LinkedList<BufferedImage> results = new LinkedList<BufferedImage>(); int width = 0; for (int i = 0; i < hits.length(); i++) { // hits.score(i) // hits.doc(i).get("descriptorImageIdentifier") BufferedImage tmp = ImageIO.read(new FileInputStream( reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0])); // if (tmp.getHeight() > 200) { double factor = 200d / ((double) tmp.getHeight()); tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200); // } width += tmp.getWidth() + 5;/* www . ja va2s. com*/ results.add(tmp); } BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) result.getGraphics(); g2.setColor(Color.white); g2.setBackground(Color.white); g2.clearRect(0, 0, result.getWidth(), result.getHeight()); g2.setColor(Color.black); g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12")); int offset = 0; int count = 0; for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) { BufferedImage next = iterator.next(); g2.drawImage(next, offset, 20, null); g2.drawString(hits.score(count) + "", offset + 5, 12); offset += next.getWidth() + 5; count++; } ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png")); }
From source file:com.ricemap.spateDB.operations.Plot.java
public static <S extends Shape> void plotLocal(Path inFile, Path outFile, S shape, int width, int height, Color color, boolean showBorders, boolean showBlockCount, boolean showRecordCount) throws IOException { FileSystem inFs = inFile.getFileSystem(new Configuration()); Prism fileMbr = FileMBR.fileMBRLocal(inFs, inFile, shape); LOG.info("FileMBR: " + fileMbr); // Adjust width and height to maintain aspect ratio if ((fileMbr.x2 - fileMbr.x1) / (fileMbr.y2 - fileMbr.y1) > (double) width / height) { // Fix width and change height height = (int) ((fileMbr.y2 - fileMbr.y1) * width / (fileMbr.x2 - fileMbr.x1)); } else {/*from w w w . j ava 2s . c om*/ width = (int) ((fileMbr.x2 - fileMbr.x1) * height / (fileMbr.y2 - fileMbr.y1)); } double scale2 = (double) width * height / ((double) (fileMbr.x2 - fileMbr.x1) * (fileMbr.y2 - fileMbr.y1)); // Create an image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); Color bg_color = new Color(0, 0, 0, 0); graphics.setBackground(bg_color); graphics.clearRect(0, 0, width, height); graphics.setColor(color); long fileLength = inFs.getFileStatus(inFile).getLen(); ShapeRecordReader<S> reader = new ShapeRecordReader<S>(inFs.open(inFile), 0, fileLength); Prism cell = reader.createKey(); while (reader.next(cell, shape)) { drawShape(graphics, shape, fileMbr, width, height, scale2); } reader.close(); graphics.dispose(); FileSystem outFs = outFile.getFileSystem(new Configuration()); OutputStream out = outFs.create(outFile, true); ImageIO.write(image, "png", out); out.close(); }
From source file:edu.umn.cs.spatialHadoop.operations.Plot.java
public static <S extends Shape> void plotLocal(Path inFile, Path outFile, S shape, int width, int height, Color color, boolean showBorders, boolean showBlockCount, boolean showRecordCount) throws IOException { FileSystem inFs = inFile.getFileSystem(new Configuration()); Rectangle fileMbr = FileMBR.fileMBRLocal(inFs, inFile, shape); LOG.info("FileMBR: " + fileMbr); // Adjust width and height to maintain aspect ratio if ((fileMbr.x2 - fileMbr.x1) / (fileMbr.y2 - fileMbr.y1) > (double) width / height) { // Fix width and change height height = (int) ((fileMbr.y2 - fileMbr.y1) * width / (fileMbr.x2 - fileMbr.x1)); } else {/*w ww . j a va2s .c o m*/ width = (int) ((fileMbr.x2 - fileMbr.x1) * height / (fileMbr.y2 - fileMbr.y1)); } double scale2 = (double) width * height / ((double) (fileMbr.x2 - fileMbr.x1) * (fileMbr.y2 - fileMbr.y1)); // Create an image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); Color bg_color = new Color(0, 0, 0, 0); graphics.setBackground(bg_color); graphics.clearRect(0, 0, width, height); graphics.setColor(color); long fileLength = inFs.getFileStatus(inFile).getLen(); ShapeRecordReader<S> reader = new ShapeRecordReader<S>(inFs.open(inFile), 0, fileLength); Rectangle cell = reader.createKey(); while (reader.next(cell, shape)) { drawShape(graphics, shape, fileMbr, width, height, scale2); } reader.close(); graphics.dispose(); FileSystem outFs = outFile.getFileSystem(new Configuration()); OutputStream out = outFs.create(outFile, true); ImageIO.write(image, "png", out); out.close(); }
From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java
/** * Rotate an image using the requested angle * * @param bufferedImage imeg to rotate//from w ww. ja va 2 s .co m * @param angle angle to rotate * @return BufferedImage containing the rotation */ @SuppressWarnings({ "UnusedAssignment" }) private static BufferedImage rotate(BufferedImage bufferedImage, int angle) { angle = angle % 360; if (angle == 0) return bufferedImage; if (angle < 0) angle += 360; switch (angle) { case 90: BufferedImageOp rot90 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI / 2.0, bufferedImage.getHeight() / 2.0, bufferedImage.getHeight() / 2.0), AffineTransformOp.TYPE_BILINEAR); BufferedImage img90 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType()); return rot90.filter(bufferedImage, img90); case 180: BufferedImageOp rot180 = new AffineTransformOp(AffineTransform.getRotateInstance(Math.PI, bufferedImage.getWidth() / 2.0, bufferedImage.getHeight() / 2.0), AffineTransformOp.TYPE_BILINEAR); BufferedImage img180 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage.getType()); return rot180.filter(bufferedImage, img180); case 270: BufferedImageOp rot270 = new AffineTransformOp(AffineTransform.getRotateInstance(-Math.PI / 2.0, bufferedImage.getWidth() / 2.0, bufferedImage.getWidth() / 2.0), AffineTransformOp.TYPE_BILINEAR); BufferedImage img270 = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType()); return rot270.filter(bufferedImage, img270); default: //rotate using a non-standard angle (have to draw a box around the image that can fit it) int box = (int) Math.sqrt(bufferedImage.getHeight() * bufferedImage.getHeight() + bufferedImage.getWidth() * bufferedImage.getWidth()); BufferedImage imgFree = new BufferedImage(box, box, bufferedImage.getType()); BufferedImage imgRet = new BufferedImage(box, box, bufferedImage.getType()); Graphics2D g = imgFree.createGraphics(); if (bufferedImage.getTransparency() == Transparency.OPAQUE) { //draw a white background on opaque images since they dont support transparency g.setBackground(Color.WHITE); g.clearRect(0, 0, box, box); Graphics2D gr = imgRet.createGraphics(); gr.setBackground(Color.WHITE); gr.clearRect(0, 0, box, box); gr = null; } g.drawImage(bufferedImage, box / 2 - bufferedImage.getWidth() / 2, box / 2 - bufferedImage.getHeight() / 2, bufferedImage.getWidth(), bufferedImage.getHeight(), null); g = null; AffineTransform at = new AffineTransform(); at.rotate(angle * Math.PI / 180.0, box / 2.0, box / 2.0); BufferedImageOp bio; bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); return bio.filter(imgFree, imgRet); } }
From source file:com.lingxiang2014.util.ImageUtils.java
public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) { Assert.notNull(srcFile);//from ww w . ja v a 2 s . co 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:Main.java
private Image createImage(Color color) { BufferedImage bImg = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bImg.createGraphics(); g2.setBackground(color);//w ww .j av a2 s . c om g2.clearRect(0, 0, Width, Height); g2.dispose(); return bImg; }
From source file:SimpleAttributes.java
public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setBackground(Color.GRAY); g2d.clearRect(0, 0, getWidth(), getHeight()); // String and line with default attributes g2d.drawString("Default Font", 10, 20); g2d.drawLine(10, 22, 80, 22);//from w w w .j a v a2 s. com // Change the font, foreground color, and Stroke g2d.setFont(g.getFont().deriveFont(Font.BOLD | Font.ITALIC, 24f)); g2d.setColor(Color.WHITE); g2d.setStroke(new BasicStroke(10f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); // String and line with new attributes g2d.drawString("New Font", 10, 50); g2d.drawLine(10, 57, 120, 57); g2d.dispose(); }
From source file:edu.umn.cs.spatialHadoop.visualization.MultilevelPlot.java
private static void plotLocal(Path[] inFiles, final Path outPath, final Class<? extends Plotter> plotterClass, final OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException { final boolean vflip = params.getBoolean("vflip", true); OperationsParams mbrParams = new OperationsParams(params); mbrParams.setBoolean("background", false); final Rectangle inputMBR = params.get("mbr") != null ? params.getShape("mbr").getMBR() : FileMBR.fileMBR(inFiles, mbrParams); OperationsParams.setShape(params, InputMBR, inputMBR); // Retrieve desired output image size and keep aspect ratio if needed int tileWidth = params.getInt("tilewidth", 256); int tileHeight = params.getInt("tileheight", 256); // Adjust width and height if aspect ratio is to be kept if (params.getBoolean("keepratio", true)) { // Expand input file to a rectangle for compatibility with the pyramid // structure if (inputMBR.getWidth() > inputMBR.getHeight()) { inputMBR.y1 -= (inputMBR.getWidth() - inputMBR.getHeight()) / 2; inputMBR.y2 = inputMBR.y1 + inputMBR.getWidth(); } else {//from w w w . j a v a 2s. c om inputMBR.x1 -= (inputMBR.getHeight() - inputMBR.getWidth()) / 2; inputMBR.x2 = inputMBR.x1 + inputMBR.getHeight(); } } String outFName = outPath.getName(); int extensionStart = outFName.lastIndexOf('.'); final String extension = extensionStart == -1 ? ".png" : outFName.substring(extensionStart); // Start reading input file Vector<InputSplit> splits = new Vector<InputSplit>(); final SpatialInputFormat3<Rectangle, Shape> inputFormat = new SpatialInputFormat3<Rectangle, Shape>(); for (Path inFile : inFiles) { FileSystem inFs = inFile.getFileSystem(params); if (!OperationsParams.isWildcard(inFile) && inFs.exists(inFile) && !inFs.isDirectory(inFile)) { if (SpatialSite.NonHiddenFileFilter.accept(inFile)) { // Use the normal input format splitter to add this non-hidden file Job job = Job.getInstance(params); SpatialInputFormat3.addInputPath(job, inFile); splits.addAll(inputFormat.getSplits(job)); } else { // A hidden file, add it immediately as one split // This is useful if the input is a hidden file which is automatically // skipped by FileInputFormat. We need to plot a hidden file for the case // of plotting partition boundaries of a spatial index splits.add(new FileSplit(inFile, 0, inFs.getFileStatus(inFile).getLen(), new String[0])); } } else { Job job = Job.getInstance(params); SpatialInputFormat3.addInputPath(job, inFile); splits.addAll(inputFormat.getSplits(job)); } } try { Plotter plotter = plotterClass.newInstance(); plotter.configure(params); String[] strLevels = params.get("levels", "7").split("\\.\\."); int minLevel, maxLevel; if (strLevels.length == 1) { minLevel = 0; maxLevel = Integer.parseInt(strLevels[0]); } else { minLevel = Integer.parseInt(strLevels[0]); maxLevel = Integer.parseInt(strLevels[1]); } GridInfo bottomGrid = new GridInfo(inputMBR.x1, inputMBR.y1, inputMBR.x2, inputMBR.y2); bottomGrid.rows = bottomGrid.columns = 1 << maxLevel; TileIndex key = new TileIndex(); // All canvases in the pyramid, one per tile Map<TileIndex, Canvas> canvases = new HashMap<TileIndex, Canvas>(); for (InputSplit split : splits) { FileSplit fsplit = (FileSplit) split; RecordReader<Rectangle, Iterable<Shape>> reader = inputFormat.createRecordReader(fsplit, null); if (reader instanceof SpatialRecordReader3) { ((SpatialRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof RTreeRecordReader3) { ((RTreeRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof HDFRecordReader) { ((HDFRecordReader) reader).initialize(fsplit, params); } else { throw new RuntimeException("Unknown record reader"); } while (reader.nextKeyValue()) { Rectangle partition = reader.getCurrentKey(); if (!partition.isValid()) partition.set(inputMBR); Iterable<Shape> shapes = reader.getCurrentValue(); for (Shape shape : shapes) { Rectangle shapeMBR = shape.getMBR(); if (shapeMBR == null) continue; java.awt.Rectangle overlappingCells = bottomGrid.getOverlappingCells(shapeMBR); // Iterate over levels from bottom up for (key.level = maxLevel; key.level >= minLevel; key.level--) { for (key.x = overlappingCells.x; key.x < overlappingCells.x + overlappingCells.width; key.x++) { for (key.y = overlappingCells.y; key.y < overlappingCells.y + overlappingCells.height; key.y++) { Canvas canvas = canvases.get(key); if (canvas == null) { Rectangle tileMBR = new Rectangle(); int gridSize = 1 << key.level; tileMBR.x1 = (inputMBR.x1 * (gridSize - key.x) + inputMBR.x2 * key.x) / gridSize; tileMBR.x2 = (inputMBR.x1 * (gridSize - (key.x + 1)) + inputMBR.x2 * (key.x + 1)) / gridSize; tileMBR.y1 = (inputMBR.y1 * (gridSize - key.y) + inputMBR.y2 * key.y) / gridSize; tileMBR.y2 = (inputMBR.y1 * (gridSize - (key.y + 1)) + inputMBR.y2 * (key.y + 1)) / gridSize; canvas = plotter.createCanvas(tileWidth, tileHeight, tileMBR); canvases.put(key.clone(), canvas); } plotter.plot(canvas, shape); } } // Update overlappingCells for the higher level int updatedX1 = overlappingCells.x / 2; int updatedY1 = overlappingCells.y / 2; int updatedX2 = (overlappingCells.x + overlappingCells.width - 1) / 2; int updatedY2 = (overlappingCells.y + overlappingCells.height - 1) / 2; overlappingCells.x = updatedX1; overlappingCells.y = updatedY1; overlappingCells.width = updatedX2 - updatedX1 + 1; overlappingCells.height = updatedY2 - updatedY1 + 1; } } } reader.close(); } // Done with all splits. Write output to disk LOG.info("Done with plotting. Now writing the output"); final FileSystem outFS = outPath.getFileSystem(params); LOG.info("Writing default empty image"); // Write a default empty image to be displayed for non-generated tiles BufferedImage emptyImg = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = new SimpleGraphics(emptyImg); g.setBackground(new Color(0, 0, 0, 0)); g.clearRect(0, 0, tileWidth, tileHeight); g.dispose(); // Write HTML file to browse the mutlielvel image OutputStream out = outFS.create(new Path(outPath, "default.png")); ImageIO.write(emptyImg, "png", out); out.close(); // Add an HTML file that visualizes the result using Google Maps LOG.info("Writing the HTML viewer file"); LineReader templateFileReader = new LineReader( MultilevelPlot.class.getResourceAsStream("/zoom_view.html")); PrintStream htmlOut = new PrintStream(outFS.create(new Path(outPath, "index.html"))); Text line = new Text(); while (templateFileReader.readLine(line) > 0) { String lineStr = line.toString(); lineStr = lineStr.replace("#{TILE_WIDTH}", Integer.toString(tileWidth)); lineStr = lineStr.replace("#{TILE_HEIGHT}", Integer.toString(tileHeight)); lineStr = lineStr.replace("#{MAX_ZOOM}", Integer.toString(maxLevel)); lineStr = lineStr.replace("#{MIN_ZOOM}", Integer.toString(minLevel)); lineStr = lineStr.replace("#{TILE_URL}", "'tile-' + zoom + '-' + coord.x + '-' + coord.y + '" + extension + "'"); htmlOut.println(lineStr); } templateFileReader.close(); htmlOut.close(); // Write the tiles final Entry<TileIndex, Canvas>[] entries = canvases.entrySet().toArray(new Map.Entry[canvases.size()]); // Clear the hash map to save memory as it is no longer needed canvases.clear(); int parallelism = params.getInt("parallel", Runtime.getRuntime().availableProcessors()); Parallel.forEach(entries.length, new RunnableRange<Object>() { @Override public Object run(int i1, int i2) { boolean output = params.getBoolean("output", true); try { Plotter plotter = plotterClass.newInstance(); plotter.configure(params); for (int i = i1; i < i2; i++) { Map.Entry<TileIndex, Canvas> entry = entries[i]; TileIndex key = entry.getKey(); if (vflip) key.y = ((1 << key.level) - 1) - key.y; Path imagePath = new Path(outPath, key.getImageFileName() + extension); // Write this tile to an image DataOutputStream outFile = output ? outFS.create(imagePath) : new DataOutputStream(new NullOutputStream()); plotter.writeImage(entry.getValue(), outFile, vflip); outFile.close(); // Remove entry to allows GC to collect it entries[i] = null; } return null; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }, parallelism); } catch (InstantiationException e) { throw new RuntimeException("Error creating rastierizer", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error creating rastierizer", e); } }
From source file:image.writer.ImageWriterExample2.java
private BufferedImage createAnImage(String compression, int pageNum) { boolean monochrome = compression.startsWith("CCITT"); //CCITT is for 1bit b/w only BufferedImage bimg;// ww w . j ava2 s .c o m if (monochrome) { bimg = new BufferedImage(400, 200, BufferedImage.TYPE_BYTE_BINARY); } else { bimg = new BufferedImage(400, 200, BufferedImage.TYPE_INT_RGB); } Graphics2D g2d = bimg.createGraphics(); g2d.setBackground(Color.white); g2d.clearRect(0, 0, 400, 200); g2d.setColor(Color.black); //Paint something paintSome(g2d, pageNum); return bimg; }
From source file:net.groupbuy.util.ImageUtils.java
/** * ?//from w w w. j ava 2s.c om * * @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(); } } } }