Example usage for java.awt.image BufferedImage getGraphics

List of usage examples for java.awt.image BufferedImage getGraphics

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getGraphics.

Prototype

public java.awt.Graphics getGraphics() 

Source Link

Document

This method returns a Graphics2D , but is here for backwards compatibility.

Usage

From source file:net.technicpack.ui.lang.ResourceLoader.java

public BufferedImage getCircleClippedImage(BufferedImage contentImage) {
    // copy the picture to an image with transparency capabilities
    BufferedImage outputImage = new BufferedImage(contentImage.getWidth(), contentImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) outputImage.getGraphics();
    g2.drawImage(contentImage, 0, 0, null);

    // Create the area around the circle to cut out
    Area cutOutArea = new Area(new Rectangle(0, 0, outputImage.getWidth(), outputImage.getHeight()));

    int diameter = (outputImage.getWidth() < outputImage.getHeight()) ? outputImage.getWidth()
            : outputImage.getHeight();/*  w ww. j a  v  a2 s.co m*/
    cutOutArea.subtract(new Area(new Ellipse2D.Float((outputImage.getWidth() - diameter) / 2,
            (outputImage.getHeight() - diameter) / 2, diameter, diameter)));

    // Set the fill color to an opaque color
    g2.setColor(Color.WHITE);
    // Set the composite to clear pixels
    g2.setComposite(AlphaComposite.Clear);
    // Turn on antialiasing
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Clear the cut out area
    g2.fill(cutOutArea);

    // dispose of the graphics object
    g2.dispose();

    return outputImage;
}

From source file:com.shending.support.CompressPic.java

public String compressPic() {
    try {/* w  w w  . ja v  a  2 s.c  om*/
        // ?
        file = new File(inputDir);
        //System.out.println(inputDir + inputFileName);
        if (!file.exists()) {
            //throw new Exception("?");
        }
        Image img = ImageIO.read(file);
        // ??
        if (img.getWidth(null) == -1) {
            System.out.println(" can't read,retry!" + "<BR>");
            return "no";
        } else {
            int newWidth;
            int newHeight;
            // ?
            if (this.proportion == true) {
                // ?
                double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
                double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
                // ?
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = outputWidth; // 
                newHeight = outputHeight; // 
            }
            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

            /*
             * Image.SCALE_SMOOTH  ?  ?? 
             */
            tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0,
                    null);
            File f = new File(outputDir);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(outputDir + outputFileName);
            // JPEGImageEncoder??
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            out.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return "ok";
}

From source file:org.openiot.gsn.vsensor.DemoVSensor.java

public void dataAvailable(String inputStreamName, StreamElement data) {
    if (inputStreamName.equalsIgnoreCase("SSTREAM")) {
        String action = (String) data.getData("STATUS");
        /**/*from  www. j  a  v a  2 s .  c om*/
         * 
         */
        String moteId = (String) data.getData("ID");
        if (moteId.toLowerCase().indexOf("mica") < 0)
            return;
        if (action.toLowerCase().indexOf("add") >= 0)
            counter++;
        if (action.toLowerCase().indexOf("remove") >= 0)
            counter--;
    }
    if (inputStreamName.equalsIgnoreCase("CSTREAM")) {

        BufferedImage bufferedImage = null;
        outputStream.reset();
        byte[] rawData = (byte[]) data.getData("IMAGE");
        input = new ByteArrayInputStream(rawData);
        try {
            bufferedImage = ImageIO.read(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        int size = 30;
        int locX = 0;
        int locY = 0;
        if (counter < 0)
            counter = 0;
        switch (counter) {
        case 0:
            graphics.setColor(Color.RED);
            break;
        case 1:
            graphics.setColor(Color.ORANGE);
            break;

        case 2:
            graphics.setColor(Color.YELLOW);
            break;

        case 3:
            graphics.setColor(Color.GREEN);
            break;
        default:
            logger.warn(
                    new StringBuilder().append("Shouldn't happen.>").append(counter).append("<").toString());
        }
        graphics.fillOval(locX, locY, size, size);
        try {
            ImageIO.write(bufferedImage, "jpeg", outputStream);
            outputStream.close();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        StreamElement outputSE = new StreamElement(OUTPUT_FIELDS, OUTPUT_TYPES,
                new Serializable[] { outputStream.toByteArray() }, data.getTimeStamp());
        dataProduced(outputSE);
    }
    if (logger.isInfoEnabled())
        logger.info(new StringBuilder().append("Data received under the name: ").append(inputStreamName)
                .toString());
}

From source file:ancat.visualizers.UndirectedModelVisualizer.java

private void produce(String fileName) {
    _currentLayout.setSize(new Dimension(600, 600));

    VisualizationImageServer<V, E> vv = new VisualizationImageServer<V, E>(_currentLayout,
            new Dimension(600, 600));

    vv.setPreferredSize(new Dimension(600, 600));

    // Setup up a new vertex to paint transformer...
    Transformer<V, Paint> vertexPaint = new Transformer<V, Paint>() {
        public Paint transform(V v) {
            //return Color.GREEN;
            ancat.common.Vertex vertex = (Vertex) v;

            if (vertex instanceof ancat.common.ExecutableFile)
                return Color.BLUE;

            if (vertex instanceof ancat.common.DynamicLibrary)
                return Color.YELLOW;

            if (vertex instanceof ancat.common.ConfigurationFile)
                return Color.ORANGE;

            if (vertex instanceof ancat.common.Unspecified)
                return Color.RED;

            return Color.darkGray;
        }/* w  w w .j  a  va  2 s  .c  o m*/
    };
    // Set up a new stroke Transformer for the edges
    float dash[] = { 10.0f };

    final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash,
            0.0f);

    Transformer<E, Stroke> edgeStrokeTransformer = new Transformer<E, Stroke>() {
        public Stroke transform(E s) {
            return edgeStroke;
        }
    };

    Transformer<E, Font> edgeFontTransformer = new Transformer<E, Font>() {
        public Font transform(E e) {
            return new Font("Dialog", Font.PLAIN, 10);
        }
    };

    Transformer<E, String> lblTransformer = new Transformer<E, String>() {
        public String transform(E e) {
            Edge edge = (Edge) e;
            //return edge.getXMLId();
            return edge.getXMLId() != null ? edge.getXMLId() : "";
        }
    };

    Transformer<V, Font> vertexFontTransformer = new Transformer<V, Font>() {
        public Font transform(V v) {
            return new Font("Dialog", Font.PLAIN, 10);
        }
    };

    Transformer<V, String> vLblTransformer = new Transformer<V, String>() {
        public String transform(V v) {
            Vertex vertex = (Vertex) v;
            return vertex.getElementID();
        }
    };

    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<V>());
    vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<E>());
    // ---->
    vv.getRenderContext().setEdgeFontTransformer(edgeFontTransformer);
    vv.getRenderContext().setLabelOffset(20);
    vv.getRenderContext().setEdgeLabelTransformer(lblTransformer);

    vv.getRenderContext().setVertexFontTransformer(vertexFontTransformer);
    vv.getRenderContext().setVertexLabelTransformer(vLblTransformer);

    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.N);

    BufferedImage img = new BufferedImage((int) _currentLayout.getSize().getWidth(),
            (int) _currentLayout.getSize().getHeight(), BufferedImage.TYPE_INT_ARGB);

    vv.getImage(new Point(0, 0), new Dimension(700, 700));

    Graphics2D g2d = (Graphics2D) img.getGraphics();

    vv.paint(g2d);

    setDisclaimer(g2d);

    g2d.dispose();

    try {
        File file = new File(fileName);

        ImageIO.write(img, "png", file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:gsn.vsensor.DemoVSensor.java

public void dataAvailable(String inputStreamName, StreamElement data) {
    if (inputStreamName.equalsIgnoreCase("SSTREAM")) {
        String action = (String) data.getData("STATUS");
        /**/*w  w  w. java 2  s . com*/
         * 
         */
        String moteId = (String) data.getData("ID");
        if (moteId.toLowerCase().indexOf("mica") < 0)
            return;
        if (action.toLowerCase().indexOf("add") >= 0)
            counter++;
        if (action.toLowerCase().indexOf("remove") >= 0)
            counter--;
    }
    if (inputStreamName.equalsIgnoreCase("CSTREAM")) {

        BufferedImage bufferedImage = null;
        outputStream.reset();
        byte[] rawData = (byte[]) data.getData("IMAGE");
        input = new ByteArrayInputStream(rawData);
        try {
            bufferedImage = ImageIO.read(input);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        int size = 30;
        int locX = 0;
        int locY = 0;
        if (counter < 0)
            counter = 0;
        switch (counter) {
        case 0:
            graphics.setColor(Color.RED);
            break;
        case 1:
            graphics.setColor(Color.ORANGE);
            break;

        case 2:
            graphics.setColor(Color.YELLOW);
            break;

        case 3:
            graphics.setColor(Color.GREEN);
            break;
        default:
            logger.warn(
                    new StringBuilder().append("Shouldn't happen.>").append(counter).append("<").toString());
        }
        graphics.fillOval(locX, locY, size, size);
        try {
            ImageIO.write(bufferedImage, "jpeg", outputStream);
            outputStream.close();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        StreamElement outputSE = new StreamElement(OUTPUT_FIELDS, OUTPUT_TYPES,
                new Serializable[] { outputStream.toByteArray() }, data.getTimeStamp());
        dataProduced(outputSE);
    }
    logger.info(
            new StringBuilder().append("Data received under the name: ").append(inputStreamName).toString());
}

From source file:com.openkm.servlet.admin.StampServlet.java

/**
 * View text color/*  ww  w. jav a 2s .c  om*/
 */
private void textColor(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("textColor({}, {}, {})", new Object[] { session, request, response });
    int stId = WebUtils.getInt(request, "st_id");
    StampText st = StampTextDAO.findByPk(stId);
    BufferedImage bi = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    g.setColor(Color.decode(st.getColor()));
    g.fillRect(0, 0, 16, 16);
    response.setContentType("image/jpeg");
    ImageIO.write(bi, "jpg", response.getOutputStream());
    log.debug("textColor: void");
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.ExcelImageHandler.java

private int clipAndEncodeImage(final Image image, final long width, final long height,
        final double deviceScaleFactor) throws UnsupportedEncoderException, IOException {
    final int imageWidth = (int) StrictGeomUtility.toExternalValue(width);
    final int imageHeight = (int) StrictGeomUtility.toExternalValue(height);
    // first clip.
    final BufferedImage bi = ImageUtils.createTransparentImage(imageWidth, imageHeight);
    final Graphics2D graphics = (Graphics2D) bi.getGraphics();
    graphics.scale(deviceScaleFactor, deviceScaleFactor);

    if (image instanceof BufferedImage) {
        if (graphics.drawImage(image, null, null) == false) {
            logger.debug("Failed to render the image. This should not happen for BufferedImages"); // NON-NLS
        }//from w w  w .  j  a  va2  s  .co m
    } else {
        final WaitingImageObserver obs = new WaitingImageObserver(image);
        obs.waitImageLoaded();

        while (graphics.drawImage(image, null, obs) == false) {
            obs.waitImageLoaded();
            if (obs.isError()) {
                logger.warn("Error while loading the image during the rendering."); // NON-NLS
                break;
            }
        }
    }

    graphics.dispose();
    final byte[] data = RenderUtility.encodeImage(bi);
    return printerBase.getWorkbook().addPicture(data, Workbook.PICTURE_TYPE_PNG);
}

From source file:com.actionbazaar.controller.SellController.java

/**
 * Saves the uploaded file into a folder for the user.
 * @param imageFile - image file to be saved
 * @return image id//from   w  w w . j a  v  a  2  s.  co  m
 */
private String save(UploadedFile imageFile) {
    try {
        File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername());
        if (!saveFld.exists()) {
            if (!saveFld.mkdir()) {
                logger.log(Level.INFO, "Unable to create folder: {0}", saveFld.getAbsolutePath());
                return null;
            }
        }
        File tmp = File.createTempFile("img", "img");
        IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp));
        File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");
        File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png");

        // Create the thumbnail
        BufferedImage image = ImageIO.read(tmp);
        Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH);
        // Convert the thumbnail java.awt.Image into a rendered image which we can save
        BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics bg = thumbnailBi.getGraphics();
        bg.drawImage(thumbnailIm, 0, 0, null);
        bg.dispose();

        ImageIO.write(thumbnailBi, "png", thumbnailImage);
        // Write out the full resolution image as a thumbnail
        ImageIO.write(image, "png", fullResolution);
        if (!tmp.delete()) {
            logger.log(Level.INFO, "Unable to delete: {0}", tmp.getAbsolutePath());
        }
        String imageId = UUID.randomUUID().toString();
        imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(),
                thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername()));
        return imageId;
    } catch (Throwable t) {
        logger.log(Level.SEVERE, "Unable to save the image.", t);
        return null;
    }
}

From source file:ca.sqlpower.wabit.report.ResultSetRendererTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    this.query = new QueryCache(getContext());
    getWorkspace().addQuery(query, getSession());
    query.setDataSource((JDBCDataSource) getSession().getDataSources().getDataSource("regression_test"));

    getWorkspace().addChild(query, 0);/*ww  w.j  a  v  a 2  s.c  om*/
    renderer = new ResultSetRenderer(query);
    parentCB = new ContentBox();
    parentCB.setContentRenderer(renderer);

    BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
    graphics = image.getGraphics();

    Report report = new Report("report");
    report.getPage().addContentBox(parentCB);
    getWorkspace().addReport(report);
}

From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java

public static BufferedImage translateImage(BufferedImage img, double dx, double dy, int type,
        Color fillBgColor) {//from w  w w  . ja  v  a2s. c  o m
    if (img == null) {
        return null;
    }

    int w = img.getWidth();
    int h = img.getHeight();

    BufferedImage out = null;
    AffineTransform tr = new AffineTransform();
    tr.translate(dx, dy);
    BufferedImageOp op = new AffineTransformOp(tr, type);
    out = new BufferedImage(w, h, img.getType());
    Graphics2D g2d = (Graphics2D) out.getGraphics();
    Rectangle clear = new Rectangle(0, 0, out.getWidth(), out.getHeight());
    g2d.setPaint(fillBgColor);
    g2d.fill(clear);
    op.filter(img, out);
    return out;
}