展示压缩图片

本文介绍了一种从网络上读取微信用户头像并实时压缩显示的方法,通过使用Java的流处理技术,实现了图片的即时压缩及展示,适用于不需保存图片的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目需要读取微信人头像,并进行压缩展示,图片在压缩后不需要储存,直接展示,所以在网上找了一些信息进行了拼装,有了此篇。

代码如下:
OutputStream os = null;
InputStream inputStream = null;
URL url=null;
try{
url=new URL(headImgUrl);
//1.获取url的输入流 dataInputStream
DataInputStream dataInputStream=new DataInputStream(url.openStream());
//2.加一层BufferedInputStream
BufferedInputStream bufferedInputStream=new BufferedInputStream(dataInputStream);
//3.构造原始图片流 preImage
BufferedImage preImage=ImageIO.read(bufferedInputStream);
//4.获得原始图片的长宽 width/height
int width=preImage.getWidth();
int height=preImage.getHeight();
//5.构造压缩后的图片流 image 长宽各为原来的1/2
BufferedImage image=new BufferedImage(width/2, height/2, BufferedImage.TYPE_INT_RGB);
//绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
//Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
image.getGraphics().drawImage(preImage.getScaledInstance(width/2, height/2, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
ImageIO.write(image, “png”, imageOutput);
inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
os = response.getOutputStream();
byte[] b = new byte[1024];
while (inputStream.read(b) != -1) {
os.write(b);
}
os.write(b);
inputStream.close();
os.flush();
os.close();
}catch(IOException e){
log.info(“微信人头像流读取失败”);
}finally {
if (os != null) {
try {
inputStream.close();
os.flush();
os.close();
} catch (IOException e) {
log.info(“微信人头像流关闭失败”);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值