List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:Main.java
/** * Snapshots the specified JavaFX {@link Image} object and stores a * copy of its pixels into a {@link BufferedImage} object, creating * a new object if needed.//from www .j a v a 2 s.c om * The method will only convert a JavaFX {@code Image} that is readable * as per the conditions on the * {@link Image#getPixelReader() Image.getPixelReader()} * method. * If the {@code Image} is not readable, as determined by its * {@code getPixelReader()} method, then this method will return null. * If the {@code Image} is a writable, or other dynamic image, then * the {@code BufferedImage} will only be set to the current state of * the pixels in the image as determined by its {@link PixelReader}. * Further changes to the pixels of the {@code Image} will not be * reflected in the returned {@code BufferedImage}. * <p> * The optional {@code BufferedImage} parameter may be reused to store * the copy of the pixels. * A new {@code BufferedImage} will be created if the supplied object * is null, is too small or of a type which the image pixels cannot * be easily converted into. * * @param img the JavaFX {@code Image} to be converted * @param bimg an optional {@code BufferedImage} object that may be * used to store the returned pixel data * @return a {@code BufferedImage} containing a snapshot of the JavaFX * {@code Image}, or null if the {@code Image} is not readable. * @since JavaFX 2.2 */ public static BufferedImage fromFXImage(Image img, BufferedImage bimg) { PixelReader pr = img.getPixelReader(); if (pr == null) { return null; } int iw = (int) img.getWidth(); int ih = (int) img.getHeight(); int prefBimgType = getBestBufferedImageType(pr.getPixelFormat(), bimg); if (bimg != null) { int bw = bimg.getWidth(); int bh = bimg.getHeight(); if (bw < iw || bh < ih || bimg.getType() != prefBimgType) { bimg = null; } else if (iw < bw || ih < bh) { Graphics2D g2d = bimg.createGraphics(); g2d.setComposite(AlphaComposite.Clear); g2d.fillRect(0, 0, bw, bh); g2d.dispose(); } } if (bimg == null) { bimg = new BufferedImage(iw, ih, prefBimgType); } IntegerComponentRaster icr = (IntegerComponentRaster) bimg.getRaster(); int offset = icr.getDataOffset(0); int scan = icr.getScanlineStride(); int data[] = icr.getDataStorage(); WritablePixelFormat<IntBuffer> pf = getAssociatedPixelFormat(bimg); pr.getPixels(0, 0, iw, ih, pf, data, offset, scan); return bimg; }
From source file:de.bund.bfr.knime.gis.views.canvas.CanvasUtils.java
public static BufferedImage getBufferedImage(ICanvas<?>... canvas) { int width = Math.max(Stream.of(canvas).mapToInt(c -> c.getCanvasSize().width).sum(), 1); int height = Stream.of(canvas).mapToInt(c -> c.getCanvasSize().height).max().orElse(1); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); int x = 0;//from w w w . j a v a 2s .co m for (ICanvas<?> c : canvas) { VisualizationImageServer<?, ?> server = c.getVisualizationServer(false); g.translate(x, 0); server.paint(g); x += c.getCanvasSize().width; } return img; }
From source file:weka.core.ChartUtils.java
/** * Render a combined histogram and box plot chart from summary data * /*from ww w. j a va 2 s. c o m*/ * @param width the width of the resulting image * @param height the height of the resulting image * @param bins the values for the chart * @param freqs the corresponding frequencies * @param summary the summary stats for the box plot * @param outliers an optional list of outliers for the box plot * @param additionalArgs optional arguments to the renderer (may be null) * @return a buffered image * @throws Exception if a problem occurs */ public static BufferedImage renderCombinedBoxPlotAndHistogramFromSummaryData(int width, int height, List<String> bins, List<Double> freqs, List<Double> summary, List<Double> outliers, 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=histogram"); BufferedImage hist = renderHistogramFromSummaryData(width / 2, height, bins, freqs, opts); opts.clear(); opts.add("-title=box plot"); BufferedImage box = null; try { box = renderBoxPlotFromSummaryData(width / 2, height, summary, outliers, opts); } catch (Exception ex) { // if we can't generate the box plot (i.e. probably because // data is 100% missing) then just return the histogram } if (box == null) { width /= 2; } 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); if (box != null) { g2d.drawImage(box, 0, 20, null); g2d.drawImage(hist, width / 2 + 1, 20, null); } else { g2d.drawImage(hist, 0, 20, null); } g2d.drawString(plotTitle, width / 2 - sw / 2, fh + 2); g2d.dispose(); return img; }
From source file:Hexagon.java
public static File write(String fileName, Shape shape) throws IOException { Rectangle bounds = shape.getBounds(); BufferedImage img = createImage(bounds.width, bounds.height); Graphics2D g2 = (Graphics2D) img.createGraphics(); //g2.setColor(WebColor.CornSilk.getColor()); g2.fill(shape);//from w w w.j a v a 2 s .com g2.setColor(Color.black); g2.draw(shape); return write(fileName, img); }
From source file:edu.ku.brc.ui.IconManager.java
/** * Creates a Black and White image from the color * @param img the image to be converted//from w ww .j a va2 s . c om * @return new B&W image */ public static ImageIcon createBWImage(final ImageIcon img) { BufferedImage bi = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.createGraphics(); g.drawImage(img.getImage(), 0, 0, null); ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); colorConvert.filter(bi, bi); ImageIcon icon = new ImageIcon(bi); g.dispose(); return icon; }
From source file:view.FramePrincipal.java
private static BufferedImage createBufferedImage(String fileName) { BufferedImage image = null;//from www. j a v a2 s. c o m try { image = ImageIO.read(new File(fileName)); } catch (IOException e) { return null; } int sizeX = image.getWidth(); int sizeY = image.getHeight(); BufferedImage result = new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_RGB); Graphics g = result.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return result; }
From source file:com.shending.support.CompressPic.java
/** * ?/*www .j a v a 2s . c o m*/ * * @param srcFile * @param dstFile * @param widthRange * @param heightRange */ public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width, int height) { int x = 0; int y = 0; try { ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile)); Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); ImageReader reader = (ImageReader) iterator.next(); reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); int oldWidth = reader.getWidth(0); int oldHeight = reader.getHeight(0); int newWidth, newHeight; if (width <= oldWidth && height <= oldHeight) { newWidth = oldHeight * widthRange / heightRange; if (newWidth < oldWidth) { newHeight = oldHeight; x = (oldWidth - newWidth) / 2; } else { newWidth = oldWidth; newHeight = oldWidth * heightRange / widthRange; y = (oldHeight - newHeight) / 2; } Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight); param.setSourceRegion(rectangle); BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } else { BufferedImage bi = reader.read(0, param); BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = tag.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight()); g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH), (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null); g2d.dispose(); File file = new File(dstFile); ImageIO.write(tag, reader.getFormatName(), file); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.piaoyou.util.ImageUtil.java
public static BufferedImage getProductionImage(String productVersion, String productRealeaseDate) { String str = productVersion + " on " + productRealeaseDate; int IMAGE_WIDTH = 250; int IMAGE_HEIGHT = 30; BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); g.setBackground(Color.blue);// w w w. j ava2 s.com g.setColor(Color.white); g.draw3DRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, false); FontMetrics fontMetrics = g.getFontMetrics(); int strWidth = fontMetrics.stringWidth(str); int strHeight = fontMetrics.getAscent() + fontMetrics.getDescent(); g.drawString(str, (IMAGE_WIDTH - strWidth) / 2, IMAGE_HEIGHT - ((IMAGE_HEIGHT - strHeight) / 2) - fontMetrics.getDescent()); g.dispose(); // free resource return bufferedImage; }
From source file:net.pms.util.UMSUtils.java
@SuppressWarnings("deprecation") public static InputStream scaleThumb(InputStream in, RendererConfiguration r) throws IOException { if (in == null) { return in; }/* w w w. j av a2s.c o m*/ String ts = r.getThumbSize(); if (StringUtils.isEmpty(ts) && StringUtils.isEmpty(r.getThumbBG())) { // no need to convert here return in; } int w; int h; Color col = null; BufferedImage img; try { img = ImageIO.read(in); } catch (Exception e) { // catch whatever is thrown at us // we can at least log it LOGGER.debug("couldn't read thumb to manipulate it " + e); img = null; // to make sure } if (img == null) { return in; } w = img.getWidth(); h = img.getHeight(); if (StringUtils.isNotEmpty(ts)) { // size limit thumbnail w = getHW(ts.split("x"), 0); h = getHW(ts.split("x"), 1); if (w == 0 || h == 0) { LOGGER.debug("bad thumb size {} skip scaling", ts); w = h = 0; // just to make sure } } if (StringUtils.isNotEmpty(r.getThumbBG())) { try { Field field = Color.class.getField(r.getThumbBG()); col = (Color) field.get(null); } catch (Exception e) { LOGGER.debug("bad color name " + r.getThumbBG()); } } if (w == 0 && h == 0 && col == null) { return in; } ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedImage img1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = img1.createGraphics(); if (col != null) { g.setColor(col); } g.fillRect(0, 0, w, h); g.drawImage(img, 0, 0, w, h, null); ImageIO.write(img1, "jpeg", out); out.flush(); return new ByteArrayInputStream(out.toByteArray()); }
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//w w w .j a v a 2s. c om * @param iconSize the icon size (Std) * @param scaledIconSize the new scaled size in pixels * @return the scaled icon */ public static Image getScaledImage(final ImageIcon icon, final int newMaxWidth, final int newMaxHeight, final boolean maintainRatio) { if (icon != null) { int dstWidth = newMaxWidth; int dstHeight = newMaxHeight; int srcWidth = icon.getIconWidth(); int srcHeight = icon.getIconHeight(); if ((dstWidth < 0) || (dstHeight < 0)) { //image is nonstd, revert to original size dstWidth = icon.getIconWidth(); dstHeight = icon.getIconHeight(); } if (maintainRatio) { double longSideForSource = Math.max(srcWidth, srcHeight); double longSideForDest = Math.max(dstWidth, dstHeight); double multiplier = longSideForDest / longSideForSource; dstWidth = (int) (srcWidth * multiplier); dstHeight = (int) (srcHeight * multiplier); } Image imgMemory = icon.getImage(); //make sure all pixels in the image were loaded imgMemory = new ImageIcon(imgMemory).getImage(); BufferedImage thumbImage = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(imgMemory, 0, 0, dstWidth, dstHeight, 0, 0, srcWidth, srcHeight, null); graphics2D.dispose(); return thumbImage; } return null; }