标签:configure 开发 tst 原因 put 简单 xtend over value
废话少说,直接干货:
前提:添加图片转换器
@Configuration public class WebMvcConfig implements WebMvcConfigurer { /** * 增加图片转换器 * @param converters */ @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new BufferedImageHttpMessageConverter()); } }
然后就可以直接写业务代码了,网上有很多一行代码搞定的,,本人亲测确实有效,代码如下:
@RestController @Slf4j @Api(tags = SwaggerConfig.TAG_IMAGE) @RequestMapping(SwaggerConfig.TAG_IMAGE) public class ImageController { //通过produces 告知浏览器我要返回的媒体类型 @GetMapping(value = "/getImage2", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE}) @ApiOperation("获取图片-返回BufferedImage") public BufferedImage getImage2() throws IOException { return ImageIO.read(new FileInputStream(new File("H:\\Pictures\\6f31c1a2gw6dcdoigmeftj.jpg"))); } }
注意: response.setContentType("image/png");这行代码一定要加上
@RestController @Slf4j @Api(tags = SwaggerConfig.TAG_IMAGE) @RequestMapping(SwaggerConfig.TAG_IMAGE) public class ImageController { @Resource private HttpServletResponse response; @GetMapping(value = "/getImage") @ApiOperation("获取图片-以ImageIO流形式写回") public void getImage() throws IOException { OutputStream os = null; try { // 读取图片 BufferedImage image = ImageIO.read(new FileInputStream(new File("F:\\谷歌下载\\未命名文件.png"))); response.setContentType("image/png"); os = response.getOutputStream(); if (image != null) { ImageIO.write(image, "png", os); } } catch (IOException e) { log.error("获取图片异常{}",e.getMessage()); } finally { if (os != null) { os.flush(); os.close(); } } } }
至此....OK
标签:configure 开发 tst 原因 put 简单 xtend over value
原文地址:https://www.cnblogs.com/Baker-Street/p/12918295.html