java-使用spring mvc输出图片

由于展示某些图片数据需要权限验证,因此不能直接访问图片资源。因此,使用spring mvc输出图片中遇到一个问题。

刚开始使用以下方式返回图片的字节,然而发现response.setContentType("image/png");并没有生效,返回的Response中type是text,导致图片无法展示。

@WebCheckLogin
@GetMapping(value="/album/resizePicture")
public byte[] resizePicture(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("image/png");
...
}

解决方案

@WebCheckLogin
@GetMapping(value="/album/resizePicture")
public void resizePicture(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("image/png");
    try (OutputStream out = response.getOutputStream()) { 
         //这里直接写入输出流
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Javajavax.imageio包来实现MultipartFile图片的压缩。下面是一个使用Spring MVC和MultipartFile进行图片压缩的示例代码: ```java import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ImageCompressor { public static void compressImage(MultipartFile file, String outputFilePath, int maxWidth, int maxHeight) throws IOException { BufferedImage image = ImageIO.read(file.getInputStream()); int originalWidth = image.getWidth(); int originalHeight = image.getHeight(); // 计算缩放比例 double scaleFactor = Math.min((double) maxWidth / originalWidth, (double) maxHeight / originalHeight); int newWidth = (int) (originalWidth * scaleFactor); int newHeight = (int) (originalHeight * scaleFactor); // 创建缩放后的图像 BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.drawImage(image, 0, 0, newWidth, newHeight, null); g2d.dispose(); // 将缩放后的图像保存到文件 ImageIO.write(resizedImage, "jpg", new File(outputFilePath)); } } ``` 使用时,你可以在Spring MVC的controller中调用`compressImage`方法来实现图片压缩。需要传入要压缩的MultipartFile对象、输出文件路径、以及期望的最大宽度和最大高度。 注意:上述示例代码仅适用于压缩JPEG格式的图片,如果需要处理其他格式的图片,可以根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值