Java BufferedImage Thumbnail thumbnail(final InputStream inputStream, final int width, final int height, final OutputStream outputStream)

Here you can find the source of thumbnail(final InputStream inputStream, final int width, final int height, final OutputStream outputStream)

Description

thumbnail

License

LGPL

Declaration

public static void thumbnail(final InputStream inputStream, final int width, final int height,
            final OutputStream outputStream) throws IOException 

Method Source Code

//package com.java2s;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

public class Main {
    public static void thumbnail(final InputStream inputStream, final int width, final int height,
            final OutputStream outputStream) throws IOException {
        thumbnail(inputStream, width, height, false, outputStream);
    }//  ww  w .j  av  a2  s  .  com

    public static void thumbnail(final InputStream inputStream, final int width, final int height,
            final boolean stretch, final OutputStream outputStream) throws IOException {
        int w, h;
        final BufferedImage sbi = ImageIO.read(inputStream);
        if (sbi == null) {
            return;
        }
        if (width == 0 || height == 0) {
            w = sbi.getWidth();
            h = sbi.getHeight();
        } else {
            if (!stretch) {
                final double d = (double) width / (double) height;
                final double d0 = (double) sbi.getWidth() / (double) sbi.getHeight();
                if (d < d0) {
                    w = width;
                    h = (int) (width / d0);
                } else {
                    w = (int) (height * d0);
                    h = height;
                }
            } else {
                w = width;
                h = height;
            }
        }
        final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = bi.createGraphics();
        if (w != width) {
            g.drawImage(sbi, Math.abs(w - width) / 2, 0, w, h, null);
        } else if (h != height) {
            g.drawImage(sbi, 0, Math.abs(h - height) / 2, w, h, null);
        } else {
            g.drawImage(sbi, 0, 0, w, h, null);
        }
        g.dispose();
        ImageIO.write(bi, "png", outputStream);
    }
}

Related

  1. thumbnail(File input, File output, int sizeX, int sizeY)
  2. thumbnail(int imageWidth, int imageHeight, File originFileName, File thumbFileName)