List of usage examples for java.awt Graphics2D setBackground
public abstract void setBackground(Color color);
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(M_sm.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);//from w w w . java 2 s . c om FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:com.centurylink.mdw.designer.pages.ExportHelper.java
public byte[] printImage(float scale, CanvasCommon canvas, Dimension graphsize, String format) throws IOException { int h_margin = 72, v_margin = 72; BufferedImage image = new BufferedImage(graphsize.width + h_margin, graphsize.height + v_margin, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); if (scale > 0) g2.scale(scale, scale);/* w w w .ja v a 2 s . c om*/ g2.setBackground(Color.WHITE); g2.clearRect(0, 0, image.getWidth(), image.getHeight()); // canvas.paint(g2); Color bgsave = canvas.getBackground(); boolean edsave = canvas.editable; canvas.editable = false; canvas.setBackground(Color.white); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); canvas.paintComponent(g2); canvas.setBackground(bgsave); canvas.editable = edsave; g2.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, format, baos); image = null; Runtime r = Runtime.getRuntime(); r.gc(); return baos.toByteArray(); }
From source file:com.centurylink.mdw.designer.pages.ExportHelper.java
public void printImage(String filename, float scale, CanvasCommon canvas, Dimension graphsize) { try {/*from www . ja va 2 s .c o m*/ int h_margin = 72, v_margin = 72; BufferedImage image = new BufferedImage(graphsize.width + h_margin, graphsize.height + v_margin, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); if (scale > 0) g2.scale(scale, scale); g2.setBackground(Color.WHITE); g2.clearRect(0, 0, image.getWidth(), image.getHeight()); // canvas.paint(g2); Color bgsave = canvas.getBackground(); canvas.setBackground(Color.white); canvas.paintComponent(g2); canvas.setBackground(bgsave); g2.dispose(); ImageIO.write(image, "jpeg", new File(filename)); image = null; Runtime r = Runtime.getRuntime(); r.gc(); } catch (IOException e) { System.err.println(e); } }
From source file:org.sakaiproject.sitestats.impl.ServerWideReportManagerImpl.java
private byte[] generateNoDataChart(int width, int height) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = img.createGraphics(); g2d.setBackground(parseColor(statsManager.getChartBackgroundColor())); g2d.clearRect(0, 0, width - 1, height - 1); g2d.setColor(parseColor("#cccccc")); g2d.drawRect(0, 0, width - 1, height - 1); Font f = new Font("SansSerif", Font.PLAIN, 12); g2d.setFont(f);//from w ww .ja va 2 s. c om FontMetrics fm = g2d.getFontMetrics(f); String noData = msgs.getString("no_data"); int noDataWidth = fm.stringWidth(noData); int noDataHeight = fm.getHeight(); g2d.setColor(parseColor("#555555")); g2d.drawString(noData, width / 2 - noDataWidth / 2, height / 2 - noDataHeight / 2 + 2); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { log.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:MyJava3D.java
public Graphics2D createGraphics2D(int width, int height, BufferedImage bi, Graphics g) { Graphics2D g2 = null; if (bi != null) { g2 = bi.createGraphics();/* w w w . j av a 2 s . c o m*/ } else { g2 = (Graphics2D) g; } g2.setBackground(getBackground()); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, AntiAlias); g2.setRenderingHint(RenderingHints.KEY_RENDERING, Rendering); if (clearSurface || clearOnce) { g2.clearRect(0, 0, width, height); clearOnce = false; } if (texture != null) { // set composite to opaque for texture fills g2.setComposite(AlphaComposite.SrcOver); g2.setPaint(texture); g2.fillRect(0, 0, width, height); } if (composite != null) { g2.setComposite(composite); } return g2; }
From source file:Thumbnail.java
/** * Reads an image in a file and creates a thumbnail in another file. * largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly. * Utilises weighted stepping method to gradually reduce the image size for better results, * i.e. larger steps to start with then smaller steps to finish with. * Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'. * PNG's with transparency are given white backgrounds *//*from w w w . j a va2s . c om*/ public String createThumbnail(String inFilename, String outFilename, int largestDimension) { try { double scale; int sizeDifference, originalImageLargestDim; if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif") && !inFilename.endsWith(".png")) { return "Error: Unsupported image type, please only either JPG, GIF or PNG"; } else { Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename); if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) { return "Error loading file: \"" + inFilename + "\""; } else { //find biggest dimension if (inImage.getWidth(null) > inImage.getHeight(null)) { scale = (double) largestDimension / (double) inImage.getWidth(null); sizeDifference = inImage.getWidth(null) - largestDimension; originalImageLargestDim = inImage.getWidth(null); } else { scale = (double) largestDimension / (double) inImage.getHeight(null); sizeDifference = inImage.getHeight(null) - largestDimension; originalImageLargestDim = inImage.getHeight(null); } //create an image buffer to draw to BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles Graphics2D g2d; AffineTransform tx; if (scale < 1.0d) //only scale if desired size is smaller than original { int numSteps = sizeDifference / 100; int stepSize = sizeDifference / numSteps; int stepWeight = stepSize / 2; int heavierStepSize = stepSize + stepWeight; int lighterStepSize = stepSize - stepWeight; int currentStepSize, centerStep; double scaledW = inImage.getWidth(null); double scaledH = inImage.getHeight(null); if (numSteps % 2 == 1) //if there's an odd number of steps centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step else centerStep = -1; //set it to -1 so it's ignored later Integer intermediateSize = originalImageLargestDim, previousIntermediateSize = originalImageLargestDim; Integer calculatedDim; for (Integer i = 0; i < numSteps; i++) { if (i + 1 != centerStep) //if this isn't the center step { if (i == numSteps - 1) //if this is the last step { //fix the stepsize to account for decimal place errors previously currentStepSize = previousIntermediateSize - largestDimension; } else { if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions currentStepSize = heavierStepSize; else currentStepSize = lighterStepSize; } } else //center step, use natural step size { currentStepSize = stepSize; } intermediateSize = previousIntermediateSize - currentStepSize; scale = (double) intermediateSize / (double) previousIntermediateSize; scaledW = (int) scaledW * scale; scaledH = (int) scaledH * scale; outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB); g2d = outImage.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight()); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); tx = new AffineTransform(); tx.scale(scale, scale); g2d.drawImage(inImage, tx, null); g2d.dispose(); inImage = new ImageIcon(outImage).getImage(); previousIntermediateSize = intermediateSize; } } else { //just copy the original outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null), BufferedImage.TYPE_INT_RGB); g2d = outImage.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight()); tx = new AffineTransform(); tx.setToIdentity(); //use identity matrix so image is copied exactly g2d.drawImage(inImage, tx, null); g2d.dispose(); } //JPEG-encode the image and write to file. OutputStream os = new FileOutputStream(outFilename); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); encoder.encode(outImage); os.close(); } } } catch (Exception ex) { String errorMsg = ""; errorMsg += "<br>Exception: " + ex.toString(); errorMsg += "<br>Cause = " + ex.getCause(); errorMsg += "<br>Stack Trace = "; StackTraceElement stackTrace[] = ex.getStackTrace(); for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) { errorMsg += "<br>" + stackTrace[traceLine]; } return errorMsg; } return ""; //success }
From source file:org.apache.fop.afp.AFPGraphics2D.java
/** * Draws an AWT image into a BufferedImage using an AWT Graphics2D implementation * * @param img the AWT image// www . ja va 2s .c o m * @param bufferedImage the AWT buffered image * @param width the image width * @param height the image height * @param observer the image observer * @return true if the image was drawn */ private boolean drawBufferedImage(Image img, BufferedImage bufferedImage, int width, int height, ImageObserver observer) { java.awt.Graphics2D g2d = bufferedImage.createGraphics(); try { g2d.setComposite(AlphaComposite.SrcOver); Color color = new Color(1, 1, 1, 0); g2d.setBackground(color); g2d.setPaint(color); g2d.fillRect(0, 0, width, height); int imageWidth = bufferedImage.getWidth(); int imageHeight = bufferedImage.getHeight(); Rectangle clipRect = new Rectangle(0, 0, imageWidth, imageHeight); g2d.clip(clipRect); g2d.setComposite(gc.getComposite()); return g2d.drawImage(img, 0, 0, imageWidth, imageHeight, observer); } finally { g2d.dispose(); //drawn so dispose immediately to free system resource } }
From source file:org.apache.fop.render.bitmap.AbstractBitmapDocumentHandler.java
/** {@inheritDoc} */ public IFPainter startPageContent() throws IFException { int bitmapWidth; int bitmapHeight; double scale; Point2D offset = null;/* w ww . j a v a 2 s. com*/ if (targetBitmapSize != null) { //Fit the generated page proportionally into the given rectangle (in pixels) double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth(); double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight(); bitmapWidth = targetBitmapSize.width; bitmapHeight = targetBitmapSize.height; //Centering the page in the given bitmap offset = new Point2D.Double(); if (scale2w < scale2h) { scale = scale2w; double h = this.currentPageDimensions.height * scale / 1000; offset.setLocation(0, (bitmapHeight - h) / 2.0); } else { scale = scale2h; double w = this.currentPageDimensions.width * scale / 1000; offset.setLocation((bitmapWidth - w) / 2.0, 0); } } else { //Normal case: just scale according to the target resolution scale = scaleFactor * getUserAgent().getTargetResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f); bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f); } //Set up bitmap to paint on this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight); Graphics2D graphics2D = this.currentImage.createGraphics(); // draw page background if (!getSettings().hasTransparentPageBackground()) { graphics2D.setBackground(getSettings().getPageBackgroundColor()); graphics2D.setPaint(getSettings().getPageBackgroundColor()); graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight); } //Set rendering hints graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } if (getSettings().isQualityRenderingEnabled()) { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); //Set up initial coordinate system for the page if (offset != null) { graphics2D.translate(offset.getX(), offset.getY()); } graphics2D.scale(scale / 1000f, scale / 1000f); return new Java2DPainter(graphics2D, getContext(), getFontInfo()); }
From source file:org.apache.fop.render.pcl.PCLDocumentHandler.java
private IFPainter createAllBitmapPainter() { double scale = gen.getMaximumBitmapResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); int bitmapWidth = (int) Math.ceil(UnitConv.mpt2px(printArea.width, gen.getMaximumBitmapResolution())); int bitmapHeight = (int) Math.ceil(UnitConv.mpt2px(printArea.height, gen.getMaximumBitmapResolution())); this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight); Graphics2D graphics2D = this.currentImage.createGraphics(); if (!PCLGenerator.isJAIAvailable()) { RenderingHints hints = new RenderingHints(null); //These hints don't seem to make a difference :-( Not seeing any dithering on Sun Java. hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); graphics2D.addRenderingHints(hints); }/*from w ww. j a va 2s. com*/ //Ensure white page background graphics2D.setBackground(Color.WHITE); graphics2D.clearRect(0, 0, bitmapWidth, bitmapHeight); graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); graphics2D.scale(scale / 1000f, scale / 1000f); graphics2D.translate(-printArea.x, -printArea.y); return new Java2DPainter(graphics2D, getContext(), getFontInfo()); }
From source file:org.apache.fop.render.pcl.PCLPainter.java
private void drawTextAsBitmap(final int x, final int y, final int letterSpacing, final int wordSpacing, final int[] dx, final String text, FontTriplet triplet) throws IFException { //Use Java2D to paint different fonts via bitmap final Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize()); //for cursive fonts, so the text isn't clipped final FontMetricsMapper mapper = (FontMetricsMapper) parent.getFontInfo().getMetricsFor(font.getFontName()); final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000; final int ascent = mapper.getAscender(font.getFontSize()) / 1000; final int descent = mapper.getDescender(font.getFontSize()) / 1000; int safetyMargin = (int) (SAFETY_MARGIN_FACTOR * font.getFontSize()); final int baselineOffset = maxAscent + safetyMargin; final Rectangle boundingBox = getTextBoundingBox(x, y, letterSpacing, wordSpacing, dx, text, font, mapper); final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { if (DEBUG) { g2d.setBackground(Color.LIGHT_GRAY); g2d.clearRect(0, 0, (int) area.getWidth(), (int) area.getHeight()); }// w w w . j ava 2 s. c o m g2d.translate(-x, -y + baselineOffset); if (DEBUG) { Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent); g2d.draw(rect); rect = new Rectangle(x, y - ascent, 2000, ascent); g2d.draw(rect); rect = new Rectangle(x, y, 1000, -descent); g2d.draw(rect); } Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawText(x, y, letterSpacing, wordSpacing, dx, text); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); }