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.openbravo.pos.util.ThumbNailBuilder.java

public Image getThumbNailText(Image img, String text) {
    /*// ww  w.  j av a2 s.com
     * Create an image containing a thumbnail of the product image,
     * or default image.
     * 
     * Then apply the text of the product name. Use text wrapping.
     * 
     * If the product name is too big for the label, ensure that
     * the first part is displayed.
     */

    img = getThumbNail(img);

    BufferedImage imgtext = new BufferedImage(img.getWidth(null), img.getHeight(null),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = imgtext.createGraphics();

    // The text
    // <p style="width: 100px"> DOES NOT WORK PROPERLY.
    // use width= instead.
    String html = "<html><p style=\"text-align:center\" width=\"" + imgtext.getWidth() + "\">"
            + StringEscapeUtils.escapeHtml(text) + "</p>";

    JLabel label = new JLabel(html);
    label.setOpaque(false);
    //label.setText("<html><center>Line1<br>Line2");
    label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    label.setVerticalAlignment(javax.swing.SwingConstants.TOP);
    Dimension d = label.getPreferredSize();
    label.setBounds(0, 0, imgtext.getWidth(), d.height);

    // The background
    Color c1 = new Color(0xff, 0xff, 0xff, 0x40);
    Color c2 = new Color(0xff, 0xff, 0xff, 0xd0);

    //        Point2D center = new Point2D.Float(imgtext.getWidth() / 2, label.getHeight());
    //        float radius = imgtext.getWidth() / 3;
    //        float[] dist = {0.1f, 1.0f};
    //        Color[] colors = {c2, c1};        
    //        Paint gpaint = new RadialGradientPaint(center, radius, dist, colors);
    Paint gpaint = new GradientPaint(new Point(0, 0), c1, new Point(label.getWidth() / 2, 0), c2, true);

    g2d.drawImage(img, 0, 0, null);
    int ypos = imgtext.getHeight() - label.getHeight();
    int ypos_min = -4; // todo: configurable
    if (ypos < ypos_min)
        ypos = ypos_min; // Clamp label
    g2d.translate(0, ypos);
    g2d.setPaint(gpaint);
    g2d.fillRect(0, 0, imgtext.getWidth(), label.getHeight());
    label.paint(g2d);

    g2d.dispose();

    return imgtext;
}

From source file:com.cubusmail.server.services.RetrieveImageServlet.java

/**
 * @param bufInputStream/*from  w w w  . j a  v a  2s .c  om*/
 * @param outputStream
 */
private void writeScaledImage(BufferedInputStream bufInputStream, OutputStream outputStream) {

    long millis = System.currentTimeMillis();
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = bufInputStream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();

        byte[] imageBytes = bos.toByteArray();

        Image image = Toolkit.getDefaultToolkit().createImage(imageBytes);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);
        // determine thumbnail size from WIDTH and HEIGHT
        int thumbWidth = 300;
        int thumbHeight = 200;
        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        int quality = 70;
        quality = Math.max(0, Math.min(quality, 100));
        param.setQuality((float) quality / 100.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
    } catch (InterruptedException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        log.debug("Time for thumbnail: " + (System.currentTimeMillis() - millis) + "ms");
    }
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image.//from   ww w . j  av  a2  s . c  om
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.JFreeChartReportDrawable.java

/**
 * Returns an optional image-map for the entry.
 *
 * @param bounds the bounds for which the image map is computed.
 * @return the computed image-map or null if there is no image-map available.
 *//*from w w  w. j  a v  a2  s.co m*/
public ImageMap getImageMap(final Rectangle2D bounds) {
    if (chartRenderingInfo == null) {
        return null;
    }
    final Rectangle2D dataArea = getDataAreaOffset();
    final Rectangle2D otherArea = new Rectangle2D.Double();

    if ((ObjectUtilities.equal(bounds, this.bounds)) == false) {
        final BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
        final Graphics2D graphics = image.createGraphics();
        draw(graphics, bounds);
        graphics.dispose();
    }

    final ImageMap map = new ImageMap();
    final EntityCollection entityCollection = chartRenderingInfo.getEntityCollection();
    final int count = entityCollection.getEntityCount();
    for (int i = 0; i < count; i++) {
        final ChartEntity chartEntity = entityCollection.getEntity(i);
        final Shape area = chartEntity.getArea();
        final String hrefValue = chartEntity.getURLText();
        final String tooltipValue = chartEntity.getToolTipText();
        if (StringUtils.isEmpty(tooltipValue) == false || StringUtils.isEmpty(hrefValue) == false) {
            final AbstractImageMapEntry entry;
            if (chartEntity instanceof XYItemEntity || chartEntity instanceof CategoryItemEntity
                    || chartEntity instanceof PieSectionEntity) {
                entry = createMapEntry(area, dataArea);
            } else {
                entry = createMapEntry(area, otherArea);
            }
            if (entry == null) {
                continue;
            }
            if (StringUtils.isEmpty(hrefValue) == false) {
                entry.setAttribute(LibXmlInfo.XHTML_NAMESPACE, "href", hrefValue);
            } else {
                entry.setAttribute(LibXmlInfo.XHTML_NAMESPACE, "href", "#");
            }
            if (StringUtils.isEmpty(tooltipValue) == false) {
                entry.setAttribute(LibXmlInfo.XHTML_NAMESPACE, "title", tooltipValue);
            }
            map.addMapEntry(entry);
        }
    }

    return map;
}

From source file:piramide.interaction.reasoner.FuzzyReasonerWizardFacade.java

private BufferedImage createErrorMessagesImage(String text) {
    final Font font = TextTitle.DEFAULT_FONT;
    final Font bigBold = new Font(font.getName(), Font.BOLD, 24);
    final FontRenderContext frc = new FontRenderContext(null, true, false);
    final TextLayout layout = new TextLayout(text, bigBold, frc);
    final Rectangle2D bounds = layout.getBounds();
    final int w = (int) Math.ceil(bounds.getWidth());
    final int h = (int) Math.ceil(bounds.getHeight());
    final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    final Graphics2D g = image.createGraphics();
    g.setColor(Color.WHITE);/*from  w w  w. j a v a 2s  . c o m*/
    g.fillRect(0, 0, w, h);
    g.setColor(Color.RED);
    g.setFont(bigBold);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
    g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY());
    g.dispose();
    return image;
}

From source file:de.thm.arsnova.util.ImageUtils.java

/**
 * Rescales an image represented by a Base64-encoded {@link String}
 *
 * @param originalImageString//from  w ww . java2s .co m
 *            The original image represented by a Base64-encoded
 *            {@link String}
 * @param width
 *            the new width
 * @param height
 *            the new height
 * @return The rescaled Image as Base64-encoded {@link String}, returns null
 *         if the passed-on image isn't in a valid format (a Base64-Image).
 */
String createCover(String originalImageString, final int width, final int height) {
    if (!isBase64EncodedImage(originalImageString)) {
        return null;
    } else {
        final String[] imgInfo = extractImageInfo(originalImageString);

        // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method
        final String extension = imgInfo[0];
        final String base64String = imgInfo[1];

        byte[] imageData = Base64.decodeBase64(base64String);
        try (final ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
                final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            BufferedImage originalImage = ImageIO.read(bais);
            BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());
            Graphics2D g = newImage.createGraphics();

            final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight());

            int x = 0, y = 0, w = width, h = height;
            if (originalImage.getWidth() > originalImage.getHeight()) {
                final int newWidth = (int) Math.round((float) height * ratio);
                x = -(newWidth - width) >> 1;
                w = newWidth;
            } else if (originalImage.getWidth() < originalImage.getHeight()) {
                final int newHeight = (int) Math.round((float) width / ratio);
                y = -(newHeight - height) >> 1;
                h = newHeight;
            }
            g.drawImage(originalImage, x, y, w, h, null);
            g.dispose();

            StringBuilder result = new StringBuilder();
            result.append(IMAGE_PREFIX_START);
            result.append(extension);
            result.append(IMAGE_PREFIX_MIDDLE);

            ImageIO.write(newImage, extension, baos);

            baos.flush();

            result.append(Base64.encodeBase64String(baos.toByteArray()));

            return result.toString();
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            return null;
        }
    }
}

From source file:edu.emory.library.tast.images.ThumbnailServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // location of images
    String baseUrl = AppConfig.getConfiguration().getString(AppConfig.IMAGES_URL);
    baseUrl = StringUtils.trimEnd(baseUrl, '/');

    // image name and size
    String imageFileName = request.getParameter("i");
    int thumbnailWidth = Integer.parseInt(request.getParameter("w"));
    int thumbnailHeight = Integer.parseInt(request.getParameter("h"));

    // image dir//from w w w.j ava 2 s . c  o  m
    String imagesDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);

    // create the thumbnail name
    String thumbnailFileName = FilenameUtils.getBaseName(imageFileName) + "-" + thumbnailWidth + "x"
            + thumbnailHeight + ".png";

    // does it exist?
    File thumbnailFile = new File(imagesDir, thumbnailFileName);
    if (thumbnailFile.exists()) {
        response.sendRedirect(baseUrl + "/" + thumbnailFileName);
        return;
    }

    // read the image
    File imageFile = new File(imagesDir, imageFileName);
    BufferedImage image = ImageIO.read(imageFile);
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    BufferedImage imageCopy = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
    imageCopy.getGraphics().drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight,
            null);

    // height is calculated automatically
    if (thumbnailHeight == 0)
        thumbnailHeight = (int) ((double) thumbnailWidth / (double) imageWidth * (double) imageHeight);

    // width is calculated automatically
    if (thumbnailWidth == 0)
        thumbnailWidth = (int) ((double) thumbnailHeight / (double) imageHeight * (double) imageWidth);

    // create an empty thumbnail
    BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D gr = thumbnail.createGraphics();
    gr.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    // determine the piece of the image which we want to clip
    int clipX1, clipX2, clipY1, clipY2;
    if (imageWidth * thumbnailHeight > thumbnailWidth * imageHeight) {

        int clipWidth = (int) Math
                .round(((double) thumbnailWidth / (double) thumbnailHeight) * (double) imageHeight);
        int imgCenterX = imageWidth / 2;
        clipX1 = imgCenterX - clipWidth / 2;
        clipX2 = imgCenterX + clipWidth / 2;
        clipY1 = 0;
        clipY2 = imageHeight;
    } else {
        int clipHeight = (int) Math
                .round(((double) thumbnailHeight / (double) thumbnailWidth) * (double) imageWidth);
        int imgCenterY = imageHeight / 2;
        clipX1 = 0;
        clipX2 = imageWidth;
        clipY1 = imgCenterY - clipHeight / 2;
        clipY2 = imgCenterY + clipHeight / 2;
    }

    // we filter the image first to get better results when shrinking
    if (2 * thumbnailWidth < clipX2 - clipX1 || 2 * thumbnailHeight < clipY2 - clipY1) {

        int kernelDimX = (clipX2 - clipX1) / (thumbnailWidth);
        int kernelDimY = (clipY2 - clipY1) / (thumbnailHeight);

        if (kernelDimX % 2 == 0)
            kernelDimX++;
        if (kernelDimY % 2 == 0)
            kernelDimY++;

        if (kernelDimX < kernelDimY)
            kernelDimX = kernelDimY;
        if (kernelDimY < kernelDimX)
            kernelDimY = kernelDimX;

        float[] blurKernel = new float[kernelDimX * kernelDimY];
        for (int i = 0; i < kernelDimX; i++)
            for (int j = 0; j < kernelDimY; j++)
                blurKernel[i * kernelDimX + j] = 1.0f / (float) (kernelDimX * kernelDimY);

        BufferedImageOp op = new ConvolveOp(new Kernel(kernelDimX, kernelDimY, blurKernel));
        imageCopy = op.filter(imageCopy, null);

    }

    // draw the thumbnail
    gr.drawImage(imageCopy, 0, 0, thumbnailWidth, thumbnailHeight, clipX1, clipY1, clipX2, clipY2, null);

    // and we are done
    gr.dispose();
    ImageIO.write(thumbnail, "png", thumbnailFile);

    // redirect to it
    response.sendRedirect(baseUrl + "/" + thumbnailFileName);

}

From source file:main.MapKit.java

private BufferedImage convert(BufferedImage loadImg, Color newColor) {
    int w = loadImg.getWidth();
    int h = loadImg.getHeight();
    BufferedImage imgOut = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    BufferedImage imgColor = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = imgColor.createGraphics();
    g.setColor(newColor);/*ww  w  .j av  a2 s .  c o m*/
    g.fillRect(0, 0, w + 1, h + 1);
    g.dispose();

    Graphics2D graphics = imgOut.createGraphics();
    graphics.drawImage(loadImg, 0, 0, null);
    graphics.setComposite(MultiplyComposite.Default);
    graphics.drawImage(imgColor, 0, 0, null);
    graphics.dispose();

    return imgOut;
}

From source file:at.tuwien.ifs.somtoolbox.visualization.ClusterConnectionsVisualizer.java

@Override
public BufferedImage createVisualization(int variantIndex, GrowingSOM gsom, int width, int height)
        throws SOMToolboxException {
    GrowingLayer layer = gsom.getLayer();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();

    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, width, height);/*w w  w .  ja  v  a  2 s.  c  om*/

    // need to calculate some params relative to the unit width/height, which is relative to the desired output size
    // a unitWidth/Height of 10, as used previously, works by default only fine in the SOMViewer
    int somWidth = layer.getXSize();
    int somHeight = layer.getYSize();
    double unitWidth = width / somWidth;
    double unitHeight = height / somHeight;

    DoubleMatrix2D unitDistanceMatrix = gsom.getLayer().getUnitDistanceMatrix();

    for (int col = 0; col < somWidth; col++) {
        for (int row = 0; row < somHeight; row++) {

            if (col < somWidth - 1) {
                // draw horizontal connection
                double distanceRight = unitDistanceMatrix.get(layer.getUnitIndex(col, row),
                        layer.getUnitIndex(col + 1, row));
                g.setPaint(getColor(distanceRight));
                int xPos = (int) (col * unitHeight + unitHeight * 0.7);
                int yPos = (int) (row * unitWidth + unitWidth * 0.4);
                g.fillRect(xPos, yPos, (int) (unitWidth * 0.6), (int) (unitHeight * 0.2));
            }

            if (row < somHeight - 1) {
                // draw vertical connection
                double distanceLower = unitDistanceMatrix.get(layer.getUnitIndex(col, row),
                        layer.getUnitIndex(col, row + 1));
                g.setPaint(getColor(distanceLower));

                int xPos = (int) (col * unitHeight + unitHeight * 0.4);
                int yPos = (int) (row * unitWidth + unitWidth * 0.7);
                g.fillRect(xPos, yPos, (int) (unitWidth * 0.2), (int) (unitHeight * 0.6));
            }
        }
    }

    return image;
}

From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java

/**
 * Masks out white colour// w ww.j  av  a 2s.  c  o m
 * @param image the image to mask out
 * @return the resulting image
 */
private BufferedImage transformWhiteToTransparent(BufferedImage image) {

    BufferedImage dest = image;
    if (image.getType() != BufferedImage.TYPE_INT_ARGB) {
        dest = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = dest.createGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();

        image.flush();
    }

    // Mask out the white pixels
    final int width = image.getWidth();
    int[] imgData = new int[width];

    for (int y = 0; y < dest.getHeight(); y++) {
        // fetch a line of data from each image
        dest.getRGB(0, y, width, 1, imgData, 0, 1);
        // apply the mask
        for (int x = 0; x < width; x++) {
            for (Color col : MASKED_COLORS) {
                int colDist = Math.abs(col.getRed() - (imgData[x] >> 16 & 0x000000FF))
                        + Math.abs(col.getGreen() - (imgData[x] >> 8 & 0x000000FF))
                        + Math.abs(col.getBlue() - (imgData[x] & 0x000000FF));
                if (colDist <= COLOR_DIST) {
                    imgData[x] = 0x00FFFFFF & imgData[x];
                }
            }
        }
        // replace the data
        dest.setRGB(0, y, width, 1, imgData, 0, 1);
    }
    return dest;
}