[英]How to create an image from an InputStream, resize it and save it?
I have this code where i get an InputStream
and 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 InputStream
and then create that resized image. 那么如何调整我从
InputStream
得到的大小,然后创建该调整大小的图像。 I want to set the largest side of the image to 180px and resize the other side with that proportion. 我想将图像的最大面设置为180px并用该比例调整另一面的大小。
Example: 例:
Image = 289px * 206px
Resized image = 180px * 128px
图片=
289px * 206px
调整大小后的图片= 180px * 128px
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! 希望可以帮助某人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.