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:com.sun.socialsite.util.ImageUtil.java

public static BufferedImage getScaledImage(BufferedImage origImage, Integer desiredWidth, Integer desiredHeight)
        throws IOException {

    if (origImage == null) {
        return null;
    }/*from  w ww.j a  va 2  s .co  m*/

    if (desiredWidth == null) {
        desiredWidth = origImage.getWidth();
    }

    if (desiredHeight == null) {
        desiredHeight = origImage.getHeight();
    }

    int origWidth = origImage.getWidth();
    int origHeight = origImage.getHeight();

    double ratio = Math.min((((double) desiredWidth) / origWidth), (((double) desiredHeight) / origHeight));

    int extraWidth = desiredWidth - ((int) (origWidth * ratio));
    int extraHeight = desiredHeight - ((int) (origHeight * ratio));

    int tmpWidth = (desiredWidth - extraWidth);
    int tmpHeight = (desiredHeight - extraHeight);
    BufferedImage tmpImage = getScaledInstance(origImage, tmpWidth, tmpHeight,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC, true);

    log.debug(String.format("tmpImage[width=%d height=%d", tmpImage.getWidth(), tmpImage.getHeight()));

    if ((tmpImage.getWidth() == desiredWidth) && (tmpImage.getHeight() == desiredHeight)) {
        return tmpImage;
    } else {
        BufferedImage scaledImage = new BufferedImage(desiredWidth, desiredHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);

        // We recalculate these in case scaling didn't quite hit its targets
        extraWidth = desiredWidth - tmpImage.getWidth();
        extraHeight = desiredHeight - tmpImage.getHeight();

        int dx1 = extraWidth / 2;
        int dy1 = extraHeight / 2;
        int dx2 = desiredWidth - dx1;
        int dy2 = desiredWidth - dy1;

        // transparent background
        g2d.setColor(new Color(0, 0, 0, 0));
        g2d.fillRect(0, 0, desiredWidth, desiredHeight);

        g2d.drawImage(tmpImage, dx1, dy1, dx2, dy2, null);
        return scaledImage;
    }
}

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

/**
 * @param bufInputStream//from  ww  w .ja  va 2 s .  com
 * @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:ImageBouncer.java

protected void setBilinear(Graphics2D g2) {
    if (mBilinear == false)
        return;// w  w  w. ja v a2  s  .c  om
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
}

From source file:PictureScaler.java

/**
 * Render all scaled versions 10 times, timing each version and 
 * reporting the results below the appropriate scaled image.
 *///w w  w.j a v  a  2s  .c om
protected void paintComponent(Graphics g) {
    // Scale with NEAREST_NEIGHBOR
    int xLoc = PADDING, yLoc = PADDING;
    long startTime, endTime;
    float totalTime;
    int iterations = 10;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("NEAREST ", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("NEAREST: " + ((endTime - startTime) / 1000000));

    // Scale with BILINEAR
    xLoc += scaleW + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("BILINEAR", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("BILINEAR: " + ((endTime - startTime) / 1000000));

    // Scale with BICUBIC
    xLoc += scaleW + PADDING;
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        g.drawImage(picture, xLoc, yLoc, scaleW, scaleH, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("BICUBIC", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("BICUBIC: " + ((endTime - startTime) / 1000000));

    // Scale with getScaledInstance
    xLoc += scaleW + PADDING;
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        Image scaledPicture = picture.getScaledInstance(scaleW, scaleH, Image.SCALE_AREA_AVERAGING);
        g.drawImage(scaledPicture, xLoc, yLoc, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("getScaled", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("getScaled: " + ((endTime - startTime) / 1000000));

    // Scale with Progressive Bilinear
    xLoc += scaleW + PADDING;
    startTime = System.nanoTime();
    for (int i = 0; i < iterations; ++i) {
        Image scaledPicture = getFasterScaledInstance(picture, scaleW, scaleH,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
        g.drawImage(scaledPicture, xLoc, yLoc, null);
    }
    endTime = System.nanoTime();
    totalTime = (float) ((endTime - startTime) / 1000000) / iterations;
    g.drawString("Progressive", xLoc, yLoc + scaleH + PADDING);
    g.drawString(Float.toString(totalTime) + " ms", xLoc, yLoc + scaleH + PADDING + 10);
    System.out.println("Progressive: " + ((endTime - startTime) / 1000000));
}

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();//from   w  ww.  j a  v a  2s.  co  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:com.flexive.shared.media.impl.FxMediaNativeEngine.java

public static BufferedImage scale(BufferedImage bi, int width, int height) {
    BufferedImage bi2;// w  w w  .j  a va2 s . c o m
    int scaleWidth = bi.getWidth(null);
    int scaleHeight = bi.getHeight(null);
    double scaleX = (double) width / scaleWidth;
    double scaleY = (double) height / scaleHeight;
    double scale = Math.min(scaleX, scaleY);
    scaleWidth = (int) ((double) scaleWidth * scale);
    scaleHeight = (int) ((double) scaleHeight * scale);
    Image scaledImage;
    if (HEADLESS) {
        // create a new buffered image, don't rely on a local graphics system (headless mode)
        final int type;
        if (bi.getType() != BufferedImage.TYPE_CUSTOM) {
            type = bi.getType();
        } else if (bi.getAlphaRaster() != null) {
            // alpha channel available
            type = BufferedImage.TYPE_INT_ARGB;
        } else {
            type = BufferedImage.TYPE_INT_RGB;
        }
        bi2 = new BufferedImage(scaleWidth, scaleHeight, type);
    } else {
        GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        bi2 = gc.createCompatibleImage(scaleWidth, scaleHeight, bi.getTransparency());
    }
    Graphics2D g = bi2.createGraphics();
    if (scale < 0.3 && Math.max(scaleWidth, scaleHeight) < 500) {
        scaledImage = bi.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
        new ImageIcon(scaledImage).getImage();
        g.drawImage(scaledImage, 0, 0, scaleWidth, scaleHeight, null);
    } else {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawImage(bi, 0, 0, scaleWidth, scaleHeight, null);
    }
    g.dispose();
    return bi2;
}

From source file:ddf.catalog.transformer.input.pdf.PdfInputTransformer.java

private byte[] generatePdfThumbnail(PDDocument pdfDocument) throws IOException {

    PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);

    if (pdfDocument.getNumberOfPages() < 1) {
        /*//from w  w w .  j a va 2  s . com
         * Can there be a PDF with zero pages??? Should we throw an error or what? The
         * original implementation assumed that a PDF would always have at least one
         * page. That's what I've implemented here, but I don't like make those
         * kinds of assumptions :-( But I also don't want to change the original
         * behavior without knowing how it will impact the system.
         */
    }

    PDPage page = pdfDocument.getPage(0);

    BufferedImage image = pdfRenderer.renderImageWithDPI(0, RESOLUTION_DPI, ImageType.RGB);

    int largestDimension = Math.max(image.getHeight(), image.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (image.getHeight() * scalingFactor);
    int scaledWidth = (int) (image.getWidth() * scalingFactor);

    BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics = scaledImage.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
    graphics.dispose();

    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        ImageIOUtil.writeImage(scaledImage, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
        return outputStream.toByteArray();
    }
}

From source file:ddf.catalog.transformer.input.pptx.PptxInputTransformer.java

/**
 * If the slide show doesn't contain any slides, then return null. Otherwise, return jpeg
 * image data of the first slide in the deck.
 *
 * @param slideShow//w  w  w .  j  a v a2s  .c om
 * @return jpeg thumbnail or null if thumbnail can't be created
 * @throws IOException
 */
private byte[] generatePptxThumbnail(XMLSlideShow slideShow) throws IOException {

    if (slideShow.getSlides().isEmpty()) {
        LOGGER.info("the powerpoint file does not contain any slides, skipping thumbnail generation");
        return null;
    }

    Dimension pgsize = slideShow.getPageSize();

    int largestDimension = (int) Math.max(pgsize.getHeight(), pgsize.getWidth());
    float scalingFactor = IMAGE_HEIGHTWIDTH / largestDimension;
    int scaledHeight = (int) (pgsize.getHeight() * scalingFactor);
    int scaledWidth = (int) (pgsize.getWidth() * scalingFactor);
    BufferedImage img = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D graphics = img.createGraphics();

    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_ON);

        graphics.scale(scalingFactor, scalingFactor);

        slideShow.getSlides().get(0).draw(graphics);

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIOUtil.writeImage(img, FORMAT_NAME, outputStream, RESOLUTION_DPI, IMAGE_QUALITY);
            return outputStream.toByteArray();
        }
    } catch (RuntimeException e) {
        if (e.getCause() instanceof javax.imageio.IIOException) {
            LOGGER.warn("unable to generate thumbnail for PPTX file", e);
        } else {
            throw e;
        }
    } finally {
        graphics.dispose();
    }

    return null;
}

From source file:FileUtils.java

/**
 * Convenience method that returns a scaled instance of the
 * provided {@code BufferedImage}./*from   w  ww.  ja  va  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}
 */
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 = (BufferedImage) 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:com.partagames.imageresizetool.SimpleImageResizeTool.java

/**
 * Scales an image to the desired dimensions.
 *
 * @param img  Original image/*from  w  w  w.ja v  a 2 s .  com*/
 * @param newW Target width
 * @param newH Target height
 * @return Scaled image
 */
public static BufferedImage scale(BufferedImage img, int newW, int newH) {
    int w = img.getWidth();
    int h = img.getHeight();
    final BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
    final Graphics2D g = dimg.createGraphics();

    // use provided rendering hint, default is bilinear 
    switch (scalingHint) {
    case "n":
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        break;
    case "b":
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        break;
    }

    g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
    g.dispose();
    return dimg;
}