Example usage for java.awt Graphics2D setColor

List of usage examples for java.awt Graphics2D setColor

Introduction

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

Prototype

public abstract void setColor(Color c);

Source Link

Document

Sets this graphics context's current color to the specified color.

Usage

From source file:Filter3dTest.java

public void draw(Graphics2D g) {

    // draw background
    g.setColor(new Color(0x33cc33));
    g.fillRect(0, 0, screen.getWidth(), screen.getHeight());

    // draw listener
    g.drawImage(listener.getImage(), Math.round(listener.getX()), Math.round(listener.getY()), null);

    // draw fly/*from www  . j a v a2 s  .  c  o m*/
    g.drawImage(fly.getImage(), Math.round(fly.getX()), Math.round(fly.getY()), null);
}

From source file:be.fedict.eidviewer.gui.printing.IDPrintout.java

public int print(Graphics graphics, PageFormat pageFormat, int pageNumber) throws PrinterException {
    // we only support printing all in one single page
    if (pageNumber > 0)
        return Printable.NO_SUCH_PAGE;

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("width", pageFormat.getWidth()).append("height", pageFormat.getHeight())
            .append("imageableWidth", pageFormat.getImageableWidth())
            .append("imageableHeight", pageFormat.getImageableHeight())
            .append("imageableX", pageFormat.getImageableX()).append("imageableY", pageFormat.getImageableY())
            .append("orientation", pageFormat.getOrientation())
            .append("paper.width", pageFormat.getPaper().getWidth())
            .append("paper.height", pageFormat.getPaper().getHeight())
            .append("paper.imageableWidth", pageFormat.getPaper().getImageableWidth())
            .append("paper.imageableHeight", pageFormat.getPaper().getImageableHeight())
            .append("paper.imageableX", pageFormat.getPaper().getImageableX())
            .append("paper.imageableY", pageFormat.getPaper().getImageableY()).toString());

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("clip.width", graphics.getClipBounds().width)
            .append("clip.height", graphics.getClipBounds().height).append("clip.x", graphics.getClipBounds().x)
            .append("clip.y", graphics.getClipBounds().y).toString());

    // translate graphics2D with origin at top left first imageable location
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

    // keep imageable width and height as variables for clarity (we use them often)
    float imageableWidth = (float) pageFormat.getImageableWidth();
    float imageableHeight = (float) pageFormat.getImageableHeight();

    // Coat of Arms images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform coatOfArmsTransform = new AffineTransform();
    coatOfArmsTransform.scale(0.5, 0.5);

    // photo images are stored at approx 36 DPI, scale 1/2 to get to Java default of 72DPI
    AffineTransform photoTransform = new AffineTransform();
    photoTransform.scale(0.5, 0.5);//from   w ww.  j  av a 2 s.  com
    photoTransform.translate((imageableWidth * 2) - (photo.getWidth(this)), 0);

    // make sure foreground is black, and draw coat of Arms and photo at the top of the page
    // using the transforms to scale them to 72DPI.
    graphics2D.setColor(Color.BLACK);
    graphics2D.drawImage(coatOfArms, coatOfArmsTransform, null);
    graphics2D.drawImage(photo, photoTransform, null);

    // calculate some sizes that need to take into account the scaling of the graphics, to avoid dragging
    // those non-intuitive "/2" further along in the code.
    float headerHeight = (float) (coatOfArms.getHeight(this)) / 2;
    float coatOfArmsWidth = (float) (coatOfArms.getWidth(this)) / 2;
    float photoWidth = (float) (photo.getWidth(this)) / 2;
    float headerSpaceBetweenImages = imageableWidth
            - (coatOfArmsWidth + photoWidth + (SPACE_BETWEEN_ITEMS * 2));

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("headerHeight", headerHeight)
            .append("coatOfArmsWidth", coatOfArmsWidth).append("photoWidth", photoWidth)
            .append("headerSpaceBetweenImages", headerSpaceBetweenImages).toString());

    // get localised strings for card type. We'll take a new line every time a ";" is found in the resource
    String[] cardTypeStr = (bundle.getString("type_" + this.identity.getDocumentType().toString())
            .toUpperCase()).split(";");

    // if a "mention" is present, append it so it appears below the card type string, between brackets

    if (identity.getSpecialOrganisation() != SpecialOrganisation.UNSPECIFIED) {
        String mention = TextFormatHelper.getSpecialOrganisationString(bundle,
                identity.getSpecialOrganisation());
        if (mention != null && !mention.isEmpty()) {
            String[] cardTypeWithMention = new String[cardTypeStr.length + 1];
            System.arraycopy(cardTypeStr, 0, cardTypeWithMention, 0, cardTypeStr.length);
            cardTypeWithMention[cardTypeStr.length] = "(" + mention + ")";
            cardTypeStr = cardTypeWithMention;
        }
    }

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the card type strings
    // stop when a font size is found where they all fit the space between the graphics in an orderly manner
    boolean sizeFound = false;
    int fontSize;
    for (fontSize = TITLE_MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        sizeFound = (ImageUtilities.getTotalStringWidth(graphics2D, cardTypeStr) < headerSpaceBetweenImages)
                && (ImageUtilities.getTotalStringHeight(graphics2D, cardTypeStr) < headerHeight);
    }

    // unless with extremely small papers, a size should always have been found.
    // draw the card type strings, centered, between the images at the top of the page
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize + 1));
        float cardTypeHeight = cardTypeStr.length * ImageUtilities.getStringHeight(graphics2D);
        float cardTypeBaseLine = ((headerHeight - cardTypeHeight) / 2) + ImageUtilities.getAscent(graphics2D);
        float cardTypeLineHeight = ImageUtilities.getStringHeight(graphics2D);

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
                .append("cardTypeHeight", cardTypeHeight).append("cardTypeBaseLine", cardTypeBaseLine)
                .append("cardTypeLineHeight", cardTypeLineHeight).toString());

        for (int i = 0; i < cardTypeStr.length; i++) {
            float left = (coatOfArmsWidth + SPACE_BETWEEN_ITEMS
                    + (headerSpaceBetweenImages - ImageUtilities.getStringWidth(graphics2D, cardTypeStr[i]))
                            / 2);
            float leading = (float) cardTypeLineHeight * i;
            graphics2D.drawString(cardTypeStr[i], left, cardTypeBaseLine + leading);
        }
    }

    // populate idAttributes with all the information from identity and address
    // as well as date printed and some separators
    List<IdentityAttribute> idAttributes = populateAttributeList();

    // draw a horizontal line just below the header (images + card type titles)
    graphics2D.drawLine(0, (int) headerHeight, (int) imageableWidth, (int) headerHeight);

    // calculate how much space is left between the header and the bottom of the imageable area

    headerHeight += 32; // take some distance from header

    float imageableDataHeight = imageableHeight - headerHeight;
    float totalDataWidth = 0, totalDataHeight = 0;
    float labelWidth, widestLabelWidth = 0;
    float valueWidth, widestValueWidth = 0;

    // iterate from MAXIMAL_FONT_SIZE, calculating how much space would be required to fit the information in idAttributes into
    // the space between the header and the bottom of the imageable area
    // stop when a font size is found where it all fits in an orderly manner
    sizeFound = false;
    for (fontSize = MAXIMAL_FONT_SIZE; (fontSize >= MINIMAL_FONT_SIZE) && (!sizeFound); fontSize--) // count down slowly until we find one that fits nicely
    {
        logger.log(Level.FINE, "fontSize=" + fontSize + " sizeFound=" + sizeFound);
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));

        widestLabelWidth = 0;
        widestValueWidth = 0;

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute == SEPARATOR)
                continue;

            labelWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getLabel());
            valueWidth = ImageUtilities.getStringWidth(graphics2D, attribute.getValue());
            if (labelWidth > widestLabelWidth)
                widestLabelWidth = labelWidth;
            if (valueWidth > widestValueWidth)
                widestValueWidth = valueWidth;
        }

        totalDataWidth = widestLabelWidth + SPACE_BETWEEN_ITEMS + widestValueWidth;
        totalDataHeight = ImageUtilities.getStringHeight(graphics2D)
                + (ImageUtilities.getStringHeight(graphics2D) * idAttributes.size());

        if ((totalDataWidth < imageableWidth) && (totalDataHeight < imageableDataHeight))
            sizeFound = true;
    }

    logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("widestLabelWidth", widestLabelWidth).append("widestValueWidth", widestValueWidth)
            .append("totalDataWidth", totalDataWidth).append("totalDataHeight", totalDataHeight).toString());

    // unless with extremely small papers, a size should always have been found.
    // draw the identity, addess and date printed information, in 2 columns, centered inside the
    // space between the header and the bottom of the imageable area
    if (sizeFound) {
        graphics2D.setFont(new Font(FONT, Font.PLAIN, fontSize));
        float labelsLeft = (imageableWidth - totalDataWidth) / 2;
        float valuesLeft = labelsLeft + widestLabelWidth + SPACE_BETWEEN_ITEMS;
        float dataLineHeight = ImageUtilities.getStringHeight(graphics2D);
        float dataTop = dataLineHeight + headerHeight + ((imageableDataHeight - totalDataHeight) / 2);
        float lineNumber = 0;

        logger.finest(new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("labelsLeft", labelsLeft)
                .append("valuesLeft", valuesLeft).append("dataLineHeight", dataLineHeight)
                .append("dataTop", dataTop).toString());

        for (IdentityAttribute attribute : idAttributes) {
            if (attribute != SEPARATOR) // data
            {
                graphics2D.setColor(attribute.isRelevant() ? Color.BLACK : Color.LIGHT_GRAY);
                graphics2D.drawString(attribute.getLabel(), labelsLeft,
                        dataTop + (lineNumber * dataLineHeight));
                graphics2D.drawString(attribute.getValue(), valuesLeft,
                        dataTop + (lineNumber * dataLineHeight));
            } else // separator
            {
                int y = (int) (((dataTop + (lineNumber * dataLineHeight) + (dataLineHeight / 2)))
                        - ImageUtilities.getAscent(graphics2D));
                graphics2D.setColor(Color.BLACK);
                graphics2D.drawLine((int) labelsLeft, y, (int) (labelsLeft + totalDataWidth), y);
            }
            lineNumber++;
        }
    }

    // tell Java printing that all this makes for a page worth printing :-)
    return Printable.PAGE_EXISTS;
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * Renders this image//  w w w  .j  a  v  a2  s.  co m
 * 
 * @return The image data
 */
private final byte[] render() throws IOException {
    Graphics2D gfx = (Graphics2D) this.image.getGraphics();
    if (config.isFontAntialiasing())
        gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int curWidth = config.getTextMarginLeft();
    FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false);
    for (int i = 0; i < charAttsList.size(); i++) {
        CharAttributes cf = (CharAttributes) charAttsList.get(i);
        TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext());
        AffineTransform textAt = new AffineTransform();
        textAt.translate(curWidth, this.height - cf.getRise());
        if (cf.getRotation() != 0) {
            textAt.rotate(cf.getRotation());
        }
        if (cf.getShearX() > 0.0)
            textAt.shear(cf.getShearX(), cf.getShearY());
        Shape shape = text.getOutline(textAt);
        curWidth += shape.getBounds().getWidth() + config.getTextSpacing();
        if (config.isUseImageBackground())
            gfx.setColor(Color.BLACK);
        else
            gfx.setXORMode(Color.BLACK);
        gfx.fill(shape);
    }
    if (config.isEffectsNoise()) {
        noiseEffects(gfx, image);
    }
    if (config.isUseTimestamp()) {
        if (config.isEffectsNoise())
            gfx.setColor(Color.WHITE);
        else
            gfx.setColor(Color.BLACK);

        TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ());
        Calendar cal = new GregorianCalendar(tz);
        SimpleDateFormat formatter;
        if (config.isUseTimestamp24hr())
            formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        else
            formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z");
        formatter.setTimeZone(tz);
        Font font = gfx.getFont();
        Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize());
        gfx.setFont(newFont);
        gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1);
    }

    return toImageData(image);
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

protected void paintComponent(Graphics g) {

    // prepare graphic object
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // set clipping area
    if (is_printing) {
        g2d.translate(-draw_area.x, -draw_area.y);
        g2d.setClip(draw_area);//from   w w  w . ja va 2s .  c o  m
    }

    //paint canvas background
    if (!is_printing) {
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
    }

    // paint white background on drawing area    
    g2d.setColor(Color.white);
    g2d.fillRect(draw_area.x, draw_area.y, draw_area.width, draw_area.height);
    if (!is_printing) {
        g2d.setColor(Color.black);
        g2d.draw(draw_area);
    }

    // paint
    paintChart(g2d);
    paintAnnotations(g2d);

    // dispose graphic object
    g2d.dispose();

    if (!is_printing) {
        if (first_time) {
            if (first_time_init_pos)
                placeStructures(true);
            else
                theDocument.fireDocumentInit();
            first_time = false;
        } else
            revalidate();
    }

}

From source file:com.esri.ArcGISController.java

private void drawCells(final Graphics2D graphics, final int imageWidth, final int imageHeight,
        final double xmin, final double ymin, final double xdel, final double ydel, final Range range,
        final int[] ramp, final Set<Map.Entry<Long, Double>> set) {
    final int cellPixel = Math.max(1, (int) Math.ceil(imageWidth * m_cell / xdel));
    final int cellPixel2 = cellPixel / 2;

    final Color[] colors = new Color[256];

    for (final Map.Entry<Long, Double> entry : set) {
        final long key = entry.getKey();
        final double val = Math.min(range.hi, entry.getValue());

        if (val < range.lo) {
            continue;
        }/*from www.j av  a 2 s  . c om*/

        final long cx = key & 0x7FFFL;
        final long cy = (key >> 16) & 0x7FFFL;
        final double wx = toWorld(cx, m_xofs, m_cell);
        final double wy = toWorld(cy, m_yofs, m_cell);
        final int px = toPixel(wx, imageWidth, xmin, xdel) - cellPixel2;
        final int py = imageHeight - toPixel(wy, imageHeight, ymin, ydel) - cellPixel2;

        final Color color = toColor(val, range, ramp, colors); // TODO - Create interface to handle zero range.dd

        graphics.setColor(color);
        graphics.fillRect(px, py, cellPixel, cellPixel);
    }

    // graphics.setColor(Color.RED);
    // graphics.drawRect(0, 0, imageWidth - 1, imageHeight - 1);
}

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);/* w  ww .  j  av a2 s.com*/
    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.codename1.android.AndroidLayoutImporter.java

private EncodedImage createBlankImage(String widthStr, String heightStr) {
    String name = "BlankImage";
    int width = convertToPixels(widthStr);
    if (width < 1)
        width = 1;//www  . j a v  a2  s.  c om
    int height = convertToPixels(heightStr);
    if (height < 1) {
        height = 1;
    }
    //System.out.println("Creating blank image "+width+"x"+height+" for "+widthStr+"x"+heightStr);
    String imgName = name + width + "x" + height + ".png";
    Image im = outputResources.getImage(imgName);
    if (im != null) {
        if (im instanceof EncodedImage) {
            return (EncodedImage) im;
        } else {
            return EncodedImage.createFromImage(im, false);
        }
    }
    BufferedImage center = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) center.createGraphics();
    //g2.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
    g2.setColor(Color.red);
    g2.fillRect(0, 0, width, height);
    g2.dispose();

    EncodedImage placeholder = EncodedImage.create(toPng(center));

    EditableResources.MultiImage multiImage = new EditableResources.MultiImage();
    multiImage.setDpi(new int[] { Display.DENSITY_MEDIUM });
    multiImage.setInternalImages(new EncodedImage[] { placeholder });

    outputResources.setMultiImage(imgName, multiImage);
    return multiImage.getBest();
}

From source file:com.joey.software.regionSelectionToolkit.controlers.ImageProfileToolDynamicRangePanel.java

@Override
public void draw(Graphics2D g) {

    updateSelectionData();//from  w ww .  ja  va2 s  .c o  m

    float tra = (transparance.getValue() / (float) (transparance.getMaximum()));

    Composite oldcomp = g.getComposite();
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tra));
    Line2D.Double line = new Line2D.Double();
    for (int i = 0; i < selectionData.length - 1; i++) {
        double x1 = view.getImage().getImage().getWidth() / (double) (selectionData.length - 1) * i;
        double y1 = view.getImage().getImage().getHeight() * (1 - getSelectionValue(i));

        double x2 = view.getImage().getImage().getWidth() / (double) (selectionData.length - 1) * (i + 1);
        double y2 = view.getImage().getImage().getHeight() * (1 - getSelectionValue(i + 1));

        if (getUseData(i)) {
            g.setColor(getPointColorSelected());
        } else {
            g.setColor(getPointColorNotSelected());
        }
        line.x1 = x1;
        line.x2 = x2;
        line.y1 = y1;
        line.y2 = y2;

        g.draw(line);

        if (showOffset.isSelected()) {
            if (getUseData(i)) {
                g.setColor(getOffsetColor());
                double offset = (Double) this.offset.getValue();
                line.y1 += offset;
                line.y2 += offset;
                g.draw(line);
            }
        }
    }

    // Draw each point

    for (int i = 0; i < value.length; i++) {
        g.setColor(getCrossColor());
        double x = view.getImage().getImage().getWidth() / (double) (value.length - 1) * i;
        double y = view.getImage().getImage().getHeight() * (1 - value[i]);
        DrawTools.drawCross(g, new Point2D.Double(x, y), pointSize * 2);

    }

    g.setComposite(oldcomp);
}

From source file:edu.umn.cs.spatialHadoop.operations.Plot.java

/**
 * Plots a Geometry from the library JTS into the given image.
 * @param graphics/*from   ww w .j  a va 2s.c  o  m*/
 * @param geom
 * @param fileMbr
 * @param imageWidth
 * @param imageHeight
 * @param scale
 * @param shape_color
 */
private static void drawJTSShape(Graphics2D graphics, Geometry geom, Rectangle fileMbr, int imageWidth,
        int imageHeight, double scale, Color shape_color) {
    if (geom instanceof GeometryCollection) {
        GeometryCollection geom_coll = (GeometryCollection) geom;
        for (int i = 0; i < geom_coll.getNumGeometries(); i++) {
            Geometry sub_geom = geom_coll.getGeometryN(i);
            // Recursive call to draw each geometry
            drawJTSShape(graphics, sub_geom, fileMbr, imageWidth, imageHeight, scale, shape_color);
        }
    } else if (geom instanceof com.vividsolutions.jts.geom.Polygon) {
        com.vividsolutions.jts.geom.Polygon poly = (com.vividsolutions.jts.geom.Polygon) geom;

        for (int i = 0; i < poly.getNumInteriorRing(); i++) {
            LineString ring = poly.getInteriorRingN(i);
            drawJTSShape(graphics, ring, fileMbr, imageWidth, imageHeight, scale, shape_color);
        }

        drawJTSShape(graphics, poly.getExteriorRing(), fileMbr, imageWidth, imageHeight, scale, shape_color);
    } else if (geom instanceof LineString) {
        LineString line = (LineString) geom;
        double geom_alpha = line.getLength() * scale;
        int color_alpha = geom_alpha > 1.0 ? 255 : (int) Math.round(geom_alpha * 255);
        if (color_alpha == 0)
            return;

        int[] xpoints = new int[line.getNumPoints()];
        int[] ypoints = new int[line.getNumPoints()];

        for (int i = 0; i < xpoints.length; i++) {
            double px = line.getPointN(i).getX();
            double py = line.getPointN(i).getY();

            // Transform a point in the polygon to image coordinates
            xpoints[i] = (int) Math.round((px - fileMbr.x1) * imageWidth / (fileMbr.x2 - fileMbr.x1));
            ypoints[i] = (int) Math.round((py - fileMbr.y1) * imageHeight / (fileMbr.y2 - fileMbr.y1));
        }

        // Draw the polygon
        graphics.setColor(new Color((shape_color.getRGB() & 0x00FFFFFF) | (color_alpha << 24), true));
        graphics.drawPolyline(xpoints, ypoints, xpoints.length);
    }
}

From source file:com.us.servlet.AuthCode.java

protected void service(HttpServletRequest request, HttpServletResponse response) {
    final CodeAuth bean = AppHelper.CODE_AUTH;
    int width = NumberUtils.toInt(request.getParameter("width"), bean.getWidth());
    int height = NumberUtils.toInt(request.getParameter("height"), bean.getHeight());
    int x = width / (bean.getLength() + 1);
    int codeY = height - 4;
    int fontHeight = height - 2;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics2D graphics = image.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    if (StringUtil.hasText(request.getParameter("bgcolor"))) {
        graphics.setBackground(ColorHelper.hex2RGB(request.getParameter("bgcolor")));
    }/*  w w  w.j  ava 2s  .c o  m*/
    graphics.fillRect(0, 0, width, height);
    graphics.setFont(new Font(bean.getFont(), Font.BOLD, fontHeight));
    graphics.drawRect(0, 0, width - 1, height - 1);
    // 
    if (bean.isBreakLine()) {
        for (int i = 0; i < 15; i++) {
            int x1 = RandomUtils.nextInt(width);
            int y1 = RandomUtils.nextInt(height);
            int x2 = RandomUtils.nextInt(12);
            int y2 = RandomUtils.nextInt(12);
            graphics.drawLine(x1, y1, x + x2, y1 + y2);
        }
    }
    char[] CHARSET_AREA = null;
    if (bean.getType().charAt(0) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS);
    }
    if (bean.getType().charAt(1) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER);
    }
    if (bean.getType().charAt(2) == '1') {
        CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS);
    }
    StringBuilder randomCode = new StringBuilder();
    for (int i = 0; i < bean.getLength(); i++) {
        String rand = String.valueOf(CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)]);
        graphics.setColor(ColorHelper.color(RandomUtils.nextInt(255), RandomUtils.nextInt(255),
                RandomUtils.nextInt(255)));
        graphics.drawString(rand, (i + 1) * x, codeY);
        randomCode.append(rand);
    }
    HttpSession session = request.getSession();
    session.setAttribute(bean.getSessionKey(), randomCode.toString());
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/png");
    try {
        // Servlet?
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "png", sos);
        sos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}