Example usage for java.awt.image BufferedImage createGraphics

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

Introduction

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

Prototype

public Graphics2D createGraphics() 

Source Link

Document

Creates a Graphics2D , which can be used to draw into this BufferedImage .

Usage

From source file:gui.GraphsPanel.java

/** Save Graph as JPEG.
 * // ww  w .j av a 2  s . c  om
 */
public void writeJpegImage(File file) {
    int width = vv.getWidth();
    int height = vv.getHeight();

    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = bi.createGraphics();
    vv.paint(graphics);
    graphics.dispose();

    try {
        ImageIO.write(bi, "jpeg", file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:peakml.math.Signal.java

public BufferedImage createGraphImage(String name, String xlabel, String ylabel, int width, int height) {
    JFreeChart linechart = createGraph(name, xlabel, ylabel);

    // create the image
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    // create the graphics context
    Graphics2D g = img.createGraphics();

    // draw the line chart
    linechart.draw(g, new Rectangle(0, 0, width, height));

    // return the result
    return img;//from  w ww  .j  a va 2  s  .  c o m
}

From source file:com.liusoft.dlog4j.action.PhotoAction.java

/**
 * /*w w  w.jav  a  2s  . c  o m*/
 * @param ctx
 * @param imgURL
 * @param orient
 * @return
 * @throws IOException
 */
protected boolean rotate(HttpContext ctx, String imgURL, int orient) throws IOException {
    PhotoSaver saver = this.getPhotoSaver();
    InputStream inImg = saver.read(ctx, imgURL);
    BufferedImage old_img = (BufferedImage) ImageIO.read(inImg);
    int width = old_img.getWidth();
    int height = old_img.getHeight();
    BufferedImage new_img = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = new_img.createGraphics();

    AffineTransform origXform = g2d.getTransform();
    AffineTransform newXform = (AffineTransform) (origXform.clone());
    // center of rotation is center of the panel
    double radian = 0;
    double xRot = 0;
    double yRot = 0;
    switch (orient) {
    case 3:
        radian = 180.0;
        xRot = width / 2.0;
        yRot = height / 2.0;
    case 6:
        radian = 90.0;
        xRot = height / 2.0;
        yRot = xRot;
        break;
    case 8:
        radian = 270.0;
        xRot = width / 2.0;
        yRot = xRot;
        break;
    default:
        return false;
    }
    newXform.rotate(Math.toRadians(radian), xRot, yRot);

    g2d.setTransform(newXform);
    // draw image centered in panel
    g2d.drawImage(old_img, 0, 0, null);
    // Reset to Original
    g2d.setTransform(origXform);
    OutputStream out = saver.write(ctx, imgURL);
    try {
        ImageIO.write(new_img, "JPG", out);
    } finally {
        out.close();
    }
    return true;
}

From source file:de.fhg.igd.mapviewer.waypoints.CustomWaypointPainter.java

/**
 * @see AbstractTileOverlayPainter#repaintTile(int, int, int, int,
 *      PixelConverter, int)/*  w w w .  jav  a 2s  .  c o m*/
 */
@Override
public BufferedImage repaintTile(int posX, int posY, int width, int height, PixelConverter converter,
        int zoom) {
    if (renderer == null) {
        return null;
    }

    int overlap = getMaxOverlap();

    // overlap pixel coordinates
    Point topLeftPixel = new Point(Math.max(posX - overlap, 0), Math.max(posY - overlap, 0));
    Point bottomRightPixel = new Point(posX + width + overlap, posY + height + overlap); // TODO
    // check
    // against
    // map
    // size

    // overlap geo positions
    GeoPosition topLeft = converter.pixelToGeo(topLeftPixel, zoom);
    GeoPosition bottomRight = converter.pixelToGeo(bottomRightPixel, zoom);

    // overlap geo positions in RTree CRS
    try {
        BoundingBox tileBounds = createSearchBB(topLeft, bottomRight);

        synchronized (waypoints) {
            Set<W> candidates = waypoints.query(tileBounds, matchTileVerifier);

            if (candidates != null) {
                // sort way-points
                List<W> sorted = new ArrayList<W>(candidates);
                Collections.sort(sorted, paintFirstComparator);

                BufferedImage image = createImage(width, height);
                Graphics2D gfx = image.createGraphics();
                configureGraphics(gfx);

                try {
                    // for each way-point within these bounds
                    for (W w : sorted) {
                        processWaypoint(w, posX, posY, width, height, converter, zoom, gfx);
                    }

                    /*
                     * DEBUG String test = getClass().getSimpleName() +
                     * " - x=" + posX + ", y=" + posY + ": " +
                     * candidates.size() + " WPs"; gfx.setColor(Color.BLUE);
                     * gfx.drawString(test, 4, height - 4);
                     * 
                     * gfx.drawString("minX: " + tileBounds.getMinX(), 4,
                     * height - 84); gfx.drawString("maxX: " +
                     * tileBounds.getMaxX(), 4, height - 64);
                     * gfx.drawString("minY: " + tileBounds.getMinY(), 4,
                     * height - 44); gfx.drawString("maxY: " +
                     * tileBounds.getMaxY(), 4, height - 24);
                     * 
                     * gfx.drawRect(0, 0, width - 1, height - 1);
                     */
                } finally {
                    gfx.dispose();
                }

                return image;
            } else {
                return null;
            }
        }
    } catch (IllegalGeoPositionException e) {
        log.warn("Error painting waypoint tile: " + e.getMessage()); //$NON-NLS-1$
        return null;
    }
}

From source file:business.ImageManager.java

public ImageIcon getArrow(double angle) {
    BufferedImage img = new BufferedImage(40, 40, BufferedImage.TRANSLUCENT);
    Graphics2D big = img.createGraphics();
    //setup para os rastros
    big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    big.setStroke(//from w  w w. j ava  2 s .  co  m
            new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] { 5f }, 0f));
    big.setColor(Color.red);

    int cx = this.getYellowBall().getIconWidth() / 2;
    int cy = this.getYellowBall().getIconHeight() / 2;
    AffineTransform at = AffineTransform.getTranslateInstance(cx, cy);
    at.rotate(Math.toRadians(angle));
    //        at.scale(2.0, 2.0);
    Shape shape = at.createTransformedShape(createArrow());
    big.setPaint(Color.red);
    big.draw(shape);
    ImageIcon ret = new ImageIcon(img);
    return (ret);
    //        tenta com o icone...angle.
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Resize an image/*from ww w  . j av  a2s  .  c om*/
 * 
 * @param originalImage
 * @param width
 * @param height
 * @param type
 * @return
 */
private BufferedImage resize(BufferedImage originalImage, int width, int height, int type) {
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    try {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(originalImage, 0, 0, width, height, null);
    } finally {
        if (g != null) {
            g.dispose();
        }
    }

    return resizedImage;
}

From source file:de.fhg.fokus.openride.services.profile.ProfileService.java

@POST
@Path("picture/")
@Produces("text/json")
public Response postPicture(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("postPicture start");

    boolean success = false;

    //String profilePicturesPath = "C:\\OpenRide\\pictures\\profile";
    String profilePicturesPath = "../OpenRideWeb/img/profile/default";

    //TODO/*from   ww  w  .j  a  v  a2 s  .c  om*/
    //String imagePath = getServletConfig().getInitParameter("imagePath");

    // FIXME: The following try/catch may be removed for production deployments:
    /*try {
    if (java.net.InetAddress.getLocalHost().getHostName().equals("elan-tku-r2032.fokus.fraunhofer.de")) {
        profilePicturesPath = "/mnt/windows/OpenRide/pictures/profile";
    }
    else if (java.net.InetAddress.getLocalHost().getHostName().equals("robusta2.fokus.fraunhofer.de")) {
        profilePicturesPath = "/usr/lib/openride/pictures/profile";
    }
    } catch (UnknownHostException ex) {
    }*/

    int picSize = 125;
    int picThumbSize = 60;

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    if (ServletFileUpload.isMultipartContent(con)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(con);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (items != null) {
            Iterator<FileItem> iter = items.iterator();

            CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
            String uploadedFileName = c.getCustNickname() + "_" + c.getCustId();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {

                    try {
                        BufferedImage uploadedPicture = ImageIO.read(item.getInputStream());

                        int newWidth, newHeight;
                        int xPos, yPos;
                        float ratio = (float) uploadedPicture.getHeight() / (float) uploadedPicture.getWidth();

                        // Resize for "large" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        Image resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picSize - newWidth) / 2);
                        yPos = Math.round((picSize - newHeight) / 2);
                        BufferedImage bim = new BufferedImage(picSize, picSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picSize, picSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        File outputPicture = new File(profilePicturesPath, uploadedFileName + ".jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                        // Resize again for "thumb" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picThumbSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picThumbSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picThumbSize - newWidth) / 2);
                        yPos = Math.round((picThumbSize - newHeight) / 2);
                        bim = new BufferedImage(picThumbSize, picThumbSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picThumbSize, picThumbSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        outputPicture = new File(profilePicturesPath, uploadedFileName + "_thumb.jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("File upload / resize unsuccessful.");
                    }
                    success = true;
                }
            }
        }
    }

    if (success) {

        // TODO: Perhaps introduce a redirection target as a parameter to the putProfile method and redirect to that URL (code 301/302) instead of just doing nothing.
        return null;

        /*
        try {
        String referer = con.getHeader("HTTP_REFERER");
        System.out.println("putPicture: Referer: " + referer);
        if (referer != null)
        return Response.status(Response.Status.SEE_OTHER).contentLocation(new URI(referer)).build();
        else
        return Response.ok().build();
        } catch (URISyntaxException ex) {
        Logger.getLogger(ProfileService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).build();
        }
         */
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an {@link Image} for the given rule.
 * //from  ww  w .j  a v  a2 s  .  c o m
 * @param rule the rule for which to create the image.
 * @param width the image width.
 * @param height the image height.
 * @return the generated image.
 */
public static BufferedImage pointRuleToImage(final Rule rule, int width, int height) {
    DuplicatingStyleVisitor copyStyle = new DuplicatingStyleVisitor();
    rule.accept(copyStyle);
    Rule newRule = (Rule) copyStyle.getCopy();

    int pointSize = 0;
    Stroke stroke = null;
    Symbolizer[] symbolizers = newRule.getSymbolizers();
    if (symbolizers.length > 0) {
        Symbolizer symbolizer = newRule.getSymbolizers()[0];
        if (symbolizer instanceof PointSymbolizer) {
            PointSymbolizer pointSymbolizer = (PointSymbolizer) symbolizer;
            pointSize = SLDs.pointSize(pointSymbolizer);
            stroke = SLDs.stroke(pointSymbolizer);
        }
    }
    int strokeSize = 0;
    if (stroke != null) {
        strokeSize = SLDs.width(stroke);
        if (strokeSize < 0) {
            strokeSize = 1;
            stroke.setWidth(ff.literal(strokeSize));
        }
    }
    pointSize = pointSize + 2 * strokeSize;
    if (pointSize <= 0) {
        pointSize = width;
    }

    // pointSize = width;
    BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    BufferedImage pointImage = new BufferedImage(pointSize, pointSize, BufferedImage.TYPE_INT_ARGB);
    Point point = d.point(pointSize / 2, pointSize / 2);
    d.drawDirect(pointImage, d.feature(point), newRule);
    Graphics2D g2d = finalImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    if (pointSize > width || pointSize > height) {
        g2d.drawImage(pointImage, 0, 0, width, height, 0, 0, pointSize, pointSize, null);
    } else {
        int x = width / 2 - pointSize / 2;
        int y = height / 2 - pointSize / 2;
        g2d.drawImage(pointImage, x, y, null);
    }
    g2d.dispose();

    return finalImage;
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java

private static BufferedImage imageToBufferedImage(Image image) {
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, 0, 0, null);/*from   w  w  w. j av a2 s. co  m*/
    g2.dispose();
    return bufferedImage;
}

From source file:fr.amap.commons.javafx.chart.ChartViewer.java

/**
 * A handler for the export to JPEG option in the context menu.
 *///from   ww  w  . j  av  a  2  s  . c  om
private void handleExportToJPEG() {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Export to JPEG");
    fileChooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("JPEG", "jpg"));
    File file = fileChooser.showSaveDialog(stage);
    if (file != null) {
        try {
            CanvasPositionsAndSize canvasPositionAndSize = getCanvasPositionAndSize();

            BufferedImage image = new BufferedImage((int) canvasPositionAndSize.totalWidth,
                    (int) canvasPositionAndSize.totalHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();

            int index = 0;
            for (ChartCanvas canvas : chartCanvasList) {

                Rectangle2D rectangle2D = canvasPositionAndSize.positionsAndSizes.get(index);

                ((Drawable) canvas.chart).draw(g2, new Rectangle((int) rectangle2D.getX(),
                        (int) rectangle2D.getY(), (int) rectangle2D.getWidth(), (int) rectangle2D.getHeight()));
                index++;
            }

            try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                ImageIO.write(image, "jpg", out);
            }

            /*ExportUtils.writeAsJPEG(chartCanvasList.get(0).chart, (int)chartCanvasList.get(0).getWidth(),
                (int)chartCanvasList.get(0).getHeight(), file);*/
        } catch (IOException ex) {
            // FIXME: show a dialog with the error
        }
    }
}