Example usage for java.awt RenderingHints VALUE_INTERPOLATION_BICUBIC

List of usage examples for java.awt RenderingHints VALUE_INTERPOLATION_BICUBIC

Introduction

In this page you can find the example usage for java.awt RenderingHints VALUE_INTERPOLATION_BICUBIC.

Prototype

Object VALUE_INTERPOLATION_BICUBIC

To view the source code for java.awt RenderingHints VALUE_INTERPOLATION_BICUBIC.

Click Source Link

Document

Interpolation hint value -- the color samples of 9 nearby integer coordinate samples in the image are interpolated using a cubic function in both X and Y to produce a color sample.

Usage

From source file:org.openstreetmap.josm.tools.ImageProvider.java

/**
 * Creates a rotated version of the input image.
 *
 * @param c The component to get properties useful for painting, e.g. the foreground or
 * background color./* w  ww  . j a  v  a  2s  . c  o  m*/
 * @param img the image to be rotated.
 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
 * will mod it with 360 before using it.
 *
 * @return the image after rotating.
 */
public static Image createRotatedImage(Component c, Image img, double rotatedAngle) {
    // convert rotatedAngle to a value from 0 to 360
    double originalAngle = rotatedAngle % 360;
    if (rotatedAngle != 0 && originalAngle == 0) {
        originalAngle = 360.0;
    }

    // convert originalAngle to a value from 0 to 90
    double angle = originalAngle % 90;
    if (originalAngle != 0.0 && angle == 0.0) {
        angle = 90.0;
    }

    double radian = Math.toRadians(angle);

    new ImageIcon(img); // load completely
    int iw = img.getWidth(null);
    int ih = img.getHeight(null);
    int w;
    int h;

    if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
        w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
        h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
    } else {
        w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
        h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
    }
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    Graphics2D g2d = (Graphics2D) g.create();

    // calculate the center of the icon.
    int cx = iw / 2;
    int cy = ih / 2;

    // move the graphics center point to the center of the icon.
    g2d.translate(w / 2, h / 2);

    // rotate the graphics about the center point of the icon
    g2d.rotate(Math.toRadians(originalAngle));

    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.drawImage(img, -cx, -cy, c);

    g2d.dispose();
    new ImageIcon(image); // load completely
    return image;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java

/**
 * @param content//from  w ww .  j av a2s  .c  om
 * @param image
 */
protected boolean drawImage(final RenderableReplacedContentBox content, Image image) {
    final StyleSheet layoutContext = content.getStyleSheet();
    final boolean shouldScale = layoutContext.getBooleanStyleProperty(ElementStyleKeys.SCALE);

    final int x = (int) StrictGeomUtility.toExternalValue(content.getX());
    final int y = (int) StrictGeomUtility.toExternalValue(content.getY());
    final int width = (int) StrictGeomUtility.toExternalValue(content.getWidth());
    final int height = (int) StrictGeomUtility.toExternalValue(content.getHeight());

    if (width == 0 || height == 0) {
        LogicalPageDrawable.logger.debug("Error: Image area is empty: " + content);
        return false;
    }

    WaitingImageObserver obs = new WaitingImageObserver(image);
    obs.waitImageLoaded();
    final int imageWidth = image.getWidth(obs);
    final int imageHeight = image.getHeight(obs);
    if (imageWidth < 1 || imageHeight < 1) {
        return false;
    }

    final Rectangle2D.Double drawAreaBounds = new Rectangle2D.Double(x, y, width, height);
    final AffineTransform scaleTransform;

    final Graphics2D g2;
    if (shouldScale == false) {
        double deviceScaleFactor = 1;
        final double devResolution = metaData.getNumericFeatureValue(OutputProcessorFeature.DEVICE_RESOLUTION);
        if (metaData.isFeatureSupported(OutputProcessorFeature.IMAGE_RESOLUTION_MAPPING)) {
            if (devResolution != 72.0 && devResolution > 0) {
                // Need to scale the device to its native resolution before attempting to draw the image..
                deviceScaleFactor = (72.0 / devResolution);
            }
        }

        final int clipWidth = Math.min(width, (int) Math.ceil(deviceScaleFactor * imageWidth));
        final int clipHeight = Math.min(height, (int) Math.ceil(deviceScaleFactor * imageHeight));
        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.translate(alignmentX, alignmentY);
        g2.clip(new Rectangle2D.Float(0, 0, clipWidth, clipHeight));
        g2.scale(deviceScaleFactor, deviceScaleFactor);

        scaleTransform = null;
    } else {
        g2 = (Graphics2D) getGraphics().create();
        g2.clip(drawAreaBounds);
        g2.translate(x, y);
        g2.clip(new Rectangle2D.Float(0, 0, width, height));

        final double scaleX;
        final double scaleY;

        final boolean keepAspectRatio = layoutContext
                .getBooleanStyleProperty(ElementStyleKeys.KEEP_ASPECT_RATIO);
        if (keepAspectRatio) {
            final double scaleFactor = Math.min(width / (double) imageWidth, height / (double) imageHeight);
            scaleX = scaleFactor;
            scaleY = scaleFactor;
        } else {
            scaleX = width / (double) imageWidth;
            scaleY = height / (double) imageHeight;
        }

        final int clipWidth = (int) (scaleX * imageWidth);
        final int clipHeight = (int) (scaleY * imageHeight);

        final ElementAlignment horizontalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.ALIGNMENT);
        final ElementAlignment verticalAlignment = (ElementAlignment) layoutContext
                .getStyleProperty(ElementStyleKeys.VALIGNMENT);
        final int alignmentX = (int) RenderUtility.computeHorizontalAlignment(horizontalAlignment, width,
                clipWidth);
        final int alignmentY = (int) RenderUtility.computeVerticalAlignment(verticalAlignment, height,
                clipHeight);

        g2.translate(alignmentX, alignmentY);

        final Object contentCached = content.getContent().getContentCached();
        if (contentCached instanceof Image) {
            image = (Image) contentCached;
            scaleTransform = null;
        } else if (metaData.isFeatureSupported(OutputProcessorFeature.PREFER_NATIVE_SCALING) == false) {
            image = RenderUtility.scaleImage(image, clipWidth, clipHeight,
                    RenderingHints.VALUE_INTERPOLATION_BICUBIC, true);
            content.getContent().setContentCached(image);
            obs = new WaitingImageObserver(image);
            obs.waitImageLoaded();
            scaleTransform = null;
        } else {
            scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
        }
    }

    while (g2.drawImage(image, scaleTransform, obs) == false) {
        obs.waitImageLoaded();
        if (obs.isError()) {
            LogicalPageDrawable.logger.warn("Error while loading the image during the rendering.");
            break;
        }
    }

    g2.dispose();
    return true;
}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) {
    log.debug("paintThumbnail entry " + photo.getUuid());
    long startTime = System.currentTimeMillis();
    long thumbReadyTime = 0;
    long thumbDrawnTime = 0;
    long endTime = 0;
    // Current position in which attributes can be drawn
    int ypos = starty + rowHeight / 2;
    boolean useOldThumbnail = false;

    Thumbnail thumbnail = null;//from   w w  w. j  a va  2 s  .  c o m
    log.debug("finding thumb");
    boolean hasThumbnail = photo.hasThumbnail();
    log.debug("asked if has thumb");
    if (hasThumbnail) {
        log.debug("Photo " + photo.getUuid() + " has thumbnail");
        thumbnail = photo.getThumbnail();
        log.debug("got thumbnail");
    } else {
        /*
         Check if the thumbnail has been just invalidated. If so, use the 
         old one until we get the new thumbnail created.
         */
        thumbnail = photo.getOldThumbnail();
        if (thumbnail != null) {
            useOldThumbnail = true;
        } else {
            // No success, use default thumnail.
            thumbnail = Thumbnail.getDefaultThumbnail();
        }

        // Inform background task scheduler that we have some work to do
        ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL);
    }
    thumbReadyTime = System.currentTimeMillis();

    log.debug("starting to draw");
    // Find the position for the thumbnail
    BufferedImage img = thumbnail.getImage();
    if (img == null) {
        thumbnail = Thumbnail.getDefaultThumbnail();
        img = thumbnail.getImage();
    }

    float scaleX = ((float) thumbWidth) / ((float) img.getWidth());
    float scaleY = ((float) thumbHeight) / ((float) img.getHeight());
    float scale = Math.min(scaleX, scaleY);
    int w = (int) (img.getWidth() * scale);
    int h = (int) (img.getHeight() * scale);

    int x = startx + (columnWidth - w) / (int) 2;
    int y = starty + (rowHeight - h) / (int) 2;

    log.debug("drawing thumbnail");

    // Draw shadow
    int offset = isSelected ? 2 : 0;
    int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset };
    int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset };
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length);
    polyline.moveTo(shadowX[0], shadowY[0]);
    for (int index = 1; index < shadowX.length; index++) {
        polyline.lineTo(shadowX[index], shadowY[index]);
    }
    ;
    BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    Stroke oldStroke = g2.getStroke();
    g2.setStroke(shadowStroke);
    g2.setColor(Color.DARK_GRAY);
    g2.draw(polyline);
    g2.setStroke(oldStroke);

    // Paint thumbnail
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null);
    if (useOldThumbnail) {
        creatingThumbIcon.paintIcon(this, g2,
                startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2,
                starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2);
    }
    log.debug("Drawn, drawing decorations");
    if (isSelected) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(3.0f));
        g2.setColor(Color.BLUE);
        g2.drawRect(x, y, w, h);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
    }

    thumbDrawnTime = System.currentTimeMillis();

    boolean drawAttrs = (thumbWidth >= 100);
    if (drawAttrs) {
        // Increase ypos so that attributes are drawn under the image
        ypos += ((int) h) / 2 + 3;

        // Draw the attributes

        // Draw the qualoity icon to the upper left corner of the thumbnail
        int quality = photo.getQuality();
        if (showQuality && quality != 0) {
            int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2;
            for (int n = 0; n < quality; n++) {
                starIcon.paintIcon(this, g2, qx, ypos);
                qx += starIcon.getIconWidth();
            }
            ypos += starIcon.getIconHeight();
        }
        ypos += 6;

        if (photo.getRawSettings() != null) {
            // Draw the "RAW" icon
            int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5;
            int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5;
            rawIcon.paintIcon(this, g2, rx, ry);
        }
        if (photo.getHistory().getHeads().size() > 1) {
            // Draw the "unresolved conflicts" icon
            int rx = startx + (columnWidth + w - 10) / (int) 2 - 20;
            int ry = starty + (columnWidth - h - 10) / (int) 2;
            g2.setColor(Color.RED);
            g2.fillRect(rx, ry, 10, 10);
        }

        Color prevBkg = g2.getBackground();
        if (isSelected) {
            g2.setBackground(Color.BLUE);
        } else {
            g2.setBackground(this.getBackground());
        }
        Font attrFont = new Font("Arial", Font.PLAIN, 10);
        FontRenderContext frc = g2.getFontRenderContext();
        if (showDate && photo.getShootTime() != null) {
            FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy());

            String dateStr = fd.format();
            TextLayout txt = new TextLayout(dateStr, attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();
            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        String shootPlace = photo.getShootingPlace();
        if (showPlace && shootPlace != null && shootPlace.length() > 0) {
            TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();

            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        g2.setBackground(prevBkg);
    }
    endTime = System.currentTimeMillis();
    log.debug("paintThumbnail: exit " + photo.getUuid());
    log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms");
    log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms");
    log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms");
    log.debug("Total " + (endTime - startTime) + " ms");
}

From source file:org.sbs.util.ImageCompress.java

/**
 * ?//from  w  w w. j  a v  a 2 s  .co  m
 * 
 * @param source
 * @param targetW
 * @param targetH
 * @return
 */
public BufferedImage resize(BufferedImage source, int targetW, int targetH) {
    // targetWtargetH
    int desH = 0;
    int type = source.getType();
    BufferedImage target = null;
    double sx = (double) targetW / source.getWidth();
    double sy = sx;
    desH = (int) (sx * source.getHeight());
    if (desH < targetH) {
        desH = targetH;
        sy = (double) 61 / source.getHeight();
    }
    if (type == BufferedImage.TYPE_CUSTOM) { // handmade
        ColorModel cm = source.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(targetW, desH);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();
        target = new BufferedImage(cm, raster, alphaPremultiplied, null);
    } else
        target = new BufferedImage(targetW, desH, type);
    Graphics2D g = target.createGraphics();
    // smoother than exlax:
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
    g.dispose();
    return target;
}

From source file:org.silverpeas.core.io.media.image.thumbnail.control.ThumbnailController.java

protected static void createCropThumbnailFileOnServer(String pathOriginalFile, String pathCropdir,
        String pathCropFile, ThumbnailDetail thumbnail, int thumbnailWidth, int thumbnailHeight) {
    try {//from ww  w .j  ava  2 s . c o m
        // Creates folder if not exists
        File dir = new File(pathCropdir);
        if (!dir.exists()) {
            FileFolderManager.createFolder(pathCropdir);
        }
        // create empty file
        File cropFile = new File(pathCropFile);
        if (!cropFile.exists()) {
            Files.createFile(cropFile.toPath());
        }

        File originalFile = new File(pathOriginalFile);
        BufferedImage bufferOriginal = ImageIO.read(originalFile);
        // crop image
        BufferedImage cropPicture = bufferOriginal.getSubimage(thumbnail.getXStart(), thumbnail.getYStart(),
                thumbnail.getXLength(), thumbnail.getYLength());
        BufferedImage cropPictureFinal = new BufferedImage(thumbnailWidth, thumbnailHeight,
                BufferedImage.TYPE_INT_RGB);
        // Redimensionnement de l'image
        Graphics2D g2 = cropPictureFinal.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.drawImage(cropPicture, 0, 0, thumbnailWidth, thumbnailHeight, null);
        g2.dispose();

        // save crop image
        String extension = FilenameUtils.getExtension(originalFile.getName());
        ImageIO.write(cropPictureFinal, extension, cropFile);
    } catch (Exception e) {
        SilverLogger.getLogger(ThumbnailController.class).warn(e);
    }
}

From source file:org.squidy.designer.shape.VisualShape.java

@Override
protected final void paint(PPaintContext paintContext) {
    super.paint(paintContext);

    Graphics2D g = paintContext.getGraphics();

    // Set default font.
    g.setFont(internalFont);/*from w  w w . j a  va 2 s  .co m*/

    //      if (!renderingHintsSet) {
    if (isRenderPrimitive()) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    } else {
        // Use anti aliasing -> May slow down performance.
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
    //         renderingHintsSet = true;
    //      }

    // Paint the shapes visual representation.
    paintShape(paintContext);

    // Allows visual debugging if enabled.
    if (DebugConstants.ENABLED) {
        paintDebug(paintContext);
    }
}

From source file:org.vulpe.view.tags.Functions.java

/**
 * This method takes in an image as a byte array (currently supports GIF,
 * JPG, PNG and possibly other formats) and resizes it to have a width no
 * greater than the pMaxWidth parameter in pixels. It converts the image to
 * a standard quality JPG and returns the byte array of that JPG image.
 *
 * @param imageData/*from  w w  w. j a va  2s. c  om*/
 *            the image data.
 * @param maxWidth
 *            the max width in pixels, 0 means do not scale.
 * @return the resized JPG image.
 * @throws IOException
 *             if the image could not be manipulated correctly.
 */
public static byte[] resizeImageAsJPG(final byte[] imageData, final int maxWidth) throws IOException {
    // Create an ImageIcon from the image data
    final ImageIcon imageIcon = new ImageIcon(imageData);
    int width = imageIcon.getIconWidth();
    if (width == maxWidth) {
        return imageData;
    }
    int height = imageIcon.getIconHeight();
    LOG.debug("imageIcon width: " + width + "  height: " + height);
    // If the image is larger than the max width, we need to resize it
    if (maxWidth > 0 && width > maxWidth) {
        // Determine the shrink ratio
        final double ratio = (double) maxWidth / imageIcon.getIconWidth();
        LOG.debug("resize ratio: " + ratio);
        height = (int) (imageIcon.getIconHeight() * ratio);
        width = maxWidth;
        LOG.debug("imageIcon post scale width: " + width + "  height: " + height);
    }
    // Create a new empty image buffer to "draw" the resized image into
    final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // Create a Graphics object to do the "drawing"
    final Graphics2D g2d = bufferedImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    // Draw the resized image
    g2d.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
    g2d.dispose();
    // Now our buffered image is ready
    // Encode it as a JPEG
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
    encoder.encode(bufferedImage);
    return baos.toByteArray();
}

From source file:util.ui.UiUtilities.java

/**
 * Scales Icons to a specific size//from  ww w .j a  v a 2s .  c  o m
 *
 * @param icon
 *          Icon that should be scaled
 * @param width
 *          scaled width
 * @param height
 *          scaled height
 * @return Scaled Icon
 */
public static Icon scaleIcon(Icon icon, int width, int height) {
    if (icon == null) {
        return null;
    }
    int currentWidth = icon.getIconWidth();
    int currentHeight = icon.getIconHeight();
    if ((currentWidth == width) && (currentHeight == height)) {
        return icon;
    }
    try {
        // Create Image with Icon
        BufferedImage iconImage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = iconImage.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        AffineTransform z = g2.getTransform();
        g2.setTransform(z);
        icon.paintIcon(null, g2, 0, 0);
        g2.dispose();
        BufferedImage scaled = scaleDown(iconImage, width, height);
        // Return new Icon
        return new ImageIcon(scaled);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return icon;
}