方式一:返回字节流
package com.ciwei.dcs.controller;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
@RestController
@RequestMapping(value="/api/v1")
public class ImageTest {
@GetMapping(value = "/image",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] test() throws Exception {
File file = ResourceUtils.getFile((ResourceUtils.CLASSPATH_URL_PREFIX + "springboot.jpg"));
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
}
方式二:利用spring自带的图片格式
package com.ciwei.dcs.controller;
import com.alibaba.fastjson.JSONObject;
import com.ciwei.app.common.*;
import com.ciwei.app.utils.GeoUtil;
import com.ciwei.activemq.producer.topic.TopicSender;
import com.ciwei.dcs.base.entity.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/coll")
public class CollectLogController {
private final Logger logger = LoggerFactory.getLogger(CollectLogController.class);
@RequestMapping(value = "/pc",method = RequestMethod.GET,produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public BufferedImage getImg(@RequestParam String json, HttpServletRequest req) throws IOException {
logger.info("--------->获取到的json是:{}",json);
File file = ResourceUtils.getFile((ResourceUtils.CLASSPATH_URL_PREFIX + "springboot.jpg"));
return ImageIO.read(new FileInputStream(file));
}
}
- 该方式需要配置转换器,不然报406错误
package com.ciwei.dcs.base.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
@Configuration
public class ImageConvert {
@Bean
public BufferedImageHttpMessageConverter bufferedImageHttpMessageConverter(){
return new BufferedImageHttpMessageConverter();
}
}