List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java
/** * Scale a {@link BufferedImage} to new size. Is faster than the basic {@link ImageUtils}.scaleImage method, has the * same quality. If it is a thumbnail, cut the images to fit into the raster * //from ww w . jav a 2 s .c o m * @param image original image * @param size the size to be resized to * @param resolution the type of the image. Might be thumb or web * @return the resized images * @throws Exception */ public static BufferedImage scaleImageFast(BufferedImage image, int size, FileResolution resolution) throws Exception { int width = image.getWidth(null); int height = image.getHeight(null); BufferedImage newImg = null; Image rescaledImage; if (width > height) { if (FileResolution.THUMBNAIL.equals(resolution)) { newImg = new BufferedImage(height, height, BufferedImage.TYPE_INT_RGB); Graphics g1 = newImg.createGraphics(); g1.drawImage(image, (height - width) / 2, 0, null); if (height > size) rescaledImage = getScaledInstance(newImg, size, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); else rescaledImage = newImg; } else rescaledImage = getScaledInstance(image, size, height * size / width, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); } else { if (FileResolution.THUMBNAIL.equals(resolution)) { newImg = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB); Graphics g1 = newImg.createGraphics(); g1.drawImage(image, 0, (width - height) / 2, null); if (width > size) rescaledImage = getScaledInstance(newImg, size, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); else rescaledImage = newImg; } else rescaledImage = getScaledInstance(image, width * size / height, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); } BufferedImage rescaledBufferedImage = new BufferedImage(rescaledImage.getWidth(null), rescaledImage.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g2 = rescaledBufferedImage.getGraphics(); g2.drawImage(rescaledImage, 0, 0, null); return rescaledBufferedImage; }
From source file:com.galenframework.utils.GalenUtils.java
public static File makeFullScreenshot(WebDriver driver) throws IOException, InterruptedException { // scroll up first scrollVerticallyTo(driver, 0);// w w w. ja v a2s . c o m byte[] bytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes)); int capturedWidth = image.getWidth(); int capturedHeight = image.getHeight(); long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript( "return Math.max(" + "document.body.scrollHeight, document.documentElement.scrollHeight," + "document.body.offsetHeight, document.documentElement.offsetHeight," + "document.body.clientHeight, document.documentElement.clientHeight);"); Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver) .executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue(); int scrollHeight = (int) longScrollHeight; File file = File.createTempFile("screenshot", ".png"); int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio); BufferedImage resultingImage; if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) { int scrollOffset = adaptedCapturedHeight; int times = scrollHeight / adaptedCapturedHeight; int leftover = scrollHeight % adaptedCapturedHeight; final BufferedImage tiledImage = new BufferedImage(capturedWidth, (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB); Graphics2D g2dTile = tiledImage.createGraphics(); g2dTile.drawImage(image, 0, 0, null); int scroll = 0; for (int i = 0; i < times - 1; i++) { scroll += scrollOffset; scrollVerticallyTo(driver, scroll); BufferedImage nextImage = ImageIO.read( new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES))); g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null); } if (leftover > 0) { scroll += scrollOffset; scrollVerticallyTo(driver, scroll); BufferedImage nextImage = ImageIO.read( new ByteArrayInputStream(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES))); BufferedImage lastPart = nextImage.getSubimage(0, nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio), nextImage.getWidth(), leftover); g2dTile.drawImage(lastPart, 0, times * capturedHeight, null); } scrollVerticallyTo(driver, 0); resultingImage = tiledImage; } else { resultingImage = image; } if (GalenConfig.getConfig().shouldAutoresizeScreenshots()) { try { resultingImage = GalenUtils.resizeScreenshotIfNeeded(driver, resultingImage); } catch (Exception ex) { LOG.trace("Couldn't resize screenshot", ex); } } ImageIO.write(resultingImage, "png", file); return file; }
From source file:com.el.ecom.utils.ImageUtils.java
/** * ?//www .j a v a 2 s . c o m * * @param srcFile ? * @param destFile * @param watermarkFile ? * @param watermarkPosition ?? * @param alpha ?? */ public static void addWatermark(File srcFile, File destFile, File watermarkFile, WatermarkPosition watermarkPosition, int alpha) { Assert.notNull(srcFile); Assert.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:com.flexive.shared.media.impl.FxMediaNativeEngine.java
/** * Rotate an image using the requested angle * * @param bufferedImage imeg to rotate//from ww w .j av a2s . c o 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:edu.ku.brc.ui.GraphicsUtils.java
/** * Convenience method that returns a scaled instance of the * provided {@code BufferedImage}./*from w ww .ja va2s . c om*/ * * Code stolen from http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html * * @param img the original image to be scaled * @param targetWidth the desired width of the scaled instance, * in pixels * @param targetHeight the desired height of the scaled instance, * in pixels * @param hint one of the rendering hints that corresponds to * {@code RenderingHints.KEY_INTERPOLATION} (e.g. * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) * @param higherQuality if true, this method will use a multi-step * scaling technique that provides higher quality than the usual * one-step technique (only useful in down-scaling cases, where * {@code targetWidth} or {@code targetHeight} is * smaller than the original dimensions, and generally only when * the {@code BILINEAR} hint is specified) * @return a scaled version of the original {@code BufferedImage} */ public static BufferedImage getScaledInstance(final BufferedImage img, final int targetWidth, final int targetHeight, final boolean higherQuality) { int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage temp = img; BufferedImage result = new BufferedImage(targetWidth, targetHeight, type); Graphics2D g2 = result.createGraphics(); if (higherQuality) { g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } g2.drawImage(temp, 0, 0, targetWidth, targetHeight, null); g2.dispose(); return result; }
From source file:Hexagon.java
public static BufferedImage drawCodePoint(char codePoint, int width, int height, Font font, Color color) { BufferedImage img = createImage(width, height); Graphics2D g2 = img.createGraphics(); String text = "" + codePoint; g2.setColor(color);/* ww w . ja v a2s . com*/ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GlyphVector gv = font.createGlyphVector(g2.getFontRenderContext(), text); g2.drawGlyphVector(gv, 0f, (float) gv.getGlyphMetrics(0).getBounds2D().getHeight()); return img; }
From source file:net.daimonin.client3d.editor.main.Editor3D.java
/** * Builds a single PNG out of all ImageSetImages, considering their calculated * coordinates./* w ww .j ava 2 s . c o m*/ * * @param fileNameImageSet Name of resulting PNG. * @param dimension [width, height] of the resulting PNG. where 0 is maximum * compression, 1 is no compression at all. * @throws IOException IOException. */ private static void writeImageSet(final String fileNameImageSet, final int[] dimension) throws IOException { BufferedImage bigImg = new BufferedImage(dimension[0], dimension[1], BufferedImage.TYPE_INT_ARGB); Graphics2D big = bigImg.createGraphics(); for (int i = 0; i < images.size(); i++) { if (images.get(i).getBorderSize() > 0) { ParameterBlock params = new ParameterBlock(); params.addSource(images.get(i).getImage()); params.add(images.get(i).getBorderSize()); // left pad params.add(images.get(i).getBorderSize()); // right pad params.add(images.get(i).getBorderSize()); // top pad params.add(images.get(i).getBorderSize()); // bottom pad params.add(new BorderExtenderConstant(new double[] { images.get(i).getBorderColor().getRed(), images.get(i).getBorderColor().getGreen(), images.get(i).getBorderColor().getBlue(), BORDERCOLORMAX })); big.drawImage(JAI.create("border", params).getAsBufferedImage(), images.get(i).getPosX(), images.get(i).getPosY(), null); } else { big.drawImage(images.get(i).getImage(), images.get(i).getPosX(), images.get(i).getPosY(), null); } } big.dispose(); ImageIO.write(bigImg, "png", new File(fileNameImageSet)); printInfo(System.getProperty("user.dir") + "/" + imageset + " created"); }
From source file:edu.ku.brc.ui.GraphicsUtils.java
/** * Gets a scaled icon and if it doesn't exist it creates one and scales it * @param icon image to be scaled//from ww w . j ava2 s . c o m * @param iconSize the icon size (Std) * @param scaledIconSize the new scaled size in pixels * @return the scaled icon */ public static BufferedImage getBufferedImage(final ImageIcon icon) { Image imgMemory = icon.getImage(); //make sure all pixels in the image were loaded imgMemory = new ImageIcon(imgMemory).getImage(); int w = icon.getIconWidth(); int h = icon.getIconHeight(); BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(imgMemory, 0, 0, w, h, 0, 0, w, h, null); graphics2D.dispose(); return bufferedImage; }
From source file:weka.core.ChartUtils.java
/** * Render a combined histogram and pie chart from summary data * /*from www .j ava 2 s. c o m*/ * @param width the width of the resulting image * @param height the height of the resulting image * @param values the values for the chart * @param freqs the corresponding frequencies * @param additionalArgs optional arguments to the renderer (may be null) * @return a buffered image * @throws Exception if a problem occurs */ public static BufferedImage renderCombinedPieAndHistogramFromSummaryData(int width, int height, List<String> values, List<Double> freqs, List<String> additionalArgs) throws Exception { String plotTitle = "Combined Chart"; String userTitle = getOption(additionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; List<String> opts = new ArrayList<String>(); opts.add("-title=distribution"); BufferedImage pie = renderPieChartFromSummaryData(width / 2, height, values, freqs, false, true, opts); opts.clear(); opts.add("-title=histogram"); BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, values, freqs, opts); BufferedImage img = new BufferedImage(width, height + 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); g2d.setFont(new Font("SansSerif", Font.BOLD, 12)); g2d.setColor(Color.lightGray); g2d.fillRect(0, 0, width, height + 20); g2d.setColor(Color.black); FontMetrics fm = g2d.getFontMetrics(); int fh = fm.getHeight(); int sw = fm.stringWidth(plotTitle); g2d.drawImage(pie, 0, 20, null); g2d.drawImage(hist, width / 2 + 1, 20, null); g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2); g2d.dispose(); return img; }
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 w w .j av a 2 s . 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(); }