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:com.kahlon.guard.controller.PersonImageManager.java

private BufferedImage resizeImage(BufferedImage originalImage, int type) {
    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();/*  w ww . j  av  a  2  s  .com*/

    return resizedImage;
}

From source file:TextBouncer.java

public BufferedImage makeBufferedImage(Image image, int imageType) {
    if (waitForImage(image) == false)
        return null;

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), imageType);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);/*from   w w  w. j a  va 2 s .  c  o m*/
    return bufferedImage;
}

From source file:org.n52.io.type.quantity.handler.img.ChartIoHandler.java

private BufferedImage createImage() {
    IoParameters parameters = getParameters();
    int width = parameters.getWidth();
    int height = parameters.getHeight();
    BufferedImage chartImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.fillRect(0, 0, width, height);
    chartGraphics.setColor(Color.WHITE);

    jFreeChart.setTextAntiAlias(true);/*from w w w.ja  v a 2 s.  c  o m*/
    jFreeChart.setAntiAlias(true);
    if (jFreeChart.getLegend() != null) {
        jFreeChart.getLegend().setFrame(BlockBorder.NONE);
    }
    jFreeChart.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height));
    return chartImage;
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

private BufferedImage resizeImageWithHint(BufferedImage originalImage, int type) {

    BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
    g.dispose();//from  w  w  w .  ja va 2 s.  c  o m
    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);

    return resizedImage;
}

From source file:com.att.aro.ui.model.diagnostic.GraphPanelHelper.java

public void SaveImageAs(JViewport pane, String graphPanelSaveDirectory) {

    JFileChooser fc = new JFileChooser(graphPanelSaveDirectory);

    // Set up file types
    String[] fileTypesJPG = new String[2];
    String fileDisplayTypeJPG = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.jpeg");
    fileTypesJPG[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpeg");
    fileTypesJPG[1] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
    FileFilter filterJPG = new ExtensionFileFilter(fileDisplayTypeJPG, fileTypesJPG);

    fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
    String[] fileTypesPng = new String[1];
    String fileDisplayTypePng = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png");
    fileTypesPng[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.png");
    FileFilter filterPng = new ExtensionFileFilter(fileDisplayTypePng, fileTypesPng);
    fc.addChoosableFileFilter(filterPng);
    fc.setFileFilter(filterJPG);//from   w  w w.  j  a va2s.c  om
    File plotImageFile = null;

    boolean bSavedOrCancelled = false;
    while (!bSavedOrCancelled) {
        if (fc.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
            String strFile = fc.getSelectedFile().toString();
            String strFileLowerCase = strFile.toLowerCase();
            String fileDesc = fc.getFileFilter().getDescription();
            String fileType = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
            if ((fileDesc.equalsIgnoreCase(
                    ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png"))
                    || strFileLowerCase.endsWith(ResourceBundleHelper.getMessageString("fileType.filters.dot")
                            + fileTypesPng[0].toLowerCase()))) {
                fileType = fileTypesPng[0];
            }
            if (strFile.length() > 0) {
                // Save current directory
                graphPanelSaveDirectory = fc.getCurrentDirectory().getPath();

                if ((fileType != null) && (fileType.length() > 0)) {
                    String fileTypeLowerCaseWithDot = ResourceBundleHelper
                            .getMessageString("fileType.filters.dot") + fileType.toLowerCase();
                    if (!strFileLowerCase.endsWith(fileTypeLowerCaseWithDot)) {
                        strFile += ResourceBundleHelper.getMessageString("fileType.filters.dot") + fileType;
                    }
                }
                plotImageFile = new File(strFile);
                boolean bAttemptToWriteToFile = true;
                if (plotImageFile.exists()) {
                    if (MessageDialogFactory.showConfirmDialog(pane,
                            MessageFormat.format(
                                    ResourceBundleHelper.getMessageString("fileChooser.fileExists"),
                                    plotImageFile.getAbsolutePath()),
                            ResourceBundleHelper.getMessageString("fileChooser.confirm"),
                            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                        bAttemptToWriteToFile = false;
                    }
                }
                if (bAttemptToWriteToFile) {
                    try {
                        if (fileType != null && fileType.equalsIgnoreCase(fileTypesPng[0])) {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "png", plotImageFile);
                        } else {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "jpg", plotImageFile);
                        }
                        bSavedOrCancelled = true;
                    } catch (IOException e) {
                        MessageDialogFactory.showMessageDialog(pane, ResourceBundleHelper
                                .getMessageString("fileChooser.errorWritingToFile" + plotImageFile.toString()));
                    }
                }
            }
        } else {
            bSavedOrCancelled = true;
        }
    }
}

From source file:com.joliciel.jochre.search.highlight.ImageSnippet.java

public BufferedImage getImage() {
    try {/*from w ww . jav  a 2 s. co m*/
        BufferedImage originalImage = ImageIO.read(imageFile);
        BufferedImage imageSnippet = new BufferedImage(this.rectangle.getWidth(), this.rectangle.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        originalImage = originalImage.getSubimage(this.rectangle.getLeft(), this.rectangle.getTop(),
                this.rectangle.getWidth(), this.rectangle.getHeight());
        Graphics2D graphics2D = imageSnippet.createGraphics();
        graphics2D.drawImage(originalImage, 0, 0, this.rectangle.getWidth(), this.rectangle.getHeight(), null);
        int extra = 2;
        for (Rectangle rect : this.highlights) {
            graphics2D.setStroke(new BasicStroke(1));
            graphics2D.setPaint(Color.BLACK);
            graphics2D.drawRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
            graphics2D.setColor(new Color(255, 255, 0, 127));
            graphics2D.fillRect(rect.getLeft() - this.rectangle.getLeft() - extra,
                    rect.getTop() - this.rectangle.getTop() - extra, rect.getWidth() + (extra * 2),
                    rect.getHeight() + (extra * 2));
        }
        return imageSnippet;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.sire.web.CajFacturaEnviadaBean.java

private void savePicture() {
    if (file != null) {
        try {/*from w w w.  j a  v  a  2s .c  o m*/
            BufferedImage originalImage = ImageIO.read(file.getInputstream());

            BufferedImage outputImage = new BufferedImage((int) (originalImage.getWidth() * 0.25),
                    (int) (originalImage.getHeight() * 0.25), originalImage.getType());

            Graphics2D g2d = outputImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, (int) (originalImage.getWidth() * 0.25),
                    (int) (originalImage.getHeight() * 0.25), null);
            g2d.dispose();

            String imagesFolder = System.getProperty("imagesFolder");

            if (imagesFolder == null) {
                String currentUsersHomeDir = System.getProperty("user.home");
                imagesFolder = currentUsersHomeDir + File.separator + "photos";
            }

            Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
            ImageWriter writer = (ImageWriter) iter.next();
            ImageWriteParam iwp = writer.getDefaultWriteParam();

            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            float quality = 1.0f; // reduce quality by 0%  
            iwp.setCompressionQuality(quality);

            File f = new File(imagesFolder + File.separator + fileName);
            try (FileImageOutputStream output = new FileImageOutputStream(f)) {
                writer.setOutput(output);

                IIOImage image = new IIOImage(outputImage, null, null);
                writer.write(null, image, iwp);
                writer.dispose();
            }
        } catch (IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }
}

From source file:kz.supershiny.core.services.ImageService.java

/**
 * Creates thumb for image.//from   ww  w  .  jav a 2s.c om
 *
 * @param originalData original image in byte array
 * @param type original - 0, large - 1, small - 2
 * @return resized image in byte array
 */
public static byte[] resizeImage(byte[] originalData, ImageSize type) {
    //if original flag, then return original
    if (type.equals(ImageSize.ORIGINAL)) {
        return originalData;
    }

    BufferedImage originalImage = null;
    BufferedImage resizedImage = null;
    byte[] result = null;
    //convert bytes to BufferedImage
    try (InputStream in = new ByteArrayInputStream(originalData)) {
        originalImage = ImageIO.read(in);
    } catch (IOException ex) {
        LOG.error("Cannot convert byte array to BufferedImage!", ex);
        return null;
    }
    //get original size
    int scaledHeight = originalImage.getHeight();
    int scaledWidth = originalImage.getWidth();

    switch (type) {
    case LARGE:
        scaledWidth = LARGE_WIDTH;
        scaledHeight = LARGE_HEIGHT;
        break;
    case SMALL:
        scaledWidth = SMALL_WIDTH;
        scaledHeight = SMALL_HEIGHT;
        break;
    default:
        break;
    }
    //calculate aspect ratio
    float ratio = 1.0F * originalImage.getWidth() / originalImage.getHeight();
    if (ratio > 1.0F) {
        scaledHeight = (int) (scaledHeight / ratio);
    } else {
        scaledWidth = (int) (scaledWidth * ratio);
    }
    //resize with hints
    resizedImage = new BufferedImage(scaledWidth, scaledHeight,
            originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());

    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    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);
    //convert BufferedImage to bytes
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(resizedImage, "png", baos);
        baos.flush();
        result = baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Cannot convert BufferedImage to byte array!", ex);
    }
    return result;
}

From source file:org.n52.oxf.render.sos.AnimatedMapBarChartRenderer.java

protected Image renderFrame(ITimePosition[] sortedTimeArray, int currentTimeIndex, int screenW, int screenH,
        IBoundingBox bbox, Set<OXFFeature> featuresWithCharts, ObservationSeriesCollection tupleFinder) {
    ContextBoundingBox contextBBox = new ContextBoundingBox(bbox);

    BufferedImage image = new BufferedImage(screenW, screenH, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);//  w  ww.  ja  va 2s.  co m
    g.fillRect(0, 0, screenW, screenH);

    g.setColor(Color.BLACK);

    ITimePosition currentTimePos = sortedTimeArray[currentTimeIndex];

    for (OXFFeature chartFeature : featuresWithCharts) {

        //
        // create Plot for each "chart feature" and add it to the cache:
        //
        if (!chartCache.contains(currentTimePos, chartFeature)) {

            // if there is a data tuple for the current time position -> create a new plot
            if (tupleFinder.getTuple(chartFeature, currentTimePos) != null) {
                CategoryPlot plot = drawChart4FOI(chartFeature.getID(), currentTimePos.toString(),
                        tupleFinder.getTuple(chartFeature, currentTimePos));
                chartCache.add(currentTimePos, chartFeature, plot);
            }
        }

        CategoryPlot plot = (CategoryPlot) chartCache.get(currentTimePos, chartFeature);

        // if there wasn't a plot for the current time position go backwards through the sortedTimeArray and take the most recent one:
        int j = currentTimeIndex - 1;
        while (plot == null && j >= 0) {
            plot = (CategoryPlot) chartCache.get(sortedTimeArray[j], chartFeature);
            j--;
        }

        //
        // draw the plots into the image at the georeferenced position of the corresponding chartFeature:
        //
        Point pRealWorld = (Point) chartFeature.getGeometry();

        java.awt.Point pScreen = ContextBoundingBox.realworld2Screen(contextBBox.getActualBBox(), screenW,
                screenH, new Point2D.Double(pRealWorld.getCoordinate().x, pRealWorld.getCoordinate().y));
        // if an appropriate plot was found -> draw it
        if (plot != null) {
            for (int i = 0; i < observedProperties.length; i++) {
                plot.getRangeAxis(i).setRange((Double) tupleFinder.getMinimum(i) - 5,
                        (Double) tupleFinder.getMaximum(i));
                if (i > 0) {
                    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
                }
            }

            plot.draw(g,
                    new Rectangle2D.Float(pScreen.x + X_SHIFT + 10, pScreen.y + Y_SHIFT,
                            CHART_WIDTH + observedProperties.length * CHART_WIDTH_MULTIPLICATOR, CHART_HEIGHT),
                    null, null, null);
        }
        // otherwise draw "no data available"
        else {
            g.drawString("No data available", pScreen.x + X_SHIFT, pScreen.y + Y_SHIFT);
        }

        // draw point of feature:
        g.fillOval(pScreen.x - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                pScreen.y - (FeatureGeometryRenderer.DOT_SIZE_POINT / 2),
                FeatureGeometryRenderer.DOT_SIZE_POINT, FeatureGeometryRenderer.DOT_SIZE_POINT);
    }

    return image;
}

From source file:IDlook.java

private void createThumbnail() {
    int maxDim = 350;
    try {//from  ww  w  .  ja  va  2  s  . com
        Image inImage = icon.getImage();

        double scale = (double) maxDim / (double) inImage.getHeight(null);
        if (inImage.getWidth(null) > inImage.getHeight(null)) {
            scale = (double) maxDim / (double) inImage.getWidth(null);
        }

        int scaledW = (int) (scale * inImage.getWidth(null));
        int scaledH = (int) (scale * inImage.getHeight(null));

        BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);

        AffineTransform tx = new AffineTransform();

        if (scale < 1.0d) {
            tx.scale(scale, scale);
        }

        Graphics2D g2d = outImage.createGraphics();
        g2d.drawImage(inImage, tx, null);
        g2d.dispose();

        iconThumbnail = new ImageIcon(outImage);
    } catch (Exception e) {
        e.printStackTrace();
    }
}