List of usage examples for java.awt Graphics2D setBackground
public abstract void setBackground(Color color);
From source file:org.photovault.swingui.PhotoCollectionThumbView.java
private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) { log.debug("paintThumbnail entry " + photo.getUuid()); long startTime = System.currentTimeMillis(); long thumbReadyTime = 0; long thumbDrawnTime = 0; long endTime = 0; // Current position in which attributes can be drawn int ypos = starty + rowHeight / 2; boolean useOldThumbnail = false; Thumbnail thumbnail = null;/*from ww w. j a va 2 s .c o m*/ log.debug("finding thumb"); boolean hasThumbnail = photo.hasThumbnail(); log.debug("asked if has thumb"); if (hasThumbnail) { log.debug("Photo " + photo.getUuid() + " has thumbnail"); thumbnail = photo.getThumbnail(); log.debug("got thumbnail"); } else { /* Check if the thumbnail has been just invalidated. If so, use the old one until we get the new thumbnail created. */ thumbnail = photo.getOldThumbnail(); if (thumbnail != null) { useOldThumbnail = true; } else { // No success, use default thumnail. thumbnail = Thumbnail.getDefaultThumbnail(); } // Inform background task scheduler that we have some work to do ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL); } thumbReadyTime = System.currentTimeMillis(); log.debug("starting to draw"); // Find the position for the thumbnail BufferedImage img = thumbnail.getImage(); if (img == null) { thumbnail = Thumbnail.getDefaultThumbnail(); img = thumbnail.getImage(); } float scaleX = ((float) thumbWidth) / ((float) img.getWidth()); float scaleY = ((float) thumbHeight) / ((float) img.getHeight()); float scale = Math.min(scaleX, scaleY); int w = (int) (img.getWidth() * scale); int h = (int) (img.getHeight() * scale); int x = startx + (columnWidth - w) / (int) 2; int y = starty + (rowHeight - h) / (int) 2; log.debug("drawing thumbnail"); // Draw shadow int offset = isSelected ? 2 : 0; int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset }; int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset }; GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length); polyline.moveTo(shadowX[0], shadowY[0]); for (int index = 1; index < shadowX.length; index++) { polyline.lineTo(shadowX[index], shadowY[index]); } ; BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); Stroke oldStroke = g2.getStroke(); g2.setStroke(shadowStroke); g2.setColor(Color.DARK_GRAY); g2.draw(polyline); g2.setStroke(oldStroke); // Paint thumbnail g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null); if (useOldThumbnail) { creatingThumbIcon.paintIcon(this, g2, startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2, starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2); } log.debug("Drawn, drawing decorations"); if (isSelected) { Stroke prevStroke = g2.getStroke(); Color prevColor = g2.getColor(); g2.setStroke(new BasicStroke(3.0f)); g2.setColor(Color.BLUE); g2.drawRect(x, y, w, h); g2.setColor(prevColor); g2.setStroke(prevStroke); } thumbDrawnTime = System.currentTimeMillis(); boolean drawAttrs = (thumbWidth >= 100); if (drawAttrs) { // Increase ypos so that attributes are drawn under the image ypos += ((int) h) / 2 + 3; // Draw the attributes // Draw the qualoity icon to the upper left corner of the thumbnail int quality = photo.getQuality(); if (showQuality && quality != 0) { int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2; for (int n = 0; n < quality; n++) { starIcon.paintIcon(this, g2, qx, ypos); qx += starIcon.getIconWidth(); } ypos += starIcon.getIconHeight(); } ypos += 6; if (photo.getRawSettings() != null) { // Draw the "RAW" icon int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5; int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5; rawIcon.paintIcon(this, g2, rx, ry); } if (photo.getHistory().getHeads().size() > 1) { // Draw the "unresolved conflicts" icon int rx = startx + (columnWidth + w - 10) / (int) 2 - 20; int ry = starty + (columnWidth - h - 10) / (int) 2; g2.setColor(Color.RED); g2.fillRect(rx, ry, 10, 10); } Color prevBkg = g2.getBackground(); if (isSelected) { g2.setBackground(Color.BLUE); } else { g2.setBackground(this.getBackground()); } Font attrFont = new Font("Arial", Font.PLAIN, 10); FontRenderContext frc = g2.getFontRenderContext(); if (showDate && photo.getShootTime() != null) { FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy()); String dateStr = fd.format(); TextLayout txt = new TextLayout(dateStr, attrFont, frc); // Calculate the position for the text Rectangle2D bounds = txt.getBounds(); int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX(); g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4); txt.draw(g2, xpos, (int) (ypos + bounds.getHeight())); ypos += bounds.getHeight() + 4; } String shootPlace = photo.getShootingPlace(); if (showPlace && shootPlace != null && shootPlace.length() > 0) { TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc); // Calculate the position for the text Rectangle2D bounds = txt.getBounds(); int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX(); g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4); txt.draw(g2, xpos, (int) (ypos + bounds.getHeight())); ypos += bounds.getHeight() + 4; } g2.setBackground(prevBkg); } endTime = System.currentTimeMillis(); log.debug("paintThumbnail: exit " + photo.getUuid()); log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms"); log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms"); log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms"); log.debug("Total " + (endTime - startTime) + " ms"); }
From source file:org.viafirma.util.QRCodeUtil.java
/** * Genera codigo de firma para impresin formado por el texto, el cdigo qr * del texto y un cdigo de barras con el cdigo de firma. * //from w ww . ja v a 2 s.c o m * @param text * @param codFirma * @return * @throws ExcepcionErrorInterno */ public byte[] generate(String text, String url, String textoQR, String codFirma) throws ExcepcionErrorInterno { // Comprobamos el tamao del texto. No recomendamos textos de mas de 120 // caracteres if (textoQR.length() > MAX_TEXT_SIZE) { log.warn("El tamao del texto '" + text + "' ha excedido el tamao mximo. " + text.length() + ">" + MAX_TEXT_SIZE); textoQR = textoQR.substring(textoQR.lastIndexOf(" ")); log.warn("El texto sera recortado: '" + textoQR + "'"); } // Generamos la sufperficie de dibujo BufferedImage imagenQR = new BufferedImage(ANCHO_ETIQUETA, ALTO_ETIQUETA, BufferedImage.TYPE_INT_RGB); Graphics2D g = imagenQR.createGraphics(); // El fondo es blanco g.setBackground(Color.WHITE); g.clearRect(0, 0, ANCHO_ETIQUETA, ALTO_ETIQUETA); g.setColor(Color.BLACK); g.setStroke(new BasicStroke(2f)); // Pintamos la caja de borde g.draw(new java.awt.Rectangle(MARGEN_CAJA, MARGEN_CAJA, ANCHO_ETIQUETA - MARGEN_CAJA * 2, ALTO_ETIQUETA - MARGEN_CAJA * 2)); g.draw(new java.awt.Rectangle(MARGEN_CAJA + 3, MARGEN_CAJA + 3, ANCHO_ETIQUETA - MARGEN_CAJA * 2 - 6, ALTO_ETIQUETA - MARGEN_CAJA * 2 - 6)); // Generamos el cdigo QR Qrcode x = new Qrcode(); x.setQrcodeErrorCorrect('L'); x.setQrcodeEncodeMode('B'); // Modo Binario byte[] d = textoQR.getBytes(); // Generamos el cdigo QR boolean[][] s = x.calQrcode(d); for (int i = 0; i < s.length; i++) { for (int j = 0; j < s.length; j++) { if (s[j][i]) { g.fillRect(j * SIZE_QR + MARGEN, i * SIZE_QR + MARGEN, SIZE_QR, SIZE_QR); } } } int marjenSeparador = MARGEN + SIZE_QR * s.length + MARGEN_CAJA; int marjenTexto = marjenSeparador + MARGEN_CAJA; // Linea de separacin entre el QR cdigo y el texto g.drawLine(marjenSeparador - 3, MARGEN_CAJA + 3, marjenSeparador - 3, ALTO_ETIQUETA - MARGEN_CAJA - 3); g.drawLine(marjenSeparador, MARGEN_CAJA + 3, marjenSeparador, ALTO_ETIQUETA - MARGEN_CAJA - 3); // Linea de separacin entre texto y cdigo de barras. int marjenCodigoBarras = MARGEN + MAX_ROWS * FONT_SIZE; // Pintamos una pequea linea de separacin g.drawLine(marjenSeparador, marjenCodigoBarras, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras); g.drawLine(marjenSeparador, marjenCodigoBarras - 3, ANCHO_ETIQUETA - MARGEN_CAJA - 3, marjenCodigoBarras - 3); // Escribimos el texto List<String> parrafos = split(text); g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE)); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (int i = 0; i < parrafos.size(); i++) { String linea = parrafos.get(i); // Pintamos la nueva linea de texto g.drawString(linea, marjenTexto, MARGEN + 3 + (FONT_SIZE * i + 1)); } g.setFont(new Font(g.getFont().getName(), Font.BOLD, FONT_SIZE - 4)); // Pintamos el texto final de una sola lnea( Generalmente el MD5 ) //if(url.length()) if (!url.equals("")) { g.drawString("Custodia del documento: ", marjenTexto, marjenCodigoBarras - 10 * 2); g.drawString(url, marjenTexto, marjenCodigoBarras - 6); } marjenCodigoBarras += MARGEN_CAJA; // Generamos el cdigo de barras try { // int marjenCodigoBarras=MARGEN+MAX_ROWS*FONT_SIZE; BarcodeFactory.createCode39(codFirma, true).draw(g, marjenTexto, marjenCodigoBarras); } catch (Exception e1) { // TODO e1.printStackTrace(); } // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_OFF); // Finalizamos la superficie de dibujo g.dispose(); ByteArrayOutputStream out = new ByteArrayOutputStream(); // Generamos la imagen try { ImageIO.write(imagenQR, "png", out); // ImageIO.write(imagenQR, "png", new // FileOutputStream("/tmp/imagen.png")); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } return out.toByteArray(); }
From source file:swift.selenium.WebHelper.java
/** * This function embosses the message on the screenshot * @param imageFilePath/*from w ww . j a v a 2s .co m*/ * @param text * @param textPosition * @return * @throws IOException */ public static byte[] mergeImageAndText(String imageFilePath, String text, Point textPosition) throws IOException { BufferedImage im = ImageIO.read(new File(imageFilePath)); Graphics2D g2 = im.createGraphics(); g2.setColor(Color.RED); g2.setBackground(Color.WHITE); g2.drawString(text, textPosition.x, textPosition.y); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(im, "PNG", baos); return baos.toByteArray(); }
From source file:tests.TestDrawing.java
@Test public void testDrawing() { BufferedImage img = null;/*from w w w.j av a 2s. c o m*/ BufferedImage imgs[] = new BufferedImage[2]; try { imgs[0] = ImageIO.read(new File("../captures/4.jpg")); // eventually C:\\ImageTest\\pic2.jpg imgs[1] = ImageIO.read(new File("../captures/5.jpg")); // eventually C:\\ImageTest\\pic2.jpg img = ImageIO.read(new File("../captures/5.jpg")); // eventually C:\\ImageTest\\pic2.jpg for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { int rgbDiff = RgbCalculator.absoluteDifference(imgs[0].getRGB(x, y), imgs[1].getRGB(x, y)); img.setRGB(x, y, rgbDiff); } } Graphics2D g2d = img.createGraphics(); g2d.setBackground(Color.BLUE); g2d.setColor(Color.RED); Vector3D[] corners = new Vector3D[] { new Vector3D(new double[] { 172, 78, 0 }), new Vector3D(new double[] { 455, 71, 0 }), new Vector3D(new double[] { 507, 350, 0 }), new Vector3D(new double[] { 143, 362, 0 }) }; //draw lines from corner to corner for (int c = 0; c < corners.length; c++) { Vector3D v1 = corners[c]; Vector3D v2 = corners[(c + 1) % corners.length]; g2d.drawLine((int) v1.getX(), (int) v1.getY(), (int) v2.getX(), (int) v2.getY()); } for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { Vector3D currentPos = new Vector3D(new double[] { x, y, 0 }); double[] normalizedCoordinates = new double[2]; { //normalize x coordinate Line floor = new Line(corners[0], corners[3], 0.5); Line roof = new Line(corners[1], corners[2], 0.5); double floorDistance = floor.distance(currentPos) * 1 / corners[0].distance(corners[3]); double roofDistance = roof.distance(currentPos) * 1 / corners[1].distance(corners[2]); normalizedCoordinates[0] = interpolate(0, 1, floorDistance / (floorDistance + roofDistance)); } { //normalize y coordinate Line floor = new Line(corners[0], corners[1], 0.5); Line roof = new Line(corners[2], corners[3], 0.5); double floorDistance = floor.distance(currentPos) * 1 / corners[0].distance(corners[1]); double roofDistance = roof.distance(currentPos) * 1 / corners[2].distance(corners[3]); normalizedCoordinates[1] = interpolate(0, 1, floorDistance / (floorDistance + roofDistance)); } boolean isEdge = false; for (int d = 0; d < 2; d++) { double val = normalizedCoordinates[d]; if (Math.abs((double) ((int) (val * 8)) - (val * 8)) < 0.05) { isEdge = true; } } if (isEdge) { //color corners red: img.setRGB(x, y, Color.RED.getRGB()); } } } JFrame dialog = new JFrame(); ImagePanel imagePanel = new ImagePanel(img); dialog.add(imagePanel); imagePanel.setSize(100, 100); dialog.pack(); dialog.setSize(300, 300); dialog.setVisible(true); } catch (IOException e) { throw new RuntimeException(e); } assertTrue("hello", true); }
From source file:ubic.basecode.graphics.MatrixDisplay.java
/** * @param outPngFilename String/*from ww w. j av a 2 s. c om*/ * @param showLabels boolean * @param standardize normalize to deviation 1, mean 0. FIXME this is not used? * @throws IOException */ public void saveImage(ColorMatrix<R, C> matrix, String outPngFilename, boolean showLabels, boolean showScalebar, boolean standardize) throws java.io.IOException { Graphics2D g = null; // Include row and column labels? boolean wereLabelsShown = m_isShowLabels; if (!wereLabelsShown) { // Labels aren't visible, so make them visible setLabelsVisible(true); initSize(); } // Draw the image to a buffer Dimension d = computeSize(showLabels, showScalebar); // how big is the image with row and // column labels BufferedImage m_image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB); g = m_image.createGraphics(); g.setBackground(Color.white); g.clearRect(0, 0, d.width, d.height); drawMatrix(matrix, g, showLabels, showScalebar); if (showLabels) { drawRowNames(g, showScalebar); drawColumnNames(g, showScalebar); } if (showScalebar) { drawScaleBar(g, d, matrix.getDisplayMin(), matrix.getDisplayMax()); } // Write the image to a png file ImageIO.write(m_image, "png", new File(outPngFilename)); // Restore state: make the image as it was before if (!wereLabelsShown) { // Labels weren't visible to begin with, so hide them setLabelsVisible(false); initSize(); } }
From source file:ubic.basecode.graphics.MatrixDisplay.java
/** * @param matrix/*from w w w . j a v a 2 s . c om*/ * @param stream * @param showLabels * @param showScalebar */ public void writeToPng(ColorMatrix<R, C> matrix, OutputStream stream, boolean showLabels, boolean showScalebar) throws IOException { // Draw the image to a buffer boolean oldLabelSate = this.m_isShowLabels; if (!oldLabelSate) { this.setLabelsVisible(true); } Dimension d = computeSize(showLabels, showScalebar); BufferedImage m_image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB); Graphics2D g = m_image.createGraphics(); g.setBackground(Color.white); g.clearRect(0, 0, d.width, d.height); drawMatrix(matrix, g, showLabels, showScalebar); if (showLabels) { drawRowNames(g, showScalebar); drawColumnNames(g, showScalebar); } if (showScalebar) { drawScaleBar(g, d, matrix.getDisplayMin(), matrix.getDisplayMax()); } // Write the buffered image to the output steam. ImageIO.write(m_image, "png", stream); this.setLabelsVisible(oldLabelSate); }
From source file:web.diva.server.model.GroupColorUtil.java
public synchronized String getImageColor(String hashColor, String path, String colName) { try {// w w w .j av a 2s . c o m Color color = hex2Rgb(hashColor); BufferedImage image = new BufferedImage(8, 9, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.setBackground(color); graphics.setColor(color); graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); File f = new File(path, colName + ".png"); if (!f.exists()) { f.createNewFile(); } ImageIO.write(image, "PNG", f); // Reading a Image file from file system FileInputStream imageInFile = new FileInputStream(f); byte imageData[] = new byte[(int) f.length()]; imageInFile.read(imageData); String base64 = Base64.encodeBase64String(imageData); base64 = "data:image/png;base64," + base64; return base64; } catch (IOException ioexp) { System.err.println(ioexp.getMessage()); } return null; }