Example usage for java.awt RenderingHints KEY_INTERPOLATION

List of usage examples for java.awt RenderingHints KEY_INTERPOLATION

Introduction

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

Prototype

Key KEY_INTERPOLATION

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

Click Source Link

Document

Interpolation hint key.

Usage

From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java

/**
 * Convenience method that returns a scaled instance of the provided {@link BufferedImage}.
 * //w w  w  . j ava 2 s.  co  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 {@link BufferedImage}
 */
public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint,
        boolean higherQuality) {
    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    int w, 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;
            }
        }
        BufferedImage tmp = new BufferedImage(w, h, type);
        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:IconDemoApp.java

/**
 * Resizes an image using a Graphics2D object backed by a BufferedImage.
 * /*from w  w  w. j a v  a 2  s.  co  m*/
 * @param srcImg -
 *            source image to scale
 * @param w -
 *            desired width
 * @param h -
 *            desired height
 * @return - the new resized image
 */
private Image getScaledImage(Image srcImg, int w, int h) {
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}

From source file:dcstore.web.ImagesWeb.java

private void resizeImage(String inPath, int w, int h, String outPath) {
    try {/*  ww w  .  ja  v a 2s  . c  o m*/
        BufferedImage originalImage = ImageIO.read(new File(inPath));
        int ow, oh;
        ow = originalImage.getWidth();
        oh = originalImage.getHeight();
        double ratio = (double) ow / (double) oh;
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        int ch = (int) Math.round(w / ratio);

        BufferedImage resizedImage = new BufferedImage(w, h, type);
        Graphics2D g = resizedImage.createGraphics();
        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.setColor(Color.white);
        g.fillRect(0, 0, w, h);
        g.drawImage(originalImage, 0, (int) (((float) h - (float) ch) / 2), w, ch, null);
        g.dispose();
        ImageIO.write(resizedImage, "jpg", new File(outPath));
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage("",
                new FacesMessage("Error while resizeing image: " + e.getMessage()));
    }
}

From source file:ScaleTest_2008.java

/**
 * Scale the image to several smaller sizes using each of the approaches
 * and time each series of operations. The times are output into the
 * application window for each row that they represent.
 *//*from  w  w  w  .j a v  a 2s. c  o  m*/
protected void paintComponent(Graphics g) {
    if (!originalImagePainted) {
        paintOriginalImage();
    }
    long startTime, endTime, totalTime;
    int xLoc, yLoc;

    // Draw scaled versions with nearest neighbor
    xLoc = 5;
    yLoc = 20;
    startTime = System.nanoTime();
    drawImage(g, yLoc, false);
    endTime = System.nanoTime();
    totalTime = (endTime - startTime) / 1000000;
    g.drawString("NEAREST ", xLoc, yLoc + (FULL_SIZE / 2));
    g.drawString(Long.toString(totalTime) + " ms", xLoc, yLoc + (FULL_SIZE / 2) + 15);
    System.out.println("NEAREST: " + (endTime - startTime) / 1000000);

    // BILINEAR
    yLoc += FULL_SIZE + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    startTime = System.nanoTime();
    drawImage(g, yLoc, false);
    endTime = System.nanoTime();
    totalTime = (endTime - startTime) / 1000000;
    g.drawString("BILINEAR ", xLoc, yLoc + (FULL_SIZE / 2));
    g.drawString(Long.toString(totalTime) + " ms", xLoc, yLoc + (FULL_SIZE / 2) + 15);
    System.out.println("BILINEAR: " + (endTime - startTime) / 1000000);

    // BIDUBIC
    yLoc += FULL_SIZE + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    startTime = System.nanoTime();
    drawImage(g, yLoc, false);
    endTime = System.nanoTime();
    totalTime = (endTime - startTime) / 1000000;
    g.drawString("BICUBIC ", xLoc, yLoc + (FULL_SIZE / 2));
    g.drawString(Long.toString(totalTime) + " ms", xLoc, yLoc + (FULL_SIZE / 2) + 15);
    System.out.println("BICUBIC: " + (endTime - startTime) / 1000000);

    // getScaledInstance()
    yLoc += FULL_SIZE + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    startTime = System.nanoTime();
    drawImage(g, yLoc, true);
    endTime = System.nanoTime();
    totalTime = (endTime - startTime) / 1000000;
    g.drawString("getScaled ", xLoc, yLoc + (FULL_SIZE / 2));
    g.drawString(Long.toString(totalTime) + " ms", xLoc, yLoc + (FULL_SIZE / 2) + 15);
    System.out.println("getScaled: " + (endTime - startTime) / 1000000);

    // Progressive Bilinear
    yLoc += FULL_SIZE + PADDING;
    startTime = System.nanoTime();
    drawBetterImage(g, yLoc);
    endTime = System.nanoTime();
    totalTime = (endTime - startTime) / 1000000;
    g.drawString("Progressive ", xLoc, yLoc + (FULL_SIZE / 2));
    g.drawString(Long.toString(totalTime) + " ms", xLoc, yLoc + (FULL_SIZE / 2) + 15);
    System.out.println("faster: " + (endTime - startTime) / 1000000);

    // Draw image sizes
    xLoc = 100;
    int delta = (int) (SCALE_FACTOR * FULL_SIZE);
    for (int scaledSize = FULL_SIZE; scaledSize > 0; scaledSize -= delta) {
        g.drawString(scaledSize + " x " + scaledSize, xLoc + Math.max(0, scaledSize / 2 - 20), 15);
        xLoc += scaledSize + 20;
    }
}

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.  j  a  va2s. co  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:ch.entwine.weblounge.preview.jai.JAIPreviewGenerator.java

/**
 * Resizes the given image to what is defined by the image style and writes
 * the result to the output stream.//w w w  .  ja  v a2s  .  c  om
 * 
 * @param is
 *          the input stream
 * @param os
 *          the output stream
 * @param format
 *          the image format
 * @param style
 *          the style
 * @throws IllegalArgumentException
 *           if the image is in an unsupported format
 * @throws IllegalArgumentException
 *           if the input stream is empty
 * @throws IOException
 *           if reading from or writing to the stream fails
 * @throws OutOfMemoryError
 *           if the image is too large to be processed in memory
 */
private void style(InputStream is, OutputStream os, String format, ImageStyle style)
        throws IllegalArgumentException, IOException, OutOfMemoryError {

    // Does the input stream contain any data?
    if (is.available() == 0)
        throw new IllegalArgumentException("Empty input stream was passed to image styling");

    // Do we need to do any work at all?
    if (style == null || ImageScalingMode.None.equals(style.getScalingMode())) {
        logger.trace("No scaling needed, performing a noop stream copy");
        IOUtils.copy(is, os);
        return;
    }

    SeekableStream seekableInputStream = null;
    RenderedOp image = null;
    try {
        // Load the image from the given input stream
        seekableInputStream = new FileCacheSeekableStream(is);
        image = JAI.create("stream", seekableInputStream);
        if (image == null)
            throw new IOException("Error reading image from input stream");

        // Get the original image size
        int imageWidth = image.getWidth();
        int imageHeight = image.getHeight();

        // Resizing
        float scale = ImageStyleUtils.getScale(imageWidth, imageHeight, style);

        RenderingHints scaleHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        scaleHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        scaleHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        scaleHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        int scaledWidth = Math.round(scale * image.getWidth());
        int scaledHeight = Math.round(scale * image.getHeight());
        int cropX = 0;
        int cropY = 0;

        // If either one of scaledWidth or scaledHeight is < 1.0, then
        // the scale needs to be adapted to scale to 1.0 exactly and accomplish
        // the rest by cropping.

        if (scaledWidth < 1.0f) {
            scale = 1.0f / imageWidth;
            scaledWidth = 1;
            cropY = imageHeight - scaledHeight;
            scaledHeight = Math.round(imageHeight * scale);
        } else if (scaledHeight < 1.0f) {
            scale = 1.0f / imageHeight;
            scaledHeight = 1;
            cropX = imageWidth - scaledWidth;
            scaledWidth = Math.round(imageWidth * scale);
        }

        if (scale > 1.0) {
            ParameterBlock scaleParams = new ParameterBlock();
            scaleParams.addSource(image);
            scaleParams.add(scale).add(scale).add(0.0f).add(0.0f);
            scaleParams.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2));
            image = JAI.create("scale", scaleParams, scaleHints);
        } else if (scale < 1.0) {
            ParameterBlock subsampleAverageParams = new ParameterBlock();
            subsampleAverageParams.addSource(image);
            subsampleAverageParams.add(Double.valueOf(scale));
            subsampleAverageParams.add(Double.valueOf(scale));
            image = JAI.create("subsampleaverage", subsampleAverageParams, scaleHints);
        }

        // Cropping
        cropX = (int) Math.max(cropX,
                (float) Math.ceil(ImageStyleUtils.getCropX(scaledWidth, scaledHeight, style)));
        cropY = (int) Math.max(cropY,
                (float) Math.ceil(ImageStyleUtils.getCropY(scaledWidth, scaledHeight, style)));

        if ((cropX > 0 && Math.floor(cropX / 2.0f) > 0) || (cropY > 0 && Math.floor(cropY / 2.0f) > 0)) {

            ParameterBlock cropTopLeftParams = new ParameterBlock();
            cropTopLeftParams.addSource(image);
            cropTopLeftParams.add(cropX > 0 ? ((float) Math.floor(cropX / 2.0f)) : 0.0f);
            cropTopLeftParams.add(cropY > 0 ? ((float) Math.floor(cropY / 2.0f)) : 0.0f);
            cropTopLeftParams.add(scaledWidth - Math.max(cropX, 0.0f)); // width
            cropTopLeftParams.add(scaledHeight - Math.max(cropY, 0.0f)); // height

            RenderingHints croppingHints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                    BorderExtender.createInstance(BorderExtender.BORDER_COPY));

            image = JAI.create("crop", cropTopLeftParams, croppingHints);
        }

        // Write resized/cropped image encoded as JPEG to the output stream
        ParameterBlock encodeParams = new ParameterBlock();
        encodeParams.addSource(image);
        encodeParams.add(os);
        encodeParams.add("jpeg");
        JAI.create("encode", encodeParams);

    } catch (Throwable t) {
        if (t.getClass().getName().contains("ImageFormat")) {
            throw new IllegalArgumentException(t.getMessage());
        }
    } finally {
        IOUtils.closeQuietly(seekableInputStream);
        if (image != null)
            image.dispose();
    }
}

From source file:com.sun.socialsite.util.ImageUtil.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}./*from   ww  w .  j  a  va  2s .c  om*/
 *
 * NOTE: Adapted from code at
 * {@link http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html}.
 *
 * @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}
 */
private static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight,
        Object hint, boolean higherQuality) {
    int type = BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = (BufferedImage) img;
    int w, 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;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        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:de.inren.service.picture.PictureModificationServiceImpl.java

private BufferedImage scaleImage(File orginal, final int max) throws IOException {
    // Load the image.
    BufferedImage originalImage = ImageIO.read(orginal);

    // Figure out the new dimensions.
    final int w = originalImage.getWidth();
    final int h = originalImage.getHeight();
    final double maxOriginal = Math.max(w, h);
    final double scaling = max / maxOriginal;

    final int newW = (int) Math.round(scaling * w);
    final int newH = (int) Math.round(scaling * h);

    // If we need to scale down by more than 2x, scale to double the
    // eventual size and then scale again. This provides much higher
    // quality results.
    if (scaling < 0.5f) {
        final BufferedImage newImg = new BufferedImage(newW * 2, newH * 2, BufferedImage.TYPE_INT_RGB);
        final Graphics2D gfx = newImg.createGraphics();
        gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        gfx.drawImage(originalImage, 0, 0, newW * 2, newH * 2, null);
        gfx.dispose();/*  ww  w  .  j a  v a  2s.c om*/
        newImg.flush();
        originalImage = newImg;
    }

    // Scale it.
    BufferedImage newImg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB);
    final Graphics2D gfx = newImg.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gfx.drawImage(originalImage, 0, 0, newW, newH, null);
    gfx.dispose();
    newImg.flush();
    originalImage.flush();

    return newImg;
}

From source file:gg.msn.ui.panel.MainPanel.java

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    super.paintComponent(g2d);
    g2d.setRenderingHints(//w  ww .j  av  a2 s . c  om
            new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR));

    try {

        ImageIcon icon = ThemeManager.getTheme().get(ThemeManager.MAIN_BACKGROUND);

        if (icon != null) {
            Image image = icon.getImage();
            g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        } else {
            log.warn("image " + icon.getDescription() + " not Found");
        }

        icon = ThemeManager.getTheme().get(ThemeManager.MAIN_IMAGE);

        if (icon != null) {

            Image cartel = icon.getImage();
            g2d.drawImage(cartel, 0 - cartel.getWidth(this) / 10, getHeight() - cartel.getHeight(this), this);
        } else {
            log.warn("image " + icon.getDescription() + " not Found");
        }
    } catch (Exception e) {
        //            log.error(e);
    }
}