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:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * this methode will load given image using tiles (saving memory)
 * //www  .j a  va  2 s  .  com
 * this strategie is spliting the original image up into smaller parts
 * called tiles. Those tiles are downscaled one by one using given quality.
 * This results int probably best possible quality but may cost a lot of
 * time.
 * 
 * @param reader -
 *            the reader to load image from
 * @param size -
 *            the resulting image size
 * @param quality -
 *            the quality used for necessary rendering
 * @return the image as buffered image
 * @throws IOException
 */
@SuppressWarnings("unused")
private static BufferedImage loadImageWithTiles(ImageReader reader, Dimension size, ImageQuality quality)
        throws IOException {

    // the image buffer used to load tiles
    ImageTypeSpecifier imageSpec = reader.getImageTypes(0).next();
    BufferedImage tile = imageSpec.createBufferedImage(IMAGE_TILE_SIZE.width, IMAGE_TILE_SIZE.height);

    // the image the result is rendered into
    BufferedImage result = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, quality.getHint());

    // prepaire image reader parameter
    ImageReadParam param = reader.getDefaultReadParam();
    param.setDestination(tile);

    // count tiles
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    int numX = (int) Math.ceil(width / (float) IMAGE_TILE_SIZE.width);
    int numY = (int) Math.ceil(height / (float) IMAGE_TILE_SIZE.height);

    float aspectX = (float) IMAGE_TILE_SIZE.width / width;
    float aspectY = (float) IMAGE_TILE_SIZE.height / height;

    // target tile dimension
    int targetTileWidth = (int) (size.width * aspectX);
    int targetTileHeight = (int) (size.height * aspectY);

    // load tiles
    Rectangle sourceRegion = new Rectangle();
    Rectangle targetRegion = new Rectangle();
    for (int i = 0; i < numX; i++) {
        // line increment
        sourceRegion.x = i * IMAGE_TILE_SIZE.width;
        sourceRegion.width = Math.min(IMAGE_TILE_SIZE.width, width - sourceRegion.x);
        targetRegion.x = i * targetTileWidth;
        targetRegion.width = Math.min(targetTileWidth, size.width - targetRegion.x);
        for (int j = 0; j < numY; j++) {
            // row increment
            sourceRegion.y = j * IMAGE_TILE_SIZE.height;
            sourceRegion.height = Math.min(IMAGE_TILE_SIZE.height, height - sourceRegion.y);
            targetRegion.y = j * targetTileHeight;
            targetRegion.height = Math.min(targetTileHeight, size.height - targetRegion.y);

            // performe read
            param.setSourceRegion(sourceRegion);
            reader.read(0, param);

            // insert into resulting image
            int dx1 = targetRegion.x;
            int dx2 = targetRegion.x + targetRegion.width;
            int dy1 = targetRegion.y;
            int dy2 = targetRegion.y + targetRegion.height;

            g.drawImage(tile, dx1, dy1, dx2, dy2, 0, 0, sourceRegion.width, sourceRegion.height, null);
        }
    }

    // finish drawing
    g.dispose();

    // return result
    return result;
}

From source file:org.lnicholls.galleon.util.Tools.java

public static Image getImage(URL url, int width, int height) {
    if (url != null) {
        // System.out.println(url);
        try {//from  w  ww . j ava 2 s  .  c  o  m
            Image internetImage = null;
            if (log.isDebugEnabled())
                log.debug("Downloading internet image=" + url.toExternalForm());

            class TimedThread implements Callable {
                private URL mUrl;

                public TimedThread(URL url) {
                    mUrl = url;
                }

                public synchronized java.lang.Object call() throws java.lang.Exception {
                    return new ImageTracker(mUrl).load();
                }
            }

            TimedCallable timedCallable = new TimedCallable(new TimedThread(url), 2000 * 60);
            internetImage = (Image) timedCallable.call();

            // System.out.println("internetImage="+internetImage);
            if (internetImage == null) {
                log.error("Invalid internet image: " + url.getPath());
            } else {
                // System.out.println("width="+width);
                // System.out.println("height="+height);
                if (width == -1)
                    width = internetImage.getWidth(null);
                if (height == -1)
                    height = internetImage.getHeight(null);

                // System.out.println("width="+width);
                // System.out.println("height="+height);

                Image image = null;
                if (internetImage instanceof BufferedImage) {
                    image = ImageManipulator.getScaledImage((BufferedImage) internetImage, width, height);
                    // System.out.println("image1="+image);
                } else {
                    try {
                        image = createBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                        Graphics2D graphics2D = ((BufferedImage) image).createGraphics();
                        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        graphics2D.drawImage(internetImage, 0, 0, width, height, null);
                        graphics2D.dispose();
                        graphics2D = null;
                        // System.out.println("image2="+image);
                    } catch (Throwable ex) {
                        // ex.printStackTrace();
                        image = internetImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                        // System.out.println("image3="+image);
                    }
                }
                internetImage.flush();
                internetImage = null;

                return image;
            }
        } catch (Throwable ex) {
            // ex.printStackTrace();
            Tools.logException(Tools.class, ex, url.toExternalForm());
        }
    }
    return null;
}

From source file:org.madsonic.controller.CoverArtController.java

public static BufferedImage videoScale(BufferedImage image, int width, int height) {

    BufferedImage thumb = image;//from w  w w  . j  a va  2 s. c  om

    BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = temp.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(thumb, 0, 0, width, height, null);
    g2.dispose();
    thumb = temp;

    return thumb;
}

From source file:org.madsonic.controller.CoverArtController.java

public static BufferedImage scale(BufferedImage image, int width, int height) {

    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage thumb = image;/*  w  w  w .ja  v  a 2s  .  co  m*/

    // For optimal results, use step by step bilinear resampling - halfing the size at each step.
    do {
        w /= 2;
        h /= 2;
        if (w < width) {
            w = width;
        }
        if (h < height) {
            h = height;
        }

        double thumbRatio = (double) width / (double) height;
        double aspectRatio = (double) w / (double) h;

        //            LOG.debug("## thumbsRatio: " + thumbRatio);
        //            LOG.debug("## aspectRatio: " + aspectRatio);

        if (thumbRatio < aspectRatio) {
            h = (int) (w / aspectRatio);
        } else {
            w = (int) (h * aspectRatio);
        }

        BufferedImage temp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = temp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(thumb, 0, 0, w, h, null);
        g2.dispose();

        thumb = temp;
    } while (w != width);

    //FIXME: check
    if (thumb.getHeight() > thumb.getWidth()) {
        thumb = thumb.getSubimage(0, 0, thumb.getWidth(), thumb.getWidth());
    }
    return thumb;
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * Convenience method that returns a scaled instance of the provided
 * {@code BufferedImage}.//from  w w w.java  2  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}
 * 
 *         This method has been taken from :
 *         http://today.java.net/pub/a/today
 *         /2007/04/03/perils-of-image-getscaledinstance.html
 * 
 * 
 */
public 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 = (BufferedImage) img;
    int width = 0;
    int height = 0;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        width = img.getWidth();
        height = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        width = targetWidth;
        height = targetHeight;
    }

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

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

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

        ret = tmp;
    } while (width != targetWidth || height != targetHeight);

    return ret;
}

From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java

/**
 * This code is very inspired on Chris Campbells article "The Perils of Image.getScaledInstance()"
 *
 * The article can be found here:/*from  w  w w .j  av  a  2 s.c om*/
 * http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
 *
 * Note that the filter method is threadsafe
 */
private static BufferedImage scaleFastTo(BufferedImage img, Size scaledSize) {
    if (!scaledSize.isChanged())
        return img;

    BufferedImage dest;
    if (img.getType() == BufferedImage.TYPE_CUSTOM) {
        dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
    } else {
        dest = new BufferedImage(scaledSize.getWidth(), scaledSize.getHeight(), img.getType());
    }

    int dstWidth = scaledSize.getWidth();
    int dstHeight = scaledSize.getHeight();

    BufferedImage ret = img;
    int w, h;

    // 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();

    int x = scaledSize.getXOffset();
    int y = scaledSize.getYOffset();

    //crop the image to see only the center of the image
    if (x > 0 || y > 0) {
        ret = img.getSubimage(x, y, w - (2 * x), h - (2 * y));
    }

    do {
        if (w > dstWidth) {
            if (x > 0) {
                x /= 2;
            }
            w /= 2;
            if (w < dstWidth) {
                w = dstWidth;
            }
        } else {
            w = dstWidth;
        }

        if (h > dstHeight) {
            h /= 2;
            if (h < dstHeight) {
                h = dstHeight;
            }
        } else {
            h = dstHeight;
        }

        BufferedImage tmp;
        if (dest.getWidth() == w && dest.getHeight() == h && w == dstWidth && h == dstHeight) {
            tmp = dest;
        } else {
            tmp = new BufferedImage(w, h, dest.getType());
        }

        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != dstWidth || h != dstHeight);

    return ret;
}

From source file:org.openbravo.erpCommon.utility.Utility.java

/**
 * Resize an image giving the image input as byte[]
 * /*from   www.  j  a  v  a  2  s  .  co m*/
 * @param bytea
 *          The contents of the image as a byte array
 * @param maxW
 *          Maximum width that the image will be resized.
 * @param maxH
 *          Maximum height that the image will be resized.
 * @param maintainAspectRatio
 *          If true, the image will be resized exactly to the maximum parameters. If false, the
 *          imagen will be resized closest to the maximum parameters keeping aspect ratio
 * @param canMakeLargerImage
 *          If true and the original image is smaller than maximum parameters, the resized image
 *          could be larger than the original one. If false, not.
 * @return The resized image
 */
public static byte[] resizeImageByte(byte[] bytea, int maxW, int maxH, boolean maintainAspectRatio,
        boolean canMakeLargerImage) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(bytea);
    BufferedImage rImage = ImageIO.read(bis);
    int newW = maxW;
    int newH = maxH;
    int oldW = rImage.getWidth();
    int oldH = rImage.getHeight();
    if (newW == 0 && newH == 0) {
        return bytea;
    } else if (newW == 0) {
        if (maintainAspectRatio) {
            newW = 99999;
        } else {
            newW = oldW;
        }
    } else if (newH == 0) {
        if (maintainAspectRatio) {
            newH = 99999;
        } else {
            newH = oldH;
        }
    }
    if (oldW == newW && oldH == newH) {
        return bytea;
    }
    if (!canMakeLargerImage && newW > oldW && newH > oldH) {
        return bytea;
    }
    if (maintainAspectRatio) {
        float oldRatio = (float) oldW / (float) oldH;
        float newRatio = (float) newW / (float) newH;
        if (oldRatio < newRatio) {
            newW = (int) (newH * oldRatio);
        } else if (oldRatio > newRatio) {
            newH = (int) (newW / oldRatio);
        }
    }
    BufferedImage dimg = new BufferedImage(newW, newH, rImage.getType());
    Graphics2D g = dimg.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(rImage, 0, 0, newW, newH, 0, 0, oldW, oldH, null);
    g.dispose();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(bytea);
    if (mimeType.contains("jpeg")) {
        mimeType = "jpeg";
    } else if (mimeType.contains("png")) {
        mimeType = "png";
    } else if (mimeType.contains("gif")) {
        mimeType = "gif";
    } else if (mimeType.contains("bmp")) {
        mimeType = "bmp";
    } else {
        return bytea;
    }
    ImageIO.write(dimg, mimeType, baos);
    byte[] bytesOut = baos.toByteArray();
    return bytesOut;
}

From source file:org.openstreetmap.gui.jmapviewer.Tile.java

/**
 * Creates a image for the current Tile// ww  w .  j av  a2  s.c om
 * 
 * @param image2
 *            origin
 * @param imageW
 *            width for the tile
 * @param imageH
 *            heigth for the tile
 */
private void createGraphicsFromImage(BufferedImage image2, int imageW, int imageH) {
    BufferedImage unScaledImage = image2;

    // Create new (blank) image of required (scaled) size
    BufferedImage scaledImage = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_ARGB);

    image = scaledImage;

    // Paint scaled version of image to new image
    Graphics2D graphics2D = scaledImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(unScaledImage, 0, 0, imageW, imageH, null);

    // clean up
    graphics2D.dispose();
}

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.//from www  .ja  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.layout.output.RenderUtility.java

public static Image scaleImage(final Image img, final int targetWidth, final int targetHeight,
        final Object hintValue, final boolean higherQuality) {
    final int type = BufferedImage.TYPE_INT_ARGB;

    Image ret = img;//w ww . j a v  a2 s.c  o m
    int w;
    int h;
    do {

        if (higherQuality) {
            final int imageWidth = ret.getWidth(null);
            final int imageHeight = ret.getHeight(null);
            if (imageWidth < targetWidth) {
                // This is a up-scale operation.
                w = Math.min(imageWidth << 1, targetWidth);
            } else if (imageWidth > targetWidth) {
                // downscale
                w = Math.max(imageWidth >> 1, targetWidth);
            } else {
                w = imageWidth;
            }

            if (imageHeight < targetHeight) {
                // This is a up-scale operation.
                h = Math.min(imageHeight << 1, targetHeight);
            } else if (imageHeight > targetHeight) {
                // downscale
                h = Math.max(imageHeight >> 1, targetHeight);
            } else {
                h = imageHeight;
            }
        } else {
            w = targetWidth;
            h = targetHeight;
        }

        final BufferedImage tmp = new BufferedImage(w, h, type);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hintValue);
        // this one scales the image ..
        if (ret instanceof BufferedImage) {
            if (g2.drawImage(ret, 0, 0, w, h, null) == false) {
                logger.debug("Failed to scale the image. This should not happen.");
            }
        } else {
            final WaitingImageObserver obs = new WaitingImageObserver(ret);
            while (g2.drawImage(ret, 0, 0, w, h, null) == false) {
                obs.waitImageLoaded();
                if (obs.isError()) {
                    logger.warn("Error while loading the image during the rendering.");
                    break;
                }
            }

        }
        g2.dispose();

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

    return ret;
}