Example usage for java.awt Graphics2D clearRect

List of usage examples for java.awt Graphics2D clearRect

Introduction

In this page you can find the example usage for java.awt Graphics2D clearRect.

Prototype

public abstract void clearRect(int x, int y, int width, int height);

Source Link

Document

Clears the specified rectangle by filling it with the background color of the current drawing surface.

Usage

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   w w  w .j  av  a  2 s . c  o m*/
    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 a  2s.  c o  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.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//w  w  w .  j a  va  2  s .c o m
 */
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.encuestame.business.images.ImageThumbnailGeneratorImpl.java

/**
 * Create a thumbnail image and save it to disk.
 *
 * This algorithm is based on://from   w  w w . ja va  2 s .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 ww  w  . j av  a  2 s .c o m*/
    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.openpnp.machine.reference.camera.TableScannerCamera.java

private void renderBuffer() {
    // determine where in the map the center tile is
    int centerTileX = lastCenterTile.getTileX();
    int centerTileY = lastCenterTile.getTileY();

    Graphics2D g = (Graphics2D) buffer.getGraphics();
    g.setColor(Color.black);//ww w .  j a  v  a2s. c  o m
    g.clearRect(0, 0, buffer.getWidth(), buffer.getHeight());
    g.setColor(Color.white);

    /*
     * Render the tiles into the buffer. Our goal is to render an area that
     * is tilesWide x tilesHigh with the center tile in the middle. Any
     * locations that fall outside of the tiles array are not rendered and
     * as such are left black.
     */
    for (int x = 0; x < tilesWide; x++) {
        for (int y = 0; y < tilesHigh; y++) {
            /*
             * We multiply everything by two here because the TableScanner
             * takes two images per width of the camera. By doing this
             * we increase the effective resolution of this image because
             * decrease the distance between tiles.
             * TODO: This should be made configurable.
             */
            int tileX = centerTileX - (2 * (tilesWide / 2)) + (2 * x);
            int tileY = centerTileY - (2 * (tilesHigh / 2)) + (2 * y);
            // If the position is within the array's bounds we'll render it.
            if (tileX >= 0 && tileX < tiles.length && tileY >= 0 && tileY < tiles[tileX].length
                    && tiles[tileX][tileY] != null) {
                Tile tile = tiles[tileX][tileY];
                BufferedImage image = tile.getImage();

                /*
                 * The source images are flipped in both dimensions, and
                 * we're rendering the local array from top to bottom
                 * instead of bottom to top, so we have to flip the images
                 * and then render right to left, bottom to top.
                 */
                int dx1 = image.getWidth() * x;
                int dy1 = image.getHeight() * (tilesHigh - y) - image.getHeight();
                int dx2 = image.getWidth() * x + image.getWidth();
                int dy2 = image.getHeight() * (tilesHigh - y);

                int sx1 = image.getWidth();
                int sy1 = image.getHeight();
                int sx2 = 0;
                int sy2 = 0;

                g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
            }
        }
    }

    g.dispose();
}

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;/*  w  ww. ja  va2  s  .c om*/
    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.squidy.designer.zoom.NavigationShape.java

@Override
protected void paintShapeZoomedIn(PPaintContext paintContext) {
    super.paintShapeZoomedIn(paintContext);

    Graphics2D g = (Graphics2D) paintContext.getGraphics();

    if (showNavigation) {// && !isHierarchicalZoomInProgress()) {

        PBounds bounds = getBoundsReference();

        int x = (int) bounds.getX();
        int y = (int) bounds.getY();
        int width = (int) bounds.getWidth();
        int height = (int) bounds.getHeight();

        g.setColor(Constants.Color.COLOR_SHAPE_BACKGROUND);
        if (isRenderPrimitiveRect())
            g.fillRect(x, y, width, 60);
        else {//from   w  w  w  .ja  v  a2  s.  c o m
            g.clearRect(x, y, width, 60);
            g.fillRoundRect(x, y, width, 60, 25, 25);
        }

        g.setColor(Constants.Color.COLOR_SHAPE_BORDER);
        if (isRenderPrimitiveRect())
            g.drawRect(x, y, width, 60);
        else
            g.drawRoundRect(x, y, width, 60, 25, 25);

        g.setFont(fontBreadcrumb);

        if (titleBounds == null) {
            FontMetrics fm = g.getFontMetrics();
            titleBounds = new Rectangle2D.Double(bounds.getX() + 455 + titleGap,
                    bounds.getY() + 25 - fm.getHeight(), FontUtils.getWidthOfText(fm, getTitle()) + 10,
                    fm.getHeight() + 5);
        }

        // Font font = internalFont.deriveFont(3.2f);
        for (int i = 0; i < 3; i++) {
            if (isRenderPrimitiveRect())
                g.fillRect((int) (bounds.getX() + 430), (int) bounds.getY() + i * 15 + 10, 5, 10);
            else
                g.fillOval((int) (bounds.getX() + 430), (int) bounds.getY() + i * 15 + 10, 5, 10);
        }

        if (!ShapeUtils.isApparent(titleInputWrapper)) {
            g.drawString(getTitle(), (int) (bounds.getX() + 460 + titleGap), (int) (bounds.getY() + 25));
        }

        if (croppedBreadcrumb == null) {
            croppedBreadcrumb = FontUtils.createCroppedLabelIfNecessary(g.getFontMetrics(), getBreadcrumb(),
                    (int) bounds.getWidth() * 10 - 450);
        }
        g.drawString(croppedBreadcrumb, (int) (bounds.getX() + 460), (int) (bounds.getY() + 50));
    }
}

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.
 * //w ww.  j  av a2s .c om
 * @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:ubic.basecode.graphics.MatrixDisplay.java

/**
 * @param outPngFilename String//  ww  w  . j  a v a 2s. c  o m
 * @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();
    }
}