Thumbnailator 压缩图片

Github地址 https://github.com/coobird/thumbnailator

不废话,直接上代码

/**
     * 智能识车接口
     * 拍照识车 一图一车
     * ByteArrayResource
     *
     * @param deviceId
     * @return
     */
    @RequestMapping(value = "demo", method = RequestMethod.POST)
    @org.springframework.web.bind.annotation.ResponseBody
    public String demo(@RequestParam(value = "file") MultipartFile file, String deviceId, HttpServletRequest request) {

        String uri = "上传uri";
        String appKey = "appkey";
        String secret = "secret";
        String sign = "sign";

        try {
            RestTemplate restTemplate = restTemplateBuilder.setConnectTimeout(Duration.ofSeconds(5))
                    .setReadTimeout(Duration.ofSeconds(10)).build();
            List<String> cookies = CookieHelper.getCookieList(request);
            //构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.put("Cookie", cookies);
            headers.add("appKey", appKey);
            headers.add("sign", sign);
            headers.add("deviceId", deviceId);
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> map = new LinkedMultiValueMap();

            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名,比如图片的jpeg,png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //Thumbnails.fromInputStreams(Arrays.asList(file.getInputStream())).scale(0.5).toFile("E:\\images\\a.jpg");
            //Quality png格式不起作用,先转换为jpg 格式,再应用
            Thumbnails.fromInputStreams(Arrays.asList(file.getInputStream())).scale(0.5).outputQuality(0.8).toOutputStream(os);
            ByteArrayResource arrayResource = new ByteArrayResource(os.toByteArray()) {
                @Override
                public String getFilename() throws IllegalStateException {
                    return fileName;
                }
            };

            Resource resource = arrayResource;

            map.add("cid", 300);
            map.add("file", resource);
            HttpEntity requestEntity = new HttpEntity(map, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(uri, requestEntity, String.class);

            HttpHeaders headersRes = responseEntity.getHeaders();
            return responseEntity.getBody();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println(ex);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }
        return "";
    }

 

Thumbnailator 压缩图片

上一篇:阿里云服务器开放端口


下一篇:如是古籍数字化工具平台介绍---自动秒级识别古籍OCR