业务需要,得获取大图的缩略图
java @GetMapping("getThumbnail")
@ApiOperation("获取缩略图")
public void getThumbnail(String url, HttpServletResponse response){
try (OutputStream outputStream = response.getOutputStream()){
// 设置响应类型为JPEG图片
response.setContentType("image/jpeg");
// 防止中文乱码以及图片在浏览器中显示问题
response.setHeader("Content-Disposition", "inline; filename=image.jpg");
// 写入图片数据到输出流
ImageUtil.getImageStream(url,200,200).writeTo(outputStream);
// 刷新缓冲区并结束响应
outputStream.flush();
}catch (IOException e){
throw new SystemException(500,"获取缩略图失败");
}
}
java
public static ByteArrayOutputStream getImageStream(String url,int width, int height) {
ByteArrayOutputStream outputStream=null;
// 打开URL连接
try (InputStream in = new URL(url).openStream()) {
// 从输入流中读取原始图片
BufferedImage originalImage = ImageIO.read(in);
// 创建一个新的缩放后的图片
BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, width, height, null);
graphics2D.dispose();
// 将缩放后的图片转换为字节数组
outputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, "jpg", outputStream);
} catch (Exception e) {
e.printStackTrace();
log.error("获取图片失败:"+e.getMessage());
// 处理异常情况
}
return outputStream;
}
``
bashhttp://localhost:8888/dictimg/getThumbnail?url=http://www.baidu.com/image1.jpg
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!