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:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static void enforceBorderColors(BufferedImage inputImage) {
    Graphics2D g = inputImage.createGraphics();
    g.setBackground(new Color(0, 0, 0, 0));
    g.clearRect(1, 1, inputImage.getWidth() - 2, inputImage.getHeight() - 2);
    g.dispose();/*from  w  ww.j a va2s  .  co  m*/
    int w = inputImage.getWidth();
    int h = inputImage.getHeight();
    int[] rgb = new int[w * h];

    inputImage.getRGB(0, 0, w, h, rgb, 0, w);

    for (int i = 0; i < rgb.length; i++) {
        if ((0xff000000 & rgb[i]) != 0) {
            rgb[i] = 0xff000000;
        }
    }
    inputImage.setRGB(0, 0, w, h, rgb, 0, w);
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void writeImage(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String formatName) throws IOException {

    BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
    Dimension newDimension = calculateDimension(originalImage, width, height);

    if (newDimension != null) {
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizedImage = new BufferedImage(newDimension.width, newDimension.height, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, newDimension.width, newDimension.height, null);
        g.dispose();/*from w  w  w  . ja va2  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);

        ImageIO.write(resizedImage, formatName, response.getOutputStream());
    } else {
        if ("png".equals(formatName)) {
            response.getOutputStream().write(imageData);
        } else {
            ImageIO.write(originalImage, "gif", response.getOutputStream());
        }
    }
}

From source file:org.gbif.portal.web.util.ChartUtils.java

/**
 * Writes out the image using the supplied file name.
 * //  ww  w.ja v  a  2s  .c  o  m
 * @param legend
 * @param fileName
 * @return
 */
public static String writePieChartImageToTempFile(Map<String, Double> legend, String fileName) {

    String filePath = System.getProperty(tmpDirSystemProperty) + File.separator + fileName + defaultExtension;
    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName + defaultExtension;
    }

    final DefaultPieDataset data = new DefaultPieDataset();
    Set<String> keys = legend.keySet();
    for (String key : keys) {
        logger.info("Adding key : " + key);
        data.setValue(key, legend.get(key));
    }

    // create a pie chart...
    final boolean withLegend = true;
    final JFreeChart chart = ChartFactory.createPieChart(null, data, withLegend, false, false);

    PiePlot piePlot = (PiePlot) chart.getPlot();
    piePlot.setLabelFont(new Font("Arial", Font.PLAIN, 10));
    piePlot.setLabelBackgroundPaint(Color.WHITE);

    LegendTitle lt = chart.getLegend();
    lt.setBackgroundPaint(Color.WHITE);
    lt.setWidth(300);
    lt.setBorder(0, 0, 0, 0);
    lt.setItemFont(new Font("Arial", Font.PLAIN, 11));

    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    final BufferedImage image = new BufferedImage(300, 250, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 300, 250);

    // draw
    chart.draw(g2, chartArea, null, null);

    try {
        FileOutputStream fOut = new FileOutputStream(fileToCheck);
        ChartUtilities.writeChartAsPNG(fOut, chart, 300, 250);
        return fileToCheck.getName();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    }
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Convenience method that returns a scaled instance of the provided {@code BufferedImage}. 
 *  /*from  w  w w  .  j a  v  a2  s  . c  o m*/
 * @param img the original image to be scaled 
 * @param targetWidth the desired width of the scaled instance, in pixels 
 * @param targetHeight the desired height of the scaled instance, in pixels 
 * @param hint one of the rendering hints that corresponds to {@code RenderingHints.KEY_INTERPOLATION} (e.g. 
 *        {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, 
 *        {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) 
 * @param higherQuality if true, this method will use a multi-step scaling technique that provides higher quality than the 
 *        usual one-step technique (only useful in downscaling cases, where {@code targetWidth} or {@code targetHeight} is 
 *        smaller than the original dimensions, and generally only when the {@code BILINEAR} hint is specified) 
 * @return a scaled version of the original {@code BufferedImage} 
 */
public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    final int type = img.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    int w;
    int h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then 
        // scale down in multiple passes with drawImage() 
        // until the target size is reached 
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original 
        // size to target size with a single drawImage() call 
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        final BufferedImage tmp = new BufferedImage(w, h, type);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

private static BufferedImage toThumbnailSize(BufferedImage image) {
    final int w = image.getWidth();
    final int h = image.getHeight();
    final int max = Math.max(w, h);
    if (max <= 256) {
        return image;
    }/*  w  w  w.j av  a 2s.  c o m*/
    final double s = max / 256d;
    final BufferedImage result = new BufferedImage(Math.max((int) Math.min(w / s, 256), 1),
            Math.max((int) Math.min(h / s, 256), 1), BufferedImage.TYPE_INT_BGR);
    final Graphics2D graphics = result.createGraphics();
    try {
        graphics.drawImage(image.getScaledInstance(result.getWidth(), result.getHeight(), Image.SCALE_SMOOTH),
                0, 0, null);
    } finally {
        graphics.dispose();
    }
    return result;
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;/*  w ww  .j ava 2 s  .  c om*/
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        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);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:br.com.diegosilva.jsfcomponents.util.Utils.java

public static byte[] resizeImage(byte[] imageData, String contentType, int width) {
    ImageIcon icon = new ImageIcon(imageData);

    double ratio = (double) width / icon.getIconWidth();
    int resizedHeight = (int) (icon.getIconHeight() * ratio);

    int imageType = "image/png".equals(contentType) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
    BufferedImage bImg = new BufferedImage(width, resizedHeight, imageType);
    Graphics2D g2d = bImg.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.drawImage(icon.getImage(), 0, 0, width, resizedHeight, null);
    g2d.dispose();/*w  w w  .j av  a 2s.c  o  m*/

    String formatName = "";
    if ("image/png".equals(contentType))
        formatName = "png";
    else if ("image/jpeg".equals(contentType) || "image/jpg".equals(contentType))
        formatName = "jpeg";

    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    try {
        ImageIO.write(bImg, formatName, baos);
        return baos.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:jshm.gui.GuiUtil.java

/**
 * Resize an ImageIcon to the specified size.
 * @param icon The ImageIcon to resize//w  w  w . j  a  v  a 2 s.c  o m
 * @param width The new width
 * @param height The new height
 */
public final static javax.swing.ImageIcon resizeIcon(ImageIcon icon, int width, int height) {
    LOG.info("Resizing to " + width + "x" + height);
    Image img = icon.getImage();
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics g = bi.createGraphics();
    g.drawImage(img, 0, 0, width, height, null);
    g.dispose();

    return new javax.swing.ImageIcon(bi);
}

From source file:com.fluidops.iwb.deepzoom.DZConvert.java

/**
 * Returns resized image//from   w ww  .ja va 2  s.  c  om
 * NB - useful reference on high quality image resizing can be found here:
 *   http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
 * @param width the required width
 * @param height the frequired height
 * @param img the image to be resized
 */
private static BufferedImage resizeImage(BufferedImage img, double width, double height) {
    int w = (int) width;
    int h = (int) height;
    BufferedImage result = new BufferedImage(w, h, getType(img));
    Graphics2D g = result.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.drawImage(img, 0, 0, w, h, 0, 0, img.getWidth(), img.getHeight(), null);
    return result;
}

From source file:edu.umn.cs.spatialHadoop.nasa.MultiHDFPlot.java

/**
 * Draws a scale used with the heat map/*from  w  w w.  j av a2s.c  om*/
 * @param output
 * @param valueRange
 * @param width
 * @param height
 * @throws IOException
 */
private static void drawVerticalScale(Path output, double min, double max, int width, int height,
        OperationsParams params) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    // fix this part to work according to color1, color2 and gradient type
    HDFPlot.HDFRasterizer gradient = new HDFPlot.HDFRasterizer();
    gradient.configure(params);
    HDFRasterLayer gradientLayer = (HDFRasterLayer) gradient.createCanvas(0, 0, new Rectangle());
    for (int y = 0; y < height; y++) {
        Color color = gradientLayer.calculateColor(height - y, 0, height);
        g.setColor(color);
        g.drawRect(width * 3 / 4, y, width / 4, 1);
    }

    int fontSize = 24;
    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    double step = (max - min) * fontSize * 5 / height;
    step = (int) (Math.pow(10.0, Math.round(Math.log10(step))));
    double min_value = Math.floor(min / step) * step;
    double max_value = Math.floor(max / step) * step;

    g.setColor(Color.WHITE);
    for (double value = min_value; value <= max_value; value += step) {
        double y = ((value - min) + (max - value) * (height - fontSize)) / (max - min);
        g.drawString(String.valueOf((int) value), 5, (int) y);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}