List of usage examples for java.awt Graphics2D clearRect
public abstract void clearRect(int x, int y, int width, int height);
From source file:com.el.ecom.utils.ImageUtils.java
/** * ?/*from ww w . j av a2s.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); } } } }
From source file:AffineTransformApp.java
public void applyFilter() { AffineTransformOp op = new AffineTransformOp(transform, null); Graphics2D biDestG2D = biDest.createGraphics(); biDestG2D.clearRect(0, 0, biDest.getWidth(this), biDest.getHeight(this)); op.filter(biSrc, biDest);//from ww w.j av a2 s . c o m bi = biDest; }
From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java
/** * Clears the canvas. */ private void clearCanvas(Graphics2D g2d) { g2d.clearRect(0, 0, width, height); }
From source file:D20140128.ApacheXMLGraphicsTest.TilingPatternExample.java
/** * Default constructor./*w w w. j ava 2s . com*/ */ public TilingPatternExample() { //Created TexturePaint instance this.tile = new BufferedImage(40, 20, BufferedImage.TYPE_INT_RGB); Graphics2D tileg2d = tile.createGraphics(); tileg2d.setBackground(Color.WHITE); tileg2d.clearRect(0, 0, tile.getWidth(), tile.getHeight()); tileg2d.setColor(Color.BLUE); tileg2d.fillOval(2, 2, tile.getWidth() - 2, tile.getHeight() - 2); tileg2d.dispose(); Rectangle2D rect = new Rectangle2D.Double(2, 2, tile.getWidth() / 2.0, tile.getHeight() / 2.0); this.paint = new TexturePaint(tile, rect); }
From source file:image.writer.ImageWriterExample1.java
/** * Creates a bitmap file. We paint a few things on a bitmap and then save the bitmap using * an ImageWriter./* w w w.j av a 2s.c o m*/ * @param outputFile the target file * @param format the target format (a MIME type, ex. "image/png") * @throws IOException In case of an I/O error */ public void generateBitmapUsingJava2D(File outputFile, String format) throws IOException { //String compression = "CCITT T.6"; String compression = "PackBits"; boolean monochrome = compression.startsWith("CCITT"); //CCITT is for 1bit b/w only BufferedImage bimg; 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, 1); OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); try { ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(format); ImageWriterParams params = new ImageWriterParams(); params.setCompressionMethod(compression); params.setResolution(72); writer.writeImage(bimg, out, params); } finally { IOUtils.closeQuietly(out); } }
From source file:org.wkm.mtool.service.QRCodeService.java
/** * ??(QRCode)//from ww w. j av a 2 s .c o m * @param content * @param imgFile */ private void encoderQRCode(String content, File imgFile) { try { Qrcode qrcodeHandler = new Qrcode(); qrcodeHandler.setQrcodeErrorCorrect('M'); qrcodeHandler.setQrcodeEncodeMode('B'); qrcodeHandler.setQrcodeVersion(7); System.out.println(content); byte[] contentBytes = content.getBytes(Consts.UTF_8.name()); BufferedImage bufImg = new BufferedImage(140, 140, BufferedImage.TYPE_INT_RGB); Graphics2D gs = bufImg.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, 140, 140); // ? > BLACK gs.setColor(Color.BLACK); // ??? ??? int pixoff = 2; // > ? if (contentBytes.length > 0 && contentBytes.length < 120) { boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < codeOut.length; i++) { for (int j = 0; j < codeOut.length; j++) { if (codeOut[j][i]) { gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); } } } } else { System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. "); } gs.dispose(); bufImg.flush(); // ??QRCode ImageIO.write(bufImg, "png", imgFile); } catch (Exception e) { log.info("Exception:" + e.getMessage()); } }
From source file:org.lmn.fc.common.datatranslators.DataExporter.java
/*********************************************************************************************** * exportComponent()./*from ww w.j a va 2 s. c o m*/ * * @param exportable * @param filename * @param timestamp * @param type * @param width * @param height * @param log * @param clock * * @return boolean */ public static boolean exportComponent(final ExportableComponentInterface exportable, final String filename, final boolean timestamp, final String type, final int width, final int height, final Vector<Vector> log, final ObservatoryClockInterface clock) { final String SOURCE = "DataExporter.exportComponent()"; boolean boolSuccess; // String[] arrayNames = ImageIO.getWriterFormatNames(); // // for (int i = 0; // i < arrayNames.length; // i++) // { // String arrayName = arrayNames[i]; // System.out.println("DataExporter.exportComponent() FORMAT NAME=" + arrayName); // } // boolSuccess = false; if ((exportable != null) && (filename != null) && (!EMPTY_STRING.equals(filename)) && (type != null) && (!EMPTY_STRING.equals(type)) && (log != null) && (clock != null) && (Arrays.asList(ImageIO.getWriterFormatNames()).contains(type))) { try { final File file; final int intRealWidth; final int intRealHeight; file = new File(FileUtilities.buildFullFilename(filename, timestamp, type)); FileUtilities.overwriteFile(file); intRealWidth = width; intRealHeight = height; // Support all current formats if ((FileUtilities.png.equalsIgnoreCase(type)) || (FileUtilities.jpg.equalsIgnoreCase(type)) || (FileUtilities.gif.equalsIgnoreCase(type))) { BufferedImage buffer; final Graphics2D graphics2D; LOGGER.debugTimedEvent(LOADER_PROPERTIES.isTimingDebug(), "DataExporter.exportComponent() writing [file " + file.getAbsolutePath() + "] [width=" + intRealWidth + "] [height=" + intRealHeight + "]"); buffer = new BufferedImage(intRealWidth, intRealHeight, BufferedImage.TYPE_INT_RGB); // Create a graphics context on the buffered image graphics2D = buffer.createGraphics(); // Draw on the image graphics2D.clearRect(0, 0, intRealWidth, intRealHeight); exportable.paintForExport(graphics2D, intRealWidth, intRealHeight); // Export the image ImageIO.write(buffer, type, file); graphics2D.dispose(); boolSuccess = true; SimpleEventLogUIComponent .logEvent( log, EventStatus.INFO, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR, SOURCE, clock); // Help the GC? buffer = null; ObservatoryInstrumentHelper.runGarbageCollector(); } else { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_INVALID_FORMAT + TERMINATOR, SOURCE, clock); } } catch (IllegalArgumentException exception) { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + EXCEPTION_PARAMETER_INVALID + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR, SOURCE, clock); } catch (SecurityException exception) { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR, SOURCE, clock); } catch (FileNotFoundException exception) { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR, SOURCE, clock); } catch (IOException exception) { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR, SOURCE, clock); } } else { SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL, METADATA_TARGET_COMPONENT + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_COMPONENT + TERMINATOR, SOURCE, clock); } return (boolSuccess); }
From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java
/** * Draws an image that can be used as a scale for heat maps generated using * Plot or PlotPyramid./*from w w w . java 2 s .c o m*/ * @param output - Output path * @param valueRange - Range of values of interest * @param width - Width of the generated image * @param height - Height of the generated image * @throws IOException */ public static void drawScale(Path output, MinMax valueRange, int width, int height) throws IOException { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setBackground(Color.BLACK); g.clearRect(0, 0, width, height); // fix this part to work according to color1, color2 and gradient type for (int y = 0; y < height; y++) { Color color = NASARectangle.calculateColor(y); g.setColor(color); g.drawRect(width * 3 / 4, y, width / 4, 1); } int fontSize = 24; g.setFont(new Font("Arial", Font.BOLD, fontSize)); int step = (valueRange.maxValue - valueRange.minValue) * fontSize * 10 / height; step = (int) Math.pow(10, Math.round(Math.log10(step))); int min_value = valueRange.minValue / step * step; int max_value = valueRange.maxValue / step * step; for (int value = min_value; value <= max_value; value += step) { int y = fontSize + (height - fontSize) - value * (height - fontSize) / (valueRange.maxValue - valueRange.minValue); g.setColor(Color.WHITE); g.drawString(String.valueOf(value), 5, y); } g.dispose(); FileSystem fs = output.getFileSystem(new Configuration()); FSDataOutputStream outStream = fs.create(output, true); ImageIO.write(image, "png", outStream); outStream.close(); }
From source file:dk.netdesign.common.osgi.config.osgi.OCD.java
public BufferedImage scaleImage(BufferedImage img, int width, int height, Color background) { int imgWidth = img.getWidth(); int imgHeight = img.getHeight(); if (imgWidth * height < imgHeight * width) { width = imgWidth * height / imgHeight; } else {//from w w w . ja va 2s .co m height = imgHeight * width / imgWidth; } BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = newImage.createGraphics(); try { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.setBackground(background); g.clearRect(0, 0, width, height); g.drawImage(img, 0, 0, width, height, null); } finally { g.dispose(); } return newImage; }
From source file:com.github.andreax79.meca.Main.java
public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern, int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException { Rule rule = new Rule(ruleNumber); Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111 Stats stats = new Stats(); FileOutputStream finalImage = null; Graphics2D g = null; BufferedImage img = null;//from w w w . j ava 2 s.c o m if (output != Output.noOutput) { String fileName = "rule" + ruleNumber; // pattern if (pattern != null) fileName += pattern; // alpha if (alpha > 0) fileName += String.format("_a%02d", (int) (alpha * 100)); // updatePattern if (updatePattern != UpdatePattern.synchronous) fileName += "-" + updatePattern; fileName += ".jpeg"; File file = new File(fileName); finalImage = new FileOutputStream(file); int width = (int) (cellSize * (size + 1) * (output == Output.all ? 1.25 : 1)); int height = cellSize * (steps + 1); img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); g = img.createGraphics(); g.setBackground(Color.white); g.clearRect(0, 0, width, height); g.setColor(Color.black); } int startMeansFromStep = 50; List<Double> densities = new LinkedList<Double>(); double totalDensities = 0; double prevValue = 0; double prevDelta = 0; double prevOnes = 0; double prevOnesDelta = 0; for (int t = 0; t < steps; t++) { if (t >= startMeansFromStep) { double density = row.getDensity(); densities.add(density); totalDensities += density; } // System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes()); if (output != Output.noOutput) { for (int j = 0; j < row.getSize(); j++) { switch (colorScheme) { case noColor: if (row.getCell(j).getState()) { g.setColor(Color.black); g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize); } break; case omegaColor: g.setColor(row.getCell(j).getOmegaColor()); g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize); break; case activationColor: if (row.getCell(j).getState()) { g.setColor(row.getCell(j).getColor()); g.fillRect(j * cellSize, t * cellSize, cellSize, cellSize); } break; } } if (output == Output.all) { double value = row.getValue(); double delta = Math.abs(value - prevValue); double ones = row.getOnes(); double onesDelta = Math.abs(ones - prevOnes); if (t > 0) { g.setColor(Color.red); g.drawLine((int) (prevValue * cellSize / 4.0) + cellSize * (size + 1), (int) ((t - 1) * cellSize), (int) (value * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize)); g.setColor(Color.blue); g.drawLine((int) (prevOnes * cellSize / 4.0) + cellSize * (size + 1), (int) ((t - 1) * cellSize), (int) (ones * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize)); if (t > 1) { g.setColor(Color.orange); g.drawLine((int) (prevDelta * cellSize / 4.0) + cellSize * (size + 1), (int) ((t - 1) * cellSize), (int) (delta * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize)); g.setColor(Color.cyan); g.drawLine((int) (prevOnesDelta * cellSize / 4.0) + cellSize * (size + 1), (int) ((t - 1) * cellSize), (int) (onesDelta * cellSize / 4.0) + cellSize * (size + 1), (int) (t * cellSize)); } } prevValue = value; prevDelta = delta; prevOnes = ones; prevOnesDelta = onesDelta; } } row = new Row(row); } double means = totalDensities / densities.size(); double var = 0; for (double density : densities) var += Math.pow(density - means, 2); var = var / densities.size(); System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern + " Alpha: " + String.format("%.3f", alpha) + " Means: " + String.format("%.6f", means) + " Variance: " + String.format("%.6f", var)); stats.setMeans(means); stats.setVariance(var); if (output != Output.noOutput) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img); param.setQuality(1.0f, true); encoder.encode(img, param); finalImage.flush(); finalImage.close(); } return stats; }