Java 如何从 InputStream 创建图像、调整大小并保存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/24452332/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an image from an InputStream, resize it and save it?
提问by Kaz Miller
I have this code where i get an InputStreamand create an image:
我有这个代码,我在那里得到一个InputStream并创建一个图像:
Part file;
// more code
try {
        InputStream is = file.getInputStream();
        File f = new File("C:\ImagenesAlmacen\QR\olaKeAse.jpg");
        OutputStream os = new FileOutputStream(f);
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        os.close();
        is.close();
    } catch (IOException e) {
        System.out.println("Error");
    }
The problem is that I have to resize that image before i create if from the InputStream
问题是我必须在创建之前调整该图像的大小,如果从 InputStream
So how to resize what I get from the InputStreamand then create that resized image. I want to set the largest side of the image to 180px and resize the other side with that proportion.
那么如何调整我从中获得的内容的InputStream大小,然后创建调整大小的图像。我想将图像的最大边设置为 180 像素,并以该比例调整另一边的大小。
Example:
例子:
Image = 289px * 206pxResized image = 180px* 128px
图像 =289px * 206px调整大小的图像 = 180像素* 128px
采纳答案by Kaz Miller
I did this:
我这样做了:
try {
        InputStream is = file.getInputStream();
        Image image = ImageIO.read(is);
        BufferedImage bi = this.createResizedCopy(image, 180, 180, true);
        ImageIO.write(bi, "jpg", new File("C:\ImagenesAlmacen\QR\olaKeAse.jpg"));
    } catch (IOException e) {
        System.out.println("Error");
    }
BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
    int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
    Graphics2D g = scaledBI.createGraphics();
    if (preserveAlpha) {
        g.setComposite(AlphaComposite.Src);
    }
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    return scaledBI;
}
And I did not use the other code.
而且我没有使用其他代码。
Hope helps someone!
希望对某人有所帮助!

