Example usage for java.awt.image BufferedImage getScaledInstance

List of usage examples for java.awt.image BufferedImage getScaledInstance

Introduction

In this page you can find the example usage for java.awt.image BufferedImage getScaledInstance.

Prototype

public Image getScaledInstance(int width, int height, int hints) 

Source Link

Document

Creates a scaled version of this image.

Usage

From source file:davmail.util.IOUtil.java

/**
 * Resize image to a max width or height image size.
 *
 * @param inputImage input image//from   ww  w  .  j av  a 2 s.co  m
 * @param max        max size
 * @return scaled image
 */
public static BufferedImage resizeImage(BufferedImage inputImage, int max) {
    int width = inputImage.getWidth();
    int height = inputImage.getHeight();
    int targetWidth;
    int targetHeight;
    if (width <= max && height <= max) {
        return inputImage;
    } else if (width > height) {
        targetWidth = max;
        targetHeight = targetWidth * height / width;
    } else {
        targetHeight = max;
        targetWidth = targetHeight * width / height;
    }
    Image scaledImage = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
    BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    targetImage.getGraphics().drawImage(scaledImage, 0, 0, null);
    return targetImage;
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

private static BufferedImage toThumbnailSize(BufferedImage image) {
    final int w = image.getWidth();
    final int h = image.getHeight();
    final int max = Math.max(w, h);
    if (max <= 256) {
        return image;
    }//from  w w w . ja v  a  2  s . co  m
    final double s = max / 256d;
    final BufferedImage result = new BufferedImage(Math.max((int) Math.min(w / s, 256), 1),
            Math.max((int) Math.min(h / s, 256), 1), BufferedImage.TYPE_INT_BGR);
    final Graphics2D graphics = result.createGraphics();
    try {
        graphics.drawImage(image.getScaledInstance(result.getWidth(), result.getHeight(), Image.SCALE_SMOOTH),
                0, 0, null);
    } finally {
        graphics.dispose();
    }
    return result;
}

From source file:fr.msch.wissl.server.Library.java

public static String resizeArtwork(String artPath) throws IOException {
    BufferedImage orig = ImageIO.read(new File(artPath));

    if (orig == null) {
        throw new IOException("Failed to open image");
    }/* ww  w . j a  v  a  2  s .c o m*/
    Image sc = orig.getScaledInstance(70, 70, Image.SCALE_SMOOTH);

    BufferedImage scaled = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = scaled.createGraphics();
    g.drawImage(sc, 0, 0, 70, 70, null);
    g.dispose();

    File ret = new File(artPath + "_SCALED.jpg");
    ImageIO.write(scaled, "JPG", ret);

    return ret.getAbsolutePath();
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Creates the thumbnail.//from   w  ww . j ava2  s.c  o  m
 *
 * @param imageFile the image file
 * @param thumbFile the empty thumbnail file
 * @param thumbX the width of the thumbnail
 * @param thumbY the height of the thumbnail
 * @param imageName the image file name with extension
 * @param tolerance the percentage of tolerance before creating a thumbnail
 * @return true is the thumbnail has been created, false otherwise
 * @throws IOException if an error occurs
 */
private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName,
        double tolerance) throws IOException {

    FileInputStream fileis = null;
    ImageInputStream imageis = null;

    Iterator readers = null;

    try {

        readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1));
        if (readers == null || (!readers.hasNext())) {
            throw new IOException("File not supported");
        }

        ImageReader reader = (ImageReader) readers.next();

        fileis = new FileInputStream(imageFile);
        imageis = ImageIO.createImageInputStream(fileis);
        reader.setInput(imageis, true);

        // Determines thumbnail height, width and quality
        int thumbWidth = thumbX;
        int thumbHeight = thumbY;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = reader.getWidth(0);
        int imageHeight = reader.getHeight(0);

        //
        // Don't create the thumbnail if the original file is smaller
        // than required size increased by % tolerance
        //
        if (imageWidth <= (thumbWidth * (1 + tolerance / 100))
                && imageHeight <= (thumbHeight * (1 + tolerance / 100))) {

            return false;
        }

        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }

        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(3, 3, 0, 0);

        BufferedImage bi = reader.read(0, param);

        Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH);

        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(thumb, 0, 0, thumbWidth, thumbHeight, null);

        FileOutputStream fileOutputStream = new FileOutputStream(thumbFile);
        ImageIO.write(thumbImage, "jpg", fileOutputStream);

        thumb.flush();
        thumbImage.flush();
        fileOutputStream.flush();
        fileOutputStream.close();
        graphics2D.dispose();

    } finally {
        if (fileis != null) {
            fileis.close();
        }
        if (imageis != null) {
            imageis.close();
        }
    }

    return true;
}

From source file:util.ui.UiUtilities.java

/**
 * Scales an image to a specific size and returns an BufferedImage
 *
 * @param img/*from  w w w. jav  a 2 s.  co m*/
 *          Scale this image
 * @param width
 *          new width
 * @param height
 *          new height
 * @param type The type of the image.
 * @return Scaled BufferedImage
 *
 * @since 3.0
 */
public static BufferedImage scaleIconToBufferedImage(BufferedImage img, int width, int height, int type,
        Color backgroundColor) {
    // Scale Image
    Image image = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    BufferedImage im = new BufferedImage(width, height, type);

    Graphics2D g2 = im.createGraphics();
    if (backgroundColor != null) {
        g2.setColor(backgroundColor);
        g2.fillRect(0, 0, width, height);
    }

    g2.drawImage(image, null, null);
    g2.dispose();

    im.flush();
    return im;

}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * ?????????/* www.  j a v  a 2s.  c  o m*/
 * 
 * @param imgfile
 * @param dim
 * @return
 */
public static BufferedImage shrinkImage(BufferedImage imgfile, int width, int height) {

    int iwidth = imgfile.getWidth();
    int iheight = imgfile.getHeight();

    double ratio = Math.min((double) width / (double) iwidth, (double) height / (double) iheight);
    int shrinkedWidth = (int) (iwidth * ratio);
    int shrinkedHeight = (int) (iheight * ratio);

    // ??
    Image targetImage = imgfile.getScaledInstance(shrinkedWidth, shrinkedHeight, Image.SCALE_AREA_AVERAGING);
    BufferedImage tmpImage = new BufferedImage(targetImage.getWidth(null), targetImage.getHeight(null),
            BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = tmpImage.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, shrinkedWidth, shrinkedHeight);
    g.drawImage(targetImage, 0, 0, null);

    return tmpImage;
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) into rez parameter
  * @param image input image for scaling
 * @param rez resulting image. must have required width and height
 * @throws IOException/*from www . java2 s  . co m*/
  */
public static void getScaledImageDimmension(BufferedImage image, BufferedImage rez) throws IOException {
    Graphics2D g2 = rez.createGraphics();
    if (rez.getHeight() > image.getHeight() || rez.getWidth() > image.getWidth()) {
        //rez image is bigger no resize
        g2.drawImage(image, 0, 0, null);
        return;
    }
    //1-st getting first side to resize (width or height)
    double scale_factor;
    if (getScaling(image.getHeight(), rez.getHeight()) > getScaling(image.getWidth(), rez.getWidth())) {
        //resize height
        scale_factor = getScaling(image.getHeight(), rez.getHeight());
        int width = (int) (scale_factor * image.getWidth());
        //cut width
        int x = (rez.getWidth() - width) / 2;
        g2.drawImage(image.getScaledInstance(width, rez.getHeight(), Image.SCALE_SMOOTH), x, 0, null);
        //System.out.println("resizing height: h="+image.getHeight()+"/"+rez.getHeight()+"; x="+x);
    } else {
        //resize width
        scale_factor = getScaling(image.getWidth(), rez.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //cut height
        int y = (rez.getHeight() - height) / 2;
        g2.drawImage(image.getScaledInstance(rez.getWidth(), height, Image.SCALE_SMOOTH), 0, y, null);
        //System.out.println("resizing width: w="+image.getWidth()+"/"+rez.getWidth()+"; y="+y);
    }
    g2.dispose();
}

From source file:common.utils.ImageUtils.java

/**
  * resize input image to new dinesions(only smaller) and save it to file
  * @param image input image for scaling
  * @param scale_factor factor for scaling image
 * @param rez writes resulting image to a file
 * @throws IOException/*from  ww  w.  j a  v a  2  s. co  m*/
  */
public static void saveScaledImageWidth(BufferedImage image, double scale_factor, OutputStream rez)
        throws IOException {
    //long time_resize = System.currentTimeMillis();
    if (scale_factor == 1) {
        writeImage(image, 1, rez);
    } else {
        int width = (int) (scale_factor * image.getWidth());
        int height = (int) (scale_factor * image.getHeight());
        //BufferedImage scaled_bi = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() );
        int type = image.getType();
        BufferedImage scaled_bi;
        if (type == BufferedImage.TYPE_CUSTOM) {
            scaled_bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        } else {
            scaled_bi = new BufferedImage(width, height, type);
        }

        Graphics2D g2 = scaled_bi.createGraphics();

        //g2.drawImage(image, at, null);
        g2.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        writeImage(scaled_bi, 1, rez);

        g2.dispose();
    }
    //time_resize = System.currentTimeMillis() - time_resize;
    //System.out.print("time_resize=" + (time_resize) + "; ");
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);/*w w w . jav  a 2 s.  co m*/
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:cpcc.ros.sim.osm.Camera.java

/**
 * @return the extracted image./*w w w .  ja v a  2s.c  o m*/
 * @throws IOException thrown in case of errors.
 */
private byte[] extractImage() throws IOException {
    double dTilesX = bottomRightTile.getxTile() - topLeftTile.getxTile();
    double dTilesY = bottomRightTile.getyTile() - topLeftTile.getyTile();

    int height = (int) (dTilesY * cfg.getTileHeight()) + bottomRightTile.getyPixel() - topLeftTile.getyPixel();
    int width = (int) (dTilesX * cfg.getTileWidth()) + bottomRightTile.getxPixel() - topLeftTile.getxPixel();

    if (height < 1) {
        height = 1;
    }

    if (width < 1) {
        width = 1;
    }

    BufferedImage image = map.getSubimage(topLeftTile.getxPixel(), topLeftTile.getyPixel(), width, height);
    Image scaledImage = image.getScaledInstance(cfg.getCameraWidth(), cfg.getCameraHeight(), 0);

    BufferedImage cameraImage = new BufferedImage(cfg.getCameraWidth(), cfg.getCameraHeight(),
            BufferedImage.TYPE_INT_RGB);
    cameraImage.createGraphics().drawImage(scaledImage, 0, 0, null);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(cameraImage, "PNG", bos);

    return bos.toByteArray();
}