List of usage examples for java.awt Graphics2D setBackground
public abstract void setBackground(Color color);
From source file:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java
private BufferedImage getImage(int width, int height, Image img, ImageObserver observer) { Dimension size = new Dimension(width, height); BufferedImage buf = buildBufferedImage(size); Graphics2D g = buf.createGraphics(); g.setComposite(AlphaComposite.SrcOver); g.setBackground(new Color(1, 1, 1, 0)); g.fillRect(0, 0, width, height);//from w ww . j av a 2 s .com g.clip(new Rectangle(0, 0, buf.getWidth(), buf.getHeight())); if (!g.drawImage(img, 0, 0, observer)) { return null; } g.dispose(); return buf; }
From source file:org.apache.fop.util.BitmapImageUtilTestCase.java
private BufferedImage createTestImage() { BufferedImage buf = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = buf.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, buf.getWidth(), buf.getHeight()); //A few rectangles rotated and with different color Graphics2D copy = (Graphics2D) g2d.create(); copy.translate(170, 170);//from www . ja va 2 s . c om 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(0, 0, 120, 120); copy.rotate(-2 * Math.PI / c); } copy.dispose(); //the same in gray scales copy = (Graphics2D) g2d.create(); copy.translate(470, 310); c = 12; for (int i = 0; i < c; i++) { float f = ((i + 1) / (float) c); Color col = new Color(f, f, f); copy.setColor(col); copy.fillRect(0, 0, 120, 120); copy.rotate(-2 * Math.PI / c); } copy.dispose(); return buf; }
From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java
public void init() { boolean emptyBackground = true; if (config.isUseImageBackground() && background != null) { ByteArrayInputStream is = new ByteArrayInputStream(background); JPEGImgDecoder decoder = new DefaultJPEGImgDecoder(); try {// w ww . j a v a2 s. co m this.image = decoder.decodeAsBufferedImage(is); this.width = image.getWidth(); this.height = image.getHeight(); emptyBackground = false; } catch (Exception e) { emptyBackground = true; } } if (emptyBackground) { this.width = config.getTextMarginLeft() * 2; this.height = config.getTextMarginBottom() * 6; } char[] chars = challengeId.toCharArray(); charAttsList = new ArrayList(); TextLayout text = null; AffineTransform textAt = null; String[] fontNames = config.getFontNames(); for (int i = 0; i < chars.length; i++) { // font name String fontName = (fontNames.length == 1) ? fontNames[0] : fontNames[randomInt(0, fontNames.length)]; // rise int rise = config.getTextRiseRange(); if (rise > 0) { rise = randomInt(config.getTextMarginBottom(), config.getTextMarginBottom() + config.getTextRiseRange()); } if (config.getTextShear() > 0.0 || config.getTextRotation() > 0) { // rotation double dRotation = 0.0; if (config.getTextRotation() > 0) { dRotation = Math.toRadians(randomInt(-(config.getTextRotation()), config.getTextRotation())); } // shear double shearX = 0.0; double shearY = 0.0; if (config.getTextShear() > 0.0) { Random ran = new Random(); shearX = ran.nextDouble() * config.getTextShear(); shearY = ran.nextDouble() * config.getTextShear(); } CharAttributes cf = new CharAttributes(chars[i], fontName, dRotation, rise, shearX, shearY); charAttsList.add(cf); text = new TextLayout(chars[i] + "", getFont(fontName), new FontRenderContext(null, config.isFontAntialiasing(), false)); textAt = new AffineTransform(); if (config.getTextRotation() > 0) textAt.rotate(dRotation); if (config.getTextShear() > 0.0) textAt.shear(shearX, shearY); } else { CharAttributes cf = new CharAttributes(chars[i], fontName, 0, rise, 0.0, 0.0); charAttsList.add(cf); } if (emptyBackground) { Shape shape = text.getOutline(textAt); // this.width += text.getBounds().getWidth(); this.width += (int) shape.getBounds2D().getWidth(); this.width += config.getTextSpacing() + 1; if (this.height < (int) shape.getBounds2D().getHeight() + rise) { this.height = (int) shape.getBounds2D().getHeight() + rise; } } } if (emptyBackground) { this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gfx = (Graphics2D) this.image.getGraphics(); gfx.setBackground(Color.WHITE); gfx.clearRect(0, 0, width, height); } }
From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java
private static int[] generateVideo(String path, int nFrames, int width, int height, int numShapes, Random r, boolean backgroundNoise, int numDistractorsPerFrame) throws Exception { //First: decide where transitions between one shape and another are double[] rns = new double[numShapes]; double sum = 0; for (int i = 0; i < numShapes; i++) { rns[i] = r.nextDouble();//from w w w . j a va 2s. c om sum += rns[i]; } for (int i = 0; i < numShapes; i++) rns[i] /= sum; int[] startFrames = new int[numShapes]; startFrames[0] = 0; for (int i = 1; i < numShapes; i++) { startFrames[i] = (int) (startFrames[i - 1] + MIN_FRAMES + rns[i] * (nFrames - numShapes * MIN_FRAMES)); } //Randomly generate shape positions, velocities, colors, and type int[] shapeTypes = new int[numShapes]; int[] initialX = new int[numShapes]; int[] initialY = new int[numShapes]; double[] velocityX = new double[numShapes]; double[] velocityY = new double[numShapes]; Color[] color = new Color[numShapes]; for (int i = 0; i < numShapes; i++) { shapeTypes[i] = r.nextInt(NUM_SHAPES); initialX[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE); initialY[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE); velocityX[i] = -1 + 2 * r.nextDouble(); velocityY[i] = -1 + 2 * r.nextDouble(); color[i] = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } //Generate a sequence of BufferedImages with the given shapes, and write them to the video SequenceEncoder enc = new SequenceEncoder(new File(path)); int currShape = 0; int[] labels = new int[nFrames]; for (int i = 0; i < nFrames; i++) { if (currShape < numShapes - 1 && i >= startFrames[currShape + 1]) currShape++; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bi.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setBackground(Color.BLACK); if (backgroundNoise) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bi.setRGB(x, y, new Color(r.nextFloat() * MAX_NOISE_VALUE, r.nextFloat() * MAX_NOISE_VALUE, r.nextFloat() * MAX_NOISE_VALUE).getRGB()); } } } g2d.setColor(color[currShape]); //Position of shape this frame int currX = (int) (initialX[currShape] + (i - startFrames[currShape]) * velocityX[currShape] * MAX_VELOCITY); int currY = (int) (initialY[currShape] + (i - startFrames[currShape]) * velocityY[currShape] * MAX_VELOCITY); //Render the shape switch (shapeTypes[currShape]) { case 0: //Circle g2d.fill(new Ellipse2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE)); break; case 1: //Square g2d.fill(new Rectangle2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE)); break; case 2: //Arc g2d.fill(new Arc2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE, 315, 225, Arc2D.PIE)); break; case 3: //Line g2d.setStroke(lineStroke); g2d.draw(new Line2D.Double(currX, currY, currX + SHAPE_SIZE, currY + SHAPE_SIZE)); break; default: throw new RuntimeException(); } //Add some distractor shapes, which are present for one frame only for (int j = 0; j < numDistractorsPerFrame; j++) { int distractorShapeIdx = r.nextInt(NUM_SHAPES); int distractorX = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE); int distractorY = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE); g2d.setColor(new Color(r.nextFloat(), r.nextFloat(), r.nextFloat())); switch (distractorShapeIdx) { case 0: g2d.fill(new Ellipse2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE)); break; case 1: g2d.fill(new Rectangle2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE)); break; case 2: g2d.fill(new Arc2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE, 315, 225, Arc2D.PIE)); break; case 3: g2d.setStroke(lineStroke); g2d.draw(new Line2D.Double(distractorX, distractorY, distractorX + SHAPE_SIZE, distractorY + SHAPE_SIZE)); break; default: throw new RuntimeException(); } } enc.encodeImage(bi); g2d.dispose(); labels[i] = shapeTypes[currShape]; } enc.finish(); //write .mp4 return labels; }
From source file:org.dishevelled.brainstorm.BrainStorm.java
/** * Create and return a new hidden cursor, that is a fully transparent one pixel custom cursor. * * @return a new hidden cursor//from www . j a v a2s .c om */ private Cursor createHiddenCursor() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension size = toolkit.getBestCursorSize(1, 1); BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); graphics.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f)); graphics.clearRect(0, 0, size.width, size.height); graphics.dispose(); return toolkit.createCustomCursor(image, new Point(0, 0), "hiddenCursor"); }
From source file:org.eclipse.wb.internal.swing.model.property.editor.beans.PropertyEditorWrapper.java
private Image paintValue(GC gc, int width, int height) throws Exception { // create AWT graphics BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = (Graphics2D) image.getGraphics(); // prepare color's Color background = gc.getBackground(); Color foreground = gc.getForeground(); // fill graphics graphics2D.setColor(SwingUtils.getAWTColor(background)); graphics2D.fillRect(0, 0, width, height); // set color/*from ww w. ja va 2 s.c o m*/ graphics2D.setBackground(SwingUtils.getAWTColor(background)); graphics2D.setColor(SwingUtils.getAWTColor(foreground)); // set font FontData[] fontData = gc.getFont().getFontData(); String name = fontData.length > 0 ? fontData[0].getName() : "Arial"; graphics2D.setFont(new java.awt.Font(name, java.awt.Font.PLAIN, graphics2D.getFont().getSize() - 1)); // paint image m_propertyEditor.paintValue(graphics2D, new java.awt.Rectangle(0, 0, width, height)); // conversion try { return SwingImageUtils.convertImage_AWT_to_SWT(image); } finally { image.flush(); graphics2D.dispose(); } }
From source file:org.encuestame.business.images.ImageThumbnailGeneratorImpl.java
/** * Create a thumbnail image and save it to disk. * * This algorithm is based on:/*from w ww. j a v a 2s . c o m*/ * http://www.philreeve.com/java_high_quality_thumbnails.php * * @param imageIn The image you want to scale. * @param fileOut The output file. * @param largestDimension The largest dimension, so that neither the width nor height * will exceed this value. * * @return the image that was created, null if imageIn or fileOut is null. * @throws java.io.IOException if something goes wrong when saving as jpeg */ public BufferedImage createThumbnailImage(Image imageIn, File fileOut, int largestDimension) throws IOException { if ((imageIn == null) || (fileOut == null)) { return null; } //it seems to not return the right size until the methods get called for the first time imageIn.getWidth(null); imageIn.getHeight(null); // Find biggest dimension int nImageWidth = imageIn.getWidth(null); int nImageHeight = imageIn.getHeight(null); int nImageLargestDim = Math.max(nImageWidth, nImageHeight); double scale = (double) largestDimension / (double) nImageLargestDim; int sizeDifference = nImageLargestDim - largestDimension; //create an image buffer to draw to BufferedImage imageOut = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); // 8-bit RGB Graphics2D g2d; AffineTransform tx; // Use a few steps if the sizes are drastically different, and only scale // if the desired size is smaller than the original. int numSteps = 0; if (scale < 1.0d) { // Make sure we have at least 1 step numSteps = Math.max(1, (sizeDifference / 100)); } if (numSteps > 0) { int stepSize = sizeDifference / numSteps; int stepWeight = stepSize / 2; int heavierStepSize = stepSize + stepWeight; int lighterStepSize = stepSize - stepWeight; int currentStepSize, centerStep; double scaledW = imageIn.getWidth(null); double scaledH = imageIn.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; Integer previousIntermediateSize = nImageLargestDim; 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 = intermediateSize / (double) previousIntermediateSize; scaledW = Math.max((int) (scaledW * scale), 1); scaledH = Math.max((int) (scaledH * scale), 1); log.info("step " + i + ": scaling to " + scaledW + " x " + scaledH); imageOut = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB); // 8 bit RGB g2d = imageOut.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight()); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); tx = new AffineTransform(); tx.scale(scale, scale); g2d.drawImage(imageIn, tx, null); g2d.dispose(); imageIn = new ImageIcon(imageOut).getImage(); previousIntermediateSize = intermediateSize; } } else { // This enforces a rule that we always have an 8-bit image with white background for the thumbnail. Plus, for large // images, this makes subsequent downscaling really fast because we are working on a large 8-bit image // instead of a large 12 or 24 bit image, so the downstream effect is very noticable. imageOut = new BufferedImage(imageIn.getWidth(null), imageIn.getHeight(null), BufferedImage.TYPE_INT_RGB); g2d = imageOut.createGraphics(); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, imageOut.getWidth(), imageOut.getHeight()); tx = new AffineTransform(); tx.setToIdentity(); //use identity matrix so image is copied exactly g2d.drawImage(imageIn, tx, null); g2d.dispose(); } //saveImageAsJPEG(imageOut, fileOut); ImageIO.write(imageOut, "jpg", fileOut); return imageOut; }
From source file:org.goko.viewer.jogl.service.JoglSceneManager.java
private void drawOverlay() { this.frame += 1; overlay.beginRendering();//from www . j av a 2 s.com Graphics2D g2d = overlay.createGraphics(); try { if (getActiveCamera() != null) { FontRenderContext frc = g2d.getFontRenderContext(); String cameraString = getActiveCamera().getLabel(); GlyphVector gv = getOverlayFont().createGlyphVector(frc, cameraString); Rectangle bounds = gv.getPixelBounds(frc, 0, 0); int x = 5; int y = 5 + bounds.height; g2d.setFont(getOverlayFont()); Color overlayColor = new Color(0.8f, 0.8f, 0.8f); Color transparentColor = new Color(0, 0, 0, 0); g2d.setBackground(transparentColor); g2d.setColor(overlayColor); g2d.clearRect(0, 0, getWidth(), height); if (isEnabled()) { g2d.drawString(cameraString, x, y); } else { g2d.drawString("Disabled", x, y); } if (System.currentTimeMillis() - lastFrameReset >= 500) { this.lastFrameReset = System.currentTimeMillis(); this.fps = this.frame; this.frame = 0; } g2d.setColor(new Color(0.55f, 0.45f, 0.28f)); g2d.drawString(String.valueOf(this.fps * 2) + "fps", x, y + bounds.height + 4); drawOverlayData(g2d); overlay.markDirty(0, 0, getWidth(), height); overlay.drawAll(); } } catch (GkException e) { LOG.error(e); } g2d.dispose(); overlay.endRendering(); }
From source file:org.limy.eclipse.qalab.outline.sequence.SequenceImageCreator.java
/** * V?[PX?}?? layoutData, pngFile ?o?B//w w w . ja v a2s . c o m * @param root V?[PX?}Bean * @throws IOException I/OO * @throws ParserException */ private void writeSequence(SequenceBean root) throws IOException, ParserException { StringWriter out = new StringWriter(); Context context = new VelocityContext(); context.put("root", root); VelocitySupport.write(new File(LimyQalabPlugin.getDefault().getPluginRoot(), "resource/sequence/index.vm") .getAbsolutePath(), context, out); File txtFile = LimyQalabUtils.createTempFile(env.getProject(), "sequence.txt"); pngFile = LimyQalabUtils.createTempFile(env.getProject(), "sequence.png"); FileUtils.writeByteArrayToFile(txtFile, out.toString().getBytes()); Parser parser = ParserFactory.getInstance().getDefaultParser(); NodeFactory nodeFactory = ParserFactory.getInstance().getNodeFactoryForParser(parser); Diagram diagram = new Diagram(parser, nodeFactory); PushbackReader reader = new PushbackReader(new FileReader(txtFile)); try { diagram.parse(reader); } finally { reader.close(); } Model model = new Model(new ExceptionHandler() { public void exception(Exception e) { e.printStackTrace(); } }, diagram); BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = bi.createGraphics(); layoutData = new LayoutData(new SwingStringMeasure(graphics)); diagram.layout(layoutData); int height = layoutData.getHeight(); int width = layoutData.getWidth(); BufferedImage png = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D pngGraphics = png.createGraphics(); pngGraphics.setClip(0, 0, width, height); Map<Key, Object> hintsMap = new HashMap<Key, Object>(); hintsMap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); pngGraphics.addRenderingHints(hintsMap); pngGraphics.setBackground(Prefs.getColorValue(Prefs.BACKGROUND_COLOR)); pngGraphics.fillRect(0, 0, width, height); SwingPainter painter = new SwingPainter(); painter.setGraphics(pngGraphics); model.layout(layoutData); layoutData.paint(painter); ImageIO.write(png, "png", pngFile); }
From source file:org.pentaho.reporting.engine.classic.core.function.PaintDynamicComponentFunction.java
/** * Creates the component.//from www. ja va2 s . c o m * * @return the created image or null, if no image could be created. */ private Image createComponentImage() { final Object o = getDataRow().get(getField()); if ((o instanceof Component) == false) { return null; } final float scale = getScale() * getDeviceScale(); final ComponentDrawable drawable = new ComponentDrawable(); drawable.setComponent((Component) o); drawable.setAllowOwnPeer(true); drawable.setPaintSynchronized(true); final Dimension dim = drawable.getSize(); final int width = Math.max(1, (int) (scale * dim.width)); final int height = Math.max(1, (int) (scale * dim.height)); final BufferedImage bi = ImageUtils.createTransparentImage(width, height); final Graphics2D graph = bi.createGraphics(); graph.setBackground(new Color(0, 0, 0, 0)); graph.setTransform(AffineTransform.getScaleInstance(scale, scale)); drawable.draw(graph, new Rectangle2D.Float(0, 0, dim.width, dim.height)); graph.dispose(); return bi; }