List of usage examples for java.awt Graphics2D dispose
public abstract void dispose();
From source file:eu.novait.imagerenamer.model.ImageFile.java
private void createThumbnail() { try {/* www .j a v a2 s . com*/ BufferedImage tmp = ImageIO.read(this.filepath); int tmpW = tmp.getWidth(); int tmpH = tmp.getHeight(); double ratio = (double) tmpW / (double) tmpH; int w = 400; int h = (int) Math.round(w / ratio); BufferedImage bi = getCompatibleImage(w, h); Graphics2D g2d = bi.createGraphics(); double xScale = (double) w / tmp.getWidth(); double yScale = (double) h / tmp.getHeight(); AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale); g2d.drawRenderedImage(tmp, at); g2d.dispose(); this.setThumbnail(bi); } catch (IOException ex) { Logger.getLogger(ImageFile.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:BufferedImageThread.java
public void paintComponent(Graphics g) { super.paintComponent(g); Dimension d = getSize();/*w w w . j a va 2 s . c o m*/ bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB); Graphics2D big = bi.createGraphics(); step(d.width, d.height); AffineTransform at = new AffineTransform(); at.setToIdentity(); at.translate(x, y); at.rotate(Math.toRadians(rotate)); at.scale(scale, scale); big.drawImage(image, at, this); Graphics2D g2D = (Graphics2D) g; g2D.drawImage(bi, 0, 0, null); big.dispose(); }
From source file:org.imos.abos.plot.JfreeChartDemo.java
protected void createPDF(String filename) { try {/* w w w .ja v a 2 s . co m*/ Rectangle page = PageSize.A4.rotate(); // step 1 Document document = new Document(page); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); float width = page.getWidth(); float height = page.getHeight(); // add chart PdfTemplate pie = cb.createTemplate(width, height); Graphics2D g2d1 = new PdfGraphics2D(pie, width, height); Rectangle2D r2d1 = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2d1, r2d1); g2d1.dispose(); cb.addTemplate(pie, 0, 0); // step 5 document.close(); } catch (DocumentException ex) { Logger.getLogger(JfreeChartDemo.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JfreeChartDemo.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("PDF finsihed"); }
From source file:de.jwic.ecolib.controls.chart.ChartControl.java
public void renderImage() throws IOException { // create image to draw into BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); if (chart != null) { chart.setBackgroundPaint(Color.WHITE); chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height)); } else {/*www .ja v a2s . co m*/ g2d.setColor(Color.BLACK); g2d.drawString("No chart has been assigned.", 1, 20); } // finish drawing g2d.dispose(); // write image data into output stream ByteArrayOutputStream out = getImageOutputStream(); out.reset(); // create a PNG image ImageWriter imageWriter = new PNGImageWriter(null); ImageWriteParam param = imageWriter.getDefaultWriteParam(); imageWriter.setOutput(new MemoryCacheImageOutputStream(out)); imageWriter.write(null, new IIOImage(bi, null, null), param); imageWriter.dispose(); setMimeType(MIME_TYPE_PNG); }
From source file:org.gumtree.vis.mask.ChartTransferableWithMask.java
@Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { BufferedImage image;/*from ww w. j av a2 s. c o m*/ if (this.imageFlavor.equals(flavor)) { image = chart.createBufferedImage(width, height); } else { throw new UnsupportedFlavorException(flavor); } Graphics2D g2 = image.createGraphics(); drawMasksInDataArea(g2, dataArea != null ? dataArea : new Rectangle2D.Double(0, 0, width, height), masks, chart); ChartMaskingUtilities.drawShapes(g2, dataArea, shapeMap, chart); ChartMaskingUtilities.drawText(g2, dataArea, textContentMap, chart); g2.dispose(); return image; }
From source file:org.lmn.fc.common.datatranslators.DataExporter.java
/*********************************************************************************************** * exportComponent()./*from w w w . j a va 2 s . co 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:org.jivesoftware.openfire.reporting.graph.GraphServlet.java
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException { try {/*from w w w.ja va 2s . c o m*/ Document document = new Document(PageSize.A4, 50, 50, 50, 50); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new PDFEventListener(request)); document.open(); int index = 0; int chapIndex = 0; for (Statistic stat : stats) { String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain(); String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " + JiveGlobals.formatDate(new Date(endtime)); Paragraph paragraph = new Paragraph(serverName, FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD)); document.add(paragraph); paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN)); document.add(paragraph); document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(), FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD)); document.add(chapterTitle); // total hack: no idea what tags people are going to use in the description // possibly recommend that we only use a <p> tag? String[] paragraphs = stat.getDescription().split("<p>"); for (String s : paragraphs) { Paragraph p = new Paragraph(s); document.add(p); } document.add(Chunk.NEWLINE); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); charts[index++].draw(graphs2D, rectangle2D); graphs2D.dispose(); float x = (document.getPageSize().width() / 2) - (width / 2); contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height); document.newPage(); } document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength is needed for MSIE!!! response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (DocumentException e) { Log.error("error creating PDF document: " + e.getMessage()); } }
From source file:embedding.ExampleJava2D2PDF.java
/** * Creates a PDF file. The contents are painted using a Graphics2D implementation that * generates an PDF file.//w w w. j a v a 2 s .c o m * @param outputFile the target file * @throws IOException In case of an I/O error * @throws ConfigurationException if an error occurs configuring the PDF output */ public void generatePDF(File outputFile) throws IOException, ConfigurationException { OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); try { //Instantiate the PDFDocumentGraphics2D instance PDFDocumentGraphics2D g2d = new PDFDocumentGraphics2D(false); g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); //Configure the G2D with the necessary fonts configure(g2d, createAutoFontsConfiguration()); //Set up the document size Dimension pageSize = new Dimension((int) Math.ceil(UnitConv.mm2pt(210)), (int) Math.ceil(UnitConv.mm2pt(297))); //page size A4 (in pt) g2d.setupDocument(out, pageSize.width, pageSize.height); g2d.translate(144, 72); //Establish some page borders //A few rectangles rotated and with different color Graphics2D copy = (Graphics2D) g2d.create(); int c = 12; for (int i = 0; i < c; i++) { float f = ((i + 1) / (float) c); Color col = new Color(0.0f, 1 - f, 0.0f); copy.setColor(col); copy.fillRect(70, 90, 50, 50); copy.rotate(-2 * Math.PI / c, 70, 90); } copy.dispose(); //Some text g2d.rotate(-0.25); g2d.setColor(Color.RED); g2d.setFont(new Font("sans-serif", Font.PLAIN, 36)); g2d.drawString("Hello world!", 140, 140); g2d.setColor(Color.RED.darker()); g2d.setFont(new Font("serif", Font.PLAIN, 36)); g2d.drawString("Hello world!", 140, 180); pageSize = new Dimension(pageSize.height, pageSize.width); g2d.nextPage(pageSize.width, pageSize.height); //Demonstrate painting rich text String someHTML = "<html><body style=\"font-family:Verdana\">" + "<p>Welcome to <b>page 2!</b></p>" + "<h2>PDFDocumentGraphics2D Demonstration</h2>" + "<p>We can <i>easily</i> paint some HTML here!</p>" + "<p style=\"color:green;\">" + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin accumsan" + " condimentum ullamcorper. Sed varius quam id arcu fermentum luctus. Praesent" + " nisi ligula, cursus sed vestibulum vel, sodales sed lectus.</p>" + "</body></html>"; JEditorPane htmlComp = new JEditorPane(); htmlComp.setContentType("text/html"); htmlComp.read(new StringReader(someHTML), null); htmlComp.setSize(new Dimension(pageSize.width - 72, pageSize.height - 72)); //htmlComp.setBackground(Color.ORANGE); htmlComp.validate(); htmlComp.printAll(g2d); //Cleanup g2d.finish(); } finally { IOUtils.closeQuietly(out); } }
From source file:info.magnolia.cms.taglibs.util.TextToImageTag.java
/** * Create an image file that is a scaled version of the original image * @param the original BufferedImage/*from w ww .j a v a 2 s . c om*/ * @param the scale factor * @return the new BufferedImage */ private BufferedImage scaleImage(BufferedImage oriImgBuff, double scaleFactor) { // get the dimesnions of the original image int oriWidth = oriImgBuff.getWidth(); int oriHeight = oriImgBuff.getHeight(); // get the width and height of the new image int newWidth = new Double(oriWidth * scaleFactor).intValue(); int newHeight = new Double(oriHeight * scaleFactor).intValue(); // create the thumbnail as a buffered image Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING); BufferedImage newImgBuff = new BufferedImage(newImg.getWidth(null), newImg.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = newImgBuff.createGraphics(); g.drawImage(newImg, 0, 0, null); g.dispose(); // return the newImgBuff return newImgBuff; }
From source file:it.smartcommunitylab.parking.management.web.manager.MarkerIconStorage.java
private void generateMarkerWithFlag(String basePath, String company, String entity, String color) throws IOException { BufferedImage templateIcon = ImageIO.read(new File(getIconFolder(basePath, ICON_FOLDER) + TEMPLATE_FILE)); BufferedImage icon = new BufferedImage(templateIcon.getWidth(), templateIcon.getHeight() + ICON_INCR_HEIGHT, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = icon.createGraphics(); graphics.setColor(new Color(Integer.parseInt(color, 16))); graphics.drawRect(0, 0, icon.getWidth(), COLOR_RECT_HEIGHT); graphics.fillRect(0, 0, icon.getWidth(), COLOR_RECT_HEIGHT); graphics.drawImage(templateIcon, 0, ICON_INCR_HEIGHT, null); graphics.dispose(); ImageIO.write(icon, ICON_TYPE, new File(getIconFolder(basePath, ICON_FOLDER_CACHE) + company + "-" + entity + "-" + color + ICON_EXTENSION)); }