List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:fr.amap.commons.javafx.chart.ChartViewer.java
/** * A handler for the export to PNG option in the context menu. *//*from w w w . ja v a 2s. c om*/ private void handleExportToPNG() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Export to PNG"); fileChooser.setSelectedExtensionFilter( new FileChooser.ExtensionFilter("Portable Network Graphics (PNG)", "png")); File file = fileChooser.showSaveDialog(stage); if (file != null) { try { CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize(); BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth, (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); int index = 0; for (ChartCanvas canvas : chartCanvasList) { Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index); ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(), (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight())); index++; } try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { ImageIO.write(image, "png", out); } } catch (IOException ex) { // FIXME: show a dialog with the error } } }
From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java
private BufferedImage convertImgToBufferedImg(Image limage, String l) { if (limage instanceof BufferedImage) { return ((BufferedImage) limage); } else {//from w ww .ja va2 s. c o m Image lImage = new ImageIcon(limage).getImage(); BufferedImage bufferedimage = new BufferedImage(lImage.getWidth(null), lImage.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics gr = bufferedimage.createGraphics(); gr.drawImage(lImage, 0, 0, null); gr.dispose(); return (bufferedimage); } }
From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java
public static BufferedImage scale(BufferedImage bi, int width, int height) { BufferedImage bi2; int scaleWidth = bi.getWidth(null); int scaleHeight = bi.getHeight(null); double scaleX = (double) width / scaleWidth; double scaleY = (double) height / scaleHeight; double scale = Math.min(scaleX, scaleY); scaleWidth = (int) ((double) scaleWidth * scale); scaleHeight = (int) ((double) scaleHeight * scale); Image scaledImage;// w w w . jav a2 s . co m if (HEADLESS) { // create a new buffered image, don't rely on a local graphics system (headless mode) final int type; if (bi.getType() != BufferedImage.TYPE_CUSTOM) { type = bi.getType(); } else if (bi.getAlphaRaster() != null) { // alpha channel available type = BufferedImage.TYPE_INT_ARGB; } else { type = BufferedImage.TYPE_INT_RGB; } bi2 = new BufferedImage(scaleWidth, scaleHeight, type); } else { GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); bi2 = gc.createCompatibleImage(scaleWidth, scaleHeight, bi.getTransparency()); } Graphics2D g = bi2.createGraphics(); if (scale < 0.3 && Math.max(scaleWidth, scaleHeight) < 500) { scaledImage = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH); new ImageIcon(scaledImage).getImage(); g.drawImage(scaledImage, 0, 0, scaleWidth, scaleHeight, null); } else { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g.drawImage(bi, 0, 0, scaleWidth, scaleHeight, null); } g.dispose(); return bi2; }
From source file:fr.amap.commons.javafx.chart.ChartViewer.java
/** * A handler for the export to PDF option in the context menu. *///from ww w . j a v a2 s.c o m private void handleExportToPDF() { FileChooser fileChooser = new FileChooser(); fileChooser.setSelectedExtensionFilter( new FileChooser.ExtensionFilter("Portable Document Format (PDF)", "pdf")); fileChooser.setTitle("Export to PDF"); File file = fileChooser.showSaveDialog(stage); if (file != null) { try { CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize(); PDDocument doc = new PDDocument(); PDPage page = new PDPage(new PDRectangle((float) canvasPositionAndSize.totalWidth, (float) canvasPositionAndSize.totalHeight)); doc.addPage(page); BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth, (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); int index = 0; for (ChartCanvas canvas : chartCanvasList) { Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index); ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(), (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight())); index++; } PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false); PDXObjectImage pdImage = new PDPixelMap(doc, image); contentStream.drawImage(pdImage, 0, 0); PDPageContentStream cos = new PDPageContentStream(doc, page); cos.drawXObject(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight()); cos.close(); doc.save(file); } catch (IOException | COSVisitorException ex) { Logger.getLogger(ChartViewer.class.getName()).log(Level.SEVERE, null, ex); } /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(), (int)canvas.getHeight(), file);*/ /*ExportUtils.writeAsPDF(this.chart, (int)canvas.getWidth(), (int)canvas.getHeight(), file);*/ } }
From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java
public BufferedImage generateImage() throws IOException { final int DEFAULT_CELL_WIDTH = 48; final int DEFAULT_CELL_HEIGHT = 48; final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns() : Math.round(this.docOptions.getImage().getSVGWidth()); final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows() : Math.round(this.docOptions.getImage().getSVGHeight()); final BufferedImage result; if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) { result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } else {/*from w w w .j ava 2 s . c o m*/ result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); } final Graphics2D gfx = result.createGraphics(); gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT, this.docOptions.getHexOrientation()); final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>(); for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) { final LayerExportRecord rec = this.exportData.getLayers().get(i); if (rec.isAllowed()) { reversedNormalizedStack.add(rec.getLayer()); } } if (Thread.currentThread().isInterrupted()) return null; final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()]; engine.setModel(new HexEngineModel<HexFieldValue[]>() { @Override public int getColumnNumber() { return docOptions.getColumns(); } @Override public int getRowNumber() { return docOptions.getRows(); } @Override public HexFieldValue[] getValueAt(final int col, final int row) { Arrays.fill(stackOfValues, null); for (int index = 0; index < reversedNormalizedStack.size(); index++) { stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row); } return stackOfValues; } @Override public HexFieldValue[] getValueAt(final HexPosition pos) { return this.getValueAt(pos.getColumn(), pos.getRow()); } @Override public void setValueAt(int col, int row, HexFieldValue[] value) { } @Override public void setValueAt(HexPosition pos, HexFieldValue[] value) { } @Override public boolean isPositionValid(final int col, final int row) { return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows(); } @Override public boolean isPositionValid(final HexPosition pos) { return this.isPositionValid(pos.getColumn(), pos.getRow()); } @Override public void attachedToEngine(final HexEngine<?> engine) { } @Override public void detachedFromEngine(final HexEngine<?> engine) { } }); final HexRect2D visibleSize = engine.getVisibleSize(); final float xcoeff = (float) result.getWidth() / visibleSize.getWidth(); final float ycoeff = (float) result.getHeight() / visibleSize.getHeight(); engine.setScale(xcoeff, ycoeff); final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][]; engine.setRenderer(new ColorHexRender() { private final Stroke stroke = new BasicStroke(docOptions.getLineWidth()); @Override public Stroke getStroke() { return this.stroke; } @Override public Color getFillColor(HexEngineModel<?> model, int col, int row) { return null; } @Override public Color getBorderColor(HexEngineModel<?> model, int col, int row) { return exportData.isExportHexBorders() ? docOptions.getColor() : null; } @Override public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor, Color fillColor) { } @Override public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col, final int row, final Color borderColor, final Color fillColor) { final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row); for (int i = 0; i < stackValues.length; i++) { final HexFieldValue valueToDraw = stackValues[i]; if (valueToDraw == null) { continue; } g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null); } } }); final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath(); final int cellWidth = hexShape.getBounds().width; final int cellHeight = hexShape.getBounds().height; for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size() && !Thread.currentThread().isInterrupted(); layerIndex++) { final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex); final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()]; for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) { cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth, cellHeight, hexShape, true); } cachedIcons[layerIndex] = cacheLineForLayer; } engine.drawWithThreadInterruptionCheck(gfx); if (Thread.currentThread().isInterrupted()) return null; if (this.exportData.isCellCommentariesExport()) { final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator(); gfx.setFont(new Font("Arial", Font.BOLD, 12)); while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) { final Entry<HexPosition, String> item = iterator.next(); final HexPosition pos = item.getKey(); final String text = item.getValue(); final float x = engine.calculateX(pos.getColumn(), pos.getRow()); final float y = engine.calculateY(pos.getColumn(), pos.getRow()); final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx); final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2; gfx.setColor(Color.BLACK); gfx.drawString(text, dx, y); gfx.setColor(Color.WHITE); gfx.drawString(text, dx - 2, y - 2); } } gfx.dispose(); return result; }
From source file:edu.ku.brc.ui.IconManager.java
/** * Gets a scaled icon and if it doesn't exist it creates one and scales it * @param icon image to be scaled//w ww. j av a 2 s . co m * @param iconSize the icon size (Std) * @param scaledIconSize the new scaled size in pixels * @return the scaled icon */ public Image getFastScale(final ImageIcon icon, final IconSize iconSize, final IconSize scaledIconSize) { if (icon != null) { int width = scaledIconSize.size(); int height = scaledIconSize.size(); if ((width < 0) || (height < 0)) { //image is nonstd, revert to original size width = icon.getIconWidth(); height = icon.getIconHeight(); } Image imgMemory = createImage(icon.getImage().getSource()); //make sure all pixels in the image were loaded imgMemory = new ImageIcon(imgMemory).getImage(); BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(imgMemory, 0, 0, width, height, null); graphics2D.dispose(); imgMemory = thumbImage; return imgMemory; } //else log.error("Couldn't find icon [" + iconSize + "] to scale to [" + scaledIconSize + "]"); return null; }
From source file:com.josue.tileset.editor.Editor.java
private BufferedImage getTileImage(int x, int y, BufferedImage tileSetImage) { BufferedImage tileImage; Graphics2D tileGraphics;/* ww w .ja va 2s. com*/ float opacity = 1L; tileImage = createTileImage(); tileGraphics = tileImage.createGraphics(); tileGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); tileGraphics.drawImage(tileSetImage, 0, // destiny x1 0, // destiny y1 TILE_SIZE, // destiny x2 TILE_SIZE, // destiny y2 x * TILE_SIZE, // source x1 y * TILE_SIZE, // source y1 x * TILE_SIZE + TILE_SIZE, // source x2 y * TILE_SIZE + TILE_SIZE, // source y2 null); return tileImage; }
From source file:jdroidremote.ServerFrame.java
private void startMonitoring() { thStartMonitoring = new Thread(new Runnable() { @Override/* w ww .j a v a 2 s . c om*/ public void run() { try { System.out.println("START MONITORING.........."); // while (1 == 1) { BufferedImage screenCapture = robot .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); Image cursor = ImageIO.read(new File("cursor.png")); int x = MouseInfo.getPointerInfo().getLocation().x; int y = MouseInfo.getPointerInfo().getLocation().y; Graphics2D graphics2D = screenCapture.createGraphics(); graphics2D.drawImage(cursor, x, y, 13, 25, null); // cursor.gif is 16x16 size. ImageIO.write(screenCapture, "JPG", new File("2.jpg")); Thread.sleep(200); File file = new File("2.jpg"); // Reading a Image file from file system FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); // Converting Image byte array into Base64 String String imageDataString = ImageManipulation.encodeImage(imageData); System.out.println(imageDataString.length()); // System.out.println(imageDataString); // // Converting a Base64 String into Image byte array // byte[] imageByteArray = ImageManipulation.decodeImage(imageDataString); // // // Write a image byte array into file system // FileOutputStream imageOutFile = new FileOutputStream( // "_avatar_.jpg"); // // imageOutFile.write(imageByteArray); imageInFile.close(); // imageOutFile.close(); System.out.println("Image Successfully Manipulated!"); // Split the five sandwiches.! StringBuilder sbImageDataString = new StringBuilder(imageDataString); for (int i = 0; i < sbImageDataString.toString().length(); i += 30000) { if (i + 30000 <= sbImageDataString.toString().length()) { dos.writeUTF(sbImageDataString.substring(i, i + 30000)); dos.flush(); } else { dos.writeUTF(sbImageDataString.substring(i, sbImageDataString.toString().length())); dos.flush(); } } dos.writeUTF("..."); dos.flush(); // } } catch (IOException ex) { Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex); } } }); }