List of usage examples for java.awt Graphics2D dispose
public abstract void dispose();
From source file:com.gst.infrastructure.documentmanagement.data.ImageData.java
public void resizeImage(InputStream in, OutputStream out, int maxWidth, int maxHeight) throws IOException { BufferedImage src = ImageIO.read(in); if (src.getWidth() <= maxWidth && src.getHeight() <= maxHeight) { out.write(getContent());//w ww. j a v a 2 s . co m return; } float widthRatio = (float) src.getWidth() / maxWidth; float heightRatio = (float) src.getHeight() / maxHeight; float scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio; // TODO(lindahl): Improve compressed image quality (perhaps quality // ratio) int newWidth = (int) (src.getWidth() / scaleRatio); int newHeight = (int) (src.getHeight() / scaleRatio); int colorModel = fileExtension == ContentRepositoryUtils.IMAGE_FILE_EXTENSION.JPEG ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage target = new BufferedImage(newWidth, newHeight, colorModel); Graphics2D g = target.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(src, 0, 0, newWidth, newHeight, Color.BLACK, null); g.dispose(); ImageIO.write(target, fileExtension != null ? fileExtension.getValueWithoutDot() : "jpeg", out); }
From source file:ddf.catalog.transformer.input.pdf.PdfInputTransformer.java
private byte[] generatePdfThumbnail(PDDocument pdfDocument) throws IOException { PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument); if (pdfDocument.getNumberOfPages() < 1) { /*//from w w w .j a va 2 s .co m * Can there be a PDF with zero pages??? Should we throw an error or what? The * original implementation assumed that a PDF would always have at least one * page. That's what I've implemented here, but I don't like make those * kinds of assumptions :-( But I also don't want to change the original * behavior without knowing how it will impact the system. */ } PDPage page = pdfDocument.getPage(0); BufferedImage image = pdfRenderer.renderImageWithDPI(0, RESOLUTION_DPI, ImageType.RGB); int largestDimension = Math.max(image.getHeight(), image.getWidth()); float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension; int scaledHeight = (int) (image.getHeight() * scalingFactor); int scaledWidth = (int) (image.getWidth() * scalingFactor); BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = scaledImage.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawImage(image, 0, 0, scaledWidth, scaledHeight, null); graphics.dispose(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ImageIOUtil.writeImage(scaledImage, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY); return outputStream.toByteArray(); } }
From source file:ec.display.chart.StatisticsChartPaneTab.java
/** * This method initializes jButton /* ww w . j a v a2s . c o m*/ * * @return javax.swing.JButton */ private JButton getPrintButton() { if (printButton == null) { printButton = new JButton(); printButton.setText("Export to PDF..."); final JFreeChart chart = chartPane.getChart(); printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { try { int width = chartPane.getWidth(); int height = chartPane.getHeight(); FileDialog fileDialog = new FileDialog(new Frame(), "Export...", FileDialog.SAVE); fileDialog.setDirectory(System.getProperty("user.dir")); fileDialog.setFile("*.pdf"); fileDialog.setVisible(true); String fileName = fileDialog.getFile(); if (fileName != null) { if (!fileName.endsWith(".pdf")) { fileName = fileName + ".pdf"; } File f = new File(fileDialog.getDirectory(), fileName); Document document = new Document(new com.lowagie.text.Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f)); document.addAuthor("ECJ Console"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, rectangle2D); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }); } return printButton; }
From source file:biz.ixnay.pivot.charts.skin.jfree.JFreeChartViewSkin.java
@Override public void paint(Graphics2D graphics) { int width = getWidth(); int height = getHeight(); if (bufferedImage == null || bufferedImage.getWidth() != width || bufferedImage.getHeight() != height) { chart = createChart();// w w w . j a v a2 s .co m bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D bufferedImageGraphics = (Graphics2D) bufferedImage.getGraphics(); java.awt.Rectangle area = new java.awt.Rectangle(0, 0, width, height); chart.setBackgroundPaint(null); chart.getPlot().setBackgroundPaint(getBackgroundColor()); chart.draw(bufferedImageGraphics, area, chartRenderingInfo); bufferedImageGraphics.dispose(); } graphics.drawImage(bufferedImage, 0, 0, null); }
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 ww w . j a v a 2s . c om*/ 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.chiorichan.factory.event.PostImageProcessor.java
@EventHandler() public void onEvent(PostEvalEvent event) { try {/*from www . java 2 s . co m*/ if (event.context().contentType() == null || !event.context().contentType().toLowerCase().startsWith("image")) return; float x = -1; float y = -1; boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true); boolean grayscale = false; ScriptingContext context = event.context(); HttpRequestWrapper request = context.request(); Map<String, String> rewrite = request.getRewriteMap(); if (rewrite != null) { if (rewrite.get("serverSideOptions") != null) { String[] params = rewrite.get("serverSideOptions").trim().split("_"); for (String p : params) if (p.toLowerCase().startsWith("width") && x < 0) x = Integer.parseInt(p.substring(5)); else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w")) && p.length() > 1 && x < 0) x = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().startsWith("height") && y < 0) y = Integer.parseInt(p.substring(6)); else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h")) && p.length() > 1 && y < 0) y = Integer.parseInt(p.substring(1)); else if (p.toLowerCase().equals("thumb")) { x = 150; y = 0; break; } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale")) grayscale = true; } if (request.getArgument("width") != null && request.getArgument("width").length() > 0) x = request.getArgumentInt("width"); if (request.getArgument("height") != null && request.getArgument("height").length() > 0) y = request.getArgumentInt("height"); if (request.getArgument("w") != null && request.getArgument("w").length() > 0) x = request.getArgumentInt("w"); if (request.getArgument("h") != null && request.getArgument("h").length() > 0) y = request.getArgumentInt("h"); if (request.getArgument("thumb") != null) { x = 150; y = 0; } if (request.hasArgument("bw") || request.hasArgument("grayscale")) grayscale = true; } // Tests if our Post Processor can process the current image. List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames()); List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames()); if (context.contentType() != null && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase())) return; int inx = event.context().buffer().readerIndex(); BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer())); event.context().buffer().readerIndex(inx); if (img == null) return; float w = img.getWidth(); float h = img.getHeight(); float w1 = w; float h1 = h; if (x < 1 && y < 1) { x = w; y = h; } else if (x > 0 && y < 1) { w1 = x; h1 = x * (h / w); } else if (y > 0 && x < 1) { w1 = y * (w / h); h1 = y; } else if (x > 0 && y > 0) { w1 = x; h1 = y; } boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h; boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8; if (!resize && !argb && !grayscale) return; // Produce a unique encapsulated id based on this image processing request String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale); File tmp = context.site() == null ? AppConfig.get().getDirectoryCache() : context.site().directoryTemp(); File file = new File(tmp, encapId + "_" + new File(context.filename()).getName()); if (cacheEnabled && file.exists()) { event.context().resetAndWrite(FileUtils.readFileToByteArray(file)); return; } Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1), AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST : Image.SCALE_SMOOTH) : img; // TODO Report malformed parameters to user if (argb) { FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(), new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16))); image = Toolkit.getDefaultToolkit().createImage(filteredSrc); } BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType()); Graphics2D graphics = rtn.createGraphics(); graphics.drawImage(image, 0, 0, null); graphics.dispose(); if (grayscale) { ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); op.filter(rtn, rtn); } if (resize) Log.get().info(EnumColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h) + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px"); if (rtn != null) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); if (context.contentType() != null && writerFormats.contains(context.contentType().split("/")[1].toLowerCase())) ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs); else ImageIO.write(rtn, "png", bs); if (cacheEnabled && !file.exists()) FileUtils.writeByteArrayToFile(file, bs.toByteArray()); event.context().resetAndWrite(bs.toByteArray()); } } catch (Throwable e) { e.printStackTrace(); } return; }
From source file:com.epiq.bitshark.ui.IVQPanel.java
public IVQPanel() { initComponents();//from w w w . j a v a2s . co m initGraph(); JPanel holderPanel = new JPanel() { @Override public void paint(Graphics g) { Range newDomain = null; // x Range newRange = null; // y Range currentDomainRange = plot.getDomainAxis().getRange(); Range currentRangeRange = plot.getRangeAxis().getRange(); if (plot.getDomainAxis().isAutoRange()) { plot.getDomainAxis().setAutoRange(false); } if (plot.getRangeAxis().isAutoRange()) { plot.getRangeAxis().setAutoRange(false); } Rectangle2D dataArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea(); double width = dataArea.getWidth(); double height = dataArea.getHeight(); double domainScale = 1; double rangeScale = 1; // scale the domain values up to match the pixels if (width > height) { domainScale = width / height; double extent = currentRangeRange.getUpperBound() - currentRangeRange.getLowerBound(); newDomain = new Range(-(extent * domainScale) / 2, (extent * domainScale) / 2); } else if (height > width) { rangeScale = height / width; double extent = currentDomainRange.getUpperBound() - currentDomainRange.getLowerBound(); newRange = new Range(-(extent * rangeScale) / 2, (extent * rangeScale) / 2); } if (newDomain == null) { double extent = currentDomainRange.getUpperBound() - currentDomainRange.getLowerBound(); newDomain = new Range(-(extent) / 2, (extent) / 2); } if (newRange == null) { double extent = currentRangeRange.getUpperBound() - currentRangeRange.getLowerBound(); newRange = new Range(-(extent) / 2, (extent) / 2); } if (newDomain != null) { plot.getDomainAxis().setRange(newDomain, true, false); } if (newRange != null) { plot.getRangeAxis().setRange(newRange, true, false); } Graphics2D g2 = (Graphics2D) g.create(); super.paint(g2); g2.dispose(); } }; holderPanel.setLayout(new BorderLayout()); holderPanel.add(chartPanel, BorderLayout.CENTER); mainPanel.add(holderPanel, BorderLayout.CENTER); headerPanel.setBackgroundPainter(Common.getHeaderPainter()); chartLabel.setUI(new BasicLabelUI()); }
From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java
/** * Creates a thumbnail for the image file using plain old java * @param file the image file// ww w . j a v a 2 s . c o m * @param thumbFile the resulting thumbnail file * @param size the size of the thumbnail */ private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException { try { BufferedImage image = ImageIO.read(file.toFile()); int w = image.getWidth(); int h = image.getHeight(); // Never scale up if (w <= size.getSize() && h <= size.getSize()) { FileUtils.copyFile(file.toFile(), thumbFile.toFile()); } else { // Compute the scale factor double dx = (double) size.getSize() / (double) w; double dy = (double) size.getSize() / (double) h; double d = Math.min(dx, dy); // Create the thumbnail BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = thumbImage.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(d, d); g2d.drawRenderedImage(image, at); g2d.dispose(); // Save the thumbnail String fileName = thumbFile.getFileName().toString(); ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile()); // Releas resources image.flush(); thumbImage.flush(); } // Update the timestamp of the thumbnail file to match the change date of the image file Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file)); } catch (Exception e) { log.error("Error creating thumbnail for image " + file, e); throw new IOException(e); } }
From source file:image.writer.ImageWriterExample1.java
/** * Paints a few things on a Graphics2D instance. * @param g2d the Graphics2D instance/*from w w w .ja v a2 s.co m*/ * @param pageNum a page number */ protected void paintSome(Graphics2D g2d, int pageNum) { //Paint a bounding box g2d.drawRect(0, 0, 400, 200); //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 / (double) c, 70, 90); } copy.dispose(); //Some text copy = (Graphics2D) g2d.create(); copy.rotate(-0.25); copy.setColor(Color.RED); copy.setFont(new Font("sans-serif", Font.PLAIN, 36)); copy.drawString("Hello world!", 140, 140); copy.setColor(Color.RED.darker()); copy.setFont(new Font("serif", Font.PLAIN, 36)); copy.drawString("Hello world!", 140, 180); copy.dispose(); //Try attributed text AttributedString aString = new AttributedString("This is attributed text."); aString.addAttribute(TextAttribute.FAMILY, "SansSerif"); aString.addAttribute(TextAttribute.FAMILY, "Serif", 8, 18); aString.addAttribute(TextAttribute.FOREGROUND, Color.orange, 8, 18); g2d.drawString(aString.getIterator(), 250, 170); g2d.drawString("Page: " + pageNum, 250, 190); }
From source file:TexturedPanel.java
/** * Creates a new TexturePaint using the provided image. */// w ww. j a v a2s . c o m private void setupImagePainter(Image texture) { if (texture == null) { ourPainter = null; return; } int w = texture.getWidth(this); int h = texture.getHeight(this); if (w <= 0 || h <= 0) { ourPainter = null; return; } BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); g2.drawImage(texture, 0, 0, this); ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w, h)); g2.dispose(); }