亲宝软件园·资讯

展开

springboot返回图片流

卑微小钟 人气:0

一、返回BufferedImage

由于spring mvc不支持返回BufferedImage ,所以增加图片转换器

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 增加图片转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new BufferedImageHttpMessageConverter());
    }
}
@GetMapping(value = "/img",produces = MediaType.IMAGE_PNG_VALUE)
public BufferedImage getImage() throws Exception {
    return ImageIO.read(new FileInputStream(new File("D:/test.jpg"))
}

二、返回byte[]

返回byte[]可以不用配置图片转换器,而自接被识别

@GetMapping(value = "/img",produces = MediaType.IMAGE_PNG_VALUE)
public byte[] getImage() throws Exception {
    bufferedImage = ImageIO.read(new FileInputStream(new File("D:/test.jpg"))
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", out);
    return out.toByteArray();
}

加载全部内容

相关教程
猜你喜欢
用户评论