How to Compress them with thumbrails When uploading pictures

When uploading large images, the speed is very slow, so the images are compressed and then stored

Thumbnailator website: http://code.google.com/p/thumbnailator/

Add in POM

   <dependency>
        <groupId>net.coobird</groupId>
        <artifactId>thumbnailator</artifactId>
        <version>0.4.8</version>
    </dependency>

controller

@PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
//        if(file.getSize() > 2 * ONE_MB){
//            return ResponseUtil.fail(500,"Image size exceeds 2M!");
//        }
        String originalFilename = file.getOriginalFilename();
        logger.info("Before compression:"+file.getSize());
        ByteArrayInputStream inputStream = uploadFile(file);
        logger.info("After compression:"+inputStream.available());
        LitemallStorage litemallStorage = storageService.store(inputStream, inputStream.available(), file.getContentType(), originalFilename);
        return ResponseUtil.ok(litemallStorage);
    }

    /**
     * image compression
     * @return
     */
    public static ByteArrayInputStream uploadFile(MultipartFile file){
        if(file == null)return  null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream()).scale(0.4f).outputQuality(0.25f).toOutputStream(baos);
            if(baos!=null)
                return parse(baos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // outputStream转inputStream
    public static ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

service:

 /**
     * Store a file object
     *
     * @param inputStream File input stream
     * @param contentLength The length of the file.
     * @param contentType File type
     * @param fileName File index name
     */
    public LitemallStorage store(InputStream inputStream, long contentLength, String contentType, String fileName) {
        String key = generateKey(fileName);
        store(inputStream, contentLength, contentType, key);

        String url = generateUrl(key);
        LitemallStorage storageInfo = new LitemallStorage();
        storageInfo.setName(fileName);
        storageInfo.setSize((int) contentLength);
        storageInfo.setType(contentType);
        storageInfo.setKey(key);
        storageInfo.setUrl(url);
        litemallStorageService.add(storageInfo);

        return storageInfo;
    }


    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        try {
            // Simple file upload, supports up to 5 GB, suitable for small file upload, recommend using this interface for files under 20M
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(contentLength);
            objectMetadata.setContentType(contentType);
            // The object key (Key) is the unique identifier of the object in the storage bucket.
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
            PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

    }

Other methods of thumbnailator:

//Shrink and put the image by the specified size (will follow the original image height and width ratio)
// Here the image is compressed into a 400×500 thumbnail
Thumbnails.of(fromPic).size(400,500).toFile(toPic);

Zoom in and out according to the specified ratio // Zoom in and out according to the ratio
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//scale down and scale up
Thumbnails.of(fromPic).scale(2f);//proportionally enlarge the image size, compress the image file size

// image size remains the same, compress the image file size outputQuality implementation, parameter 1 is the highest quality
Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

Read More: