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:com.shending.support.CompressPic.java

/**
 * ?/*  ww  w .  java2  s .c  o  m*/
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:SplashScreenTest.java

private static void drawOnSplash(int percent) {
    Rectangle bounds = splash.getBounds();
    Graphics2D g = splash.createGraphics();
    int height = 20;
    int x = 2;//www.jav a  2  s .  c  om
    int y = bounds.height - height - 2;
    int width = bounds.width - 4;
    Color brightPurple = new Color(76, 36, 121);
    g.setColor(brightPurple);
    g.fillRect(x, y, width * percent / 100, height);
    splash.update();
}

From source file:D20140128.ApacheXMLGraphicsTest.EPSExample1.java

/**
 * Creates an EPS file. The contents are painted using a Graphics2D
 * implementation that generates an EPS file.
 *
 * @param outputFile the target file//from w ww.  ja va 2 s  .c o m
 * @throws IOException In case of an I/O error
 */
public static void generateEPSusingJava2D(File outputFile) throws IOException {
    OutputStream out = new java.io.FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    try {
        //Instantiate the EPSDocumentGraphics2D instance
        EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
        g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

        //Set up the document size
        g2d.setupDocument(out, 400, 200); //400pt x 200pt

        //Paint a bounding box
        g2d.drawRect(0, 0, 400, 200);

        //A few rectangles rotated and with different color
        Graphics2D copy = (Graphics2D) g2d.create();
        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(70, 90, 50, 50);
            copy.rotate(-2 * Math.PI / (double) c, 70, 90);
        }
        copy.dispose();

        //Some text
        g2d.rotate(-0.25);
        g2d.setColor(Color.RED);
        g2d.setFont(new Font("sans-serif", Font.PLAIN, 36));
        g2d.drawString("Hello world!", 140, 140);
        g2d.setColor(Color.RED.darker());
        g2d.setFont(new Font("serif", Font.PLAIN, 36));
        g2d.drawString("Hello world!", 140, 180);

        //Cleanup
        g2d.finish();
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java

/**
 * Loads the given CLP or SVG file and creates a BufferedImage with the given dimensions. As CLP files contain Vector images,
 * they can be scaled to every size needed. The contents are scaled to the given width and height, <b>not</b> preserving any
 * ratio of the image.//from  w w  w.j ava  2s .c o m
 *
 * @param clpFile CLP or SVG file.
 * @param widthPixel The width, in pixels, the resulting image shall have.
 * @param heightPixel The height, in pixels, the resulting image shall have.
 *
 * @return An image displaying the contents of the loaded CLP file.
 *
 * @throws IOException If any I/O related problem occurs reading the file.
 */
public static BufferedImage loadClpFile(File clpFile, int widthPixel, int heightPixel) throws IOException {
    FileInputStream fis = new FileInputStream(clpFile);
    ClpInputStream cis = null;
    InputStream in = clpFile.getName().toLowerCase().endsWith(".clp") ? (cis = new ClpInputStream(fis)) : fis;

    UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
    BridgeContext bridgeContext = new BridgeContext(userAgentAdapter);

    SVGDocument svgDocument;
    GraphicsNode rootSvgNode;
    try {
        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
        svgDocument = (SVGDocument) factory.createDocument(clpFile.toURI().toString(),
                new InputStreamReader(in, "ISO-8859-1"));
        rootSvgNode = getRootNode(svgDocument, bridgeContext);
    } finally {
        IOUtils.closeQuietly(cis);
        IOUtils.closeQuietly(fis);
    }

    float[] vb = ViewBox.parseViewBoxAttribute(svgDocument.getRootElement(),
            svgDocument.getRootElement().getAttribute("viewBox"), bridgeContext);

    AffineTransform usr2dev = ViewBox.getPreserveAspectRatioTransform(vb,
            SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE, true, widthPixel, heightPixel);

    BufferedImage img = new BufferedImage(widthPixel, heightPixel, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();

    g2d.setColor(new Color(0.0f, 0.0f, 0.0f, 0.0f));
    g2d.fillRect(0, 0, widthPixel, heightPixel);
    g2d.transform(usr2dev);

    // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 1
    final Object oldBufferedImage = g2d.getRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE);
    g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference<BufferedImage>(img));
    rootSvgNode.paint(g2d);
    // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 2
    if (oldBufferedImage != null)
        g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, oldBufferedImage);
    else
        g2d.getRenderingHints().remove(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE);

    g2d.dispose();
    return img;
}

From source file:de.codesourcery.planning.swing.DateAxis.java

protected static void debugBoundingBox(BoundingBox box, Graphics2D g) {
    if (DEBUG) {//from   ww w  .j a  v  a2s .com
        Color old = g.getColor();
        g.setColor(Color.RED);
        g.drawRect(box.getX(), box.getY(), box.getWidth(), box.getHeight());
        g.setColor(old);
    }
}

From source file:de.laures.cewolf.util.Renderer.java

/**
 * Renders a legend/* www  .ja v  a  2s  .  co  m*/
 * @param cd the chart iamge to be rendred
 * @return the rendered image
 * @throws CewolfException
 */
private static RenderedImage renderLegend(ChartImage cd, Object c) throws CewolfException {
    try {
        JFreeChart chart = (JFreeChart) c;
        final int width = cd.getWidth();
        final int height = cd.getHeight();
        LegendTitle legend = getLegend(chart);
        boolean haslegend = true;

        // with JFreeChart v0.9.20, the only way to get a valid legend,
        // is either to retrieve it from the chart or to assign a new
        // one to the chart. In the case where the chart has no legend,
        // a new one must be assigned, but just for rendering. After, we
        // have to reset the legend to null in the chart.
        if (null == legend) {
            haslegend = false;
            legend = new LegendTitle(chart.getPlot());
        }
        legend.setPosition(RectangleEdge.BOTTOM);
        BufferedImage bimage = ImageHelper.createImage(width, height);
        Graphics2D g = bimage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        legend.arrange(g, new RectangleConstraint(width, height));
        legend.draw(g, new Rectangle(width, height));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
        param.setQuality(1.0f, true);
        encoder.encode(bimage, param);
        out.close();

        // if the chart had no legend, reset it to null in order to give back the
        // chart in the state we received it.
        if (!haslegend) {
            removeLegend(chart);
        }

        return new RenderedImage(out.toByteArray(), "image/jpeg",
                new ChartRenderingInfo(new StandardEntityCollection()));
    } catch (IOException ioex) {
        log.error(ioex);
        throw new ChartRenderingException(ioex.getMessage(), ioex);
    }
}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static void drawPageState(PageTask pageTask, SourceConfig sourceConfig,
        //SourceDirectoryConfiguration configHandler, 
        int pageIndex, float densityThreshold, FormMaster master, BufferedImage image, int focusedColumnIndex,
        Rectangle scope) throws IOException {

    PageTaskResult pageTaskResult = pageTask.getPageTaskResult();
    PageTaskException pageTaskException = pageTask.getPageTaskException();

    FrameConfig frameConfig = sourceConfig.getFrameConfig();
    DeskewGuideAreaConfig deskewGuideAreaConfig = frameConfig.getDeskewGuideAreaConfig();
    MarkRecognitionConfig markRecognizationConfig = sourceConfig.getMarkRecognitionConfig();

    float headerVerticalMargin = deskewGuideAreaConfig.getHeaderVerticalMargin();
    float footerVerticalMargin = deskewGuideAreaConfig.getFooterVerticalMargin();
    float deskewGuideAreaHeight = deskewGuideAreaConfig.getHeight();
    float deskewGuideAreaHorizontalMargin = deskewGuideAreaConfig.getHeaderVerticalMargin();

    int w = image.getWidth();
    int h = image.getHeight();
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(HEADER_FOOTER_COLOR);
    g.fillRect((int) (w * deskewGuideAreaHorizontalMargin), (int) (h * headerVerticalMargin),
            (int) (w - 2 * w * deskewGuideAreaHorizontalMargin), (int) (h * deskewGuideAreaHeight));
    g.fillRect((int) (w * deskewGuideAreaHorizontalMargin),
            (int) (h - h * (footerVerticalMargin + deskewGuideAreaHeight) - 1),
            (int) (w - 2 * w * deskewGuideAreaHorizontalMargin), (int) (h * deskewGuideAreaHeight));

    if (pageTaskResult != null) {
        Point2D[] corners = pageTaskResult.getDeskewGuideCenterPoints();
        DeskewedImageSource pageSource = drawCorners(master, corners, image, g);
        drawFormAreas(pageIndex, densityThreshold, (FormMaster) master, pageTaskResult, g,
                markRecognizationConfig, pageSource, focusedColumnIndex, scope);
    }//from  w  w  w  .j  a  va2 s .  c  om
    if (pageTaskException != null) {
        PageTaskExceptionModel model = pageTaskException.getExceptionModel();
        if (model instanceof PageFrameExceptionModel) {
            PageFrameExceptionModel m = (PageFrameExceptionModel) model;
            drawCorners(master, m.getCorners(), image, g);
        }
    }
}

From source file:com.alvermont.terraj.stargen.ui.UIUtils.java

/**
 * Combine a list of images horizontally into one new image.
 * /*from   ww  w.  ja  va 2s .c o m*/
 * @param images The list of images to be combined
 * @return A new image, as wide horizontally as the sum of the input images,
 * containing all the input images
 */
public static BufferedImage combineImagesHorizontal(List<BufferedImage> images) {
    int imageType = -1;
    int height = 0;
    int width = 0;

    // first work out the sizing and image type, we assume the images
    // are all compatible.

    for (BufferedImage image : images) {
        if (imageType == -1) {
            imageType = image.getType();
        }

        width += image.getWidth();

        height = Math.max(height, image.getHeight());
    }

    // create the new image and clear it to black

    BufferedImage bi = new BufferedImage(width, height, imageType);

    Graphics2D g = bi.createGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, width, height);

    // merge the images into the new one

    int xpos = 0;

    for (BufferedImage image : images) {
        int ypos = (height - image.getHeight()) / 2;

        g.drawImage(image, xpos, ypos, null);

        xpos += image.getWidth();
    }

    return bi;
}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static DeskewedImageSource drawCorners(FormMaster master, Point2D[] corners, BufferedImage image,
        Graphics2D g) {
    DeskewedImageSource pageSource = new DeskewedImageSource(image, master.getDeskewGuideCenterPoints(),
            corners);//from   w  ww .  j  a v a2s.co m
    g.setColor(CORNER_COLOR);
    g.setStroke(new BasicStroke(5));
    double size = 40;
    for (int y = 0; y < 2; y++) {
        int i = y * 2;
        g.fillPolygon(pageSource.createPolygon(new Point2D[] { corners[i],
                new Point2D.Double(corners[i].getX() - 1 * size, corners[i].getY() + 1 * size),
                new Point2D.Double(corners[i].getX() - 1 * size, corners[i].getY() - 1 * size) }));
        i++;
        g.fillPolygon(pageSource.createPolygon(new Point2D[] { corners[i],
                new Point2D.Double(corners[i].getX() + 1 * size, corners[i].getY() - 1 * size),
                new Point2D.Double(corners[i].getX() + 1 * size, corners[i].getY() + 1 * size) }));
    }
    return pageSource;
}

From source file:common.utils.ImageUtils.java

/**
 *
 * @param src images to draw, they must be resized to an appropriate size
 * @param dst image where given images will be drawen
 *//* w ww. j av  a 2 s.co m*/
public static void draw4on1(BufferedImage[] src, BufferedImage dst) {
    Graphics2D g2 = dst.createGraphics();
    g2.setColor(java.awt.Color.WHITE);
    g2.fillRect(0, 0, dst.getWidth(), dst.getHeight());
    int dxi;
    int dyi = 0;

    int x0 = dst.getWidth() - 5;
    int y0 = 5;
    int x = x0;
    int y = y0;
    for (int i = 0; i < src.length; i++) {
        if (i % 2 == 0) {
            dxi = -10;
        } else {
            dxi = 0;
        }
        //g2.draw3DRect(dx - 1 , dy-tmp_bi.getHeight() - 1, tmp_bi.getWidth() + 1 , tmp_bi.getHeight() + 1, true);
        g2.drawImage(src[i], x - src[i].getWidth() + dxi, y + dyi, null);
        g2.drawString("#" + i, x - src[i].getWidth() + dxi, y + dyi + 20);
        //g2.rotate(Math.toRadians(4));
        y = y + src[i].getHeight() / 2;
        if (y > dst.getHeight() - src[i].getHeight()) {
            y = y0;
            if (dyi == 0)
                dyi = 10;
            else
                dyi = 0;
            if (x < src[i].getWidth()) {
                x = dst.getWidth();
            }
            x = x - src[i].getWidth() / 2;
        }
    }
    g2.setColor(Color.gray);
    g2.drawRect(0, 0, dst.getWidth() - 1, dst.getHeight() - 1);
    g2.dispose();
}