简体   繁体   中英

How to reduce size of a multipart file in java

I have Java Spring MVC application in which there is an option to upload an image and save to the server. i have the following method:

@RequestMapping(value = "/uploaddocimagecontentsubmit", method = RequestMethod.POST)
public String createUpdateFileImageContentSubmit(@RequestParam("file") MultipartFile file, ModelMap model)
{
//methods to handle file upload
}

I am now trying to reduce the size of the image refering the following:

increasing-resolution-and-reducing-size-of-an-image-in-java and decrease-image-resolution-in-java The problem I am facing is that in the above examples, we are dealing with java.io.File Objects which are saved to a specified location. I dont want to save the image. Is there any way that I can use something similar to compress my Multipart Image file and continue with the upload.

It was my first time taking a deep dive into the ImageIO package. I came across the MemoryCacheImageOutputStream, which allows you to write an image output stream to an output stream, ie ByteArrayOutputStream. From there, The data can be retrieved using toByteArray() and toString(), after compression. I used toByteArray, as I am storing images to postgresql and it stores the images as a byte array. I know this is late, but I hope it helps someone.

private byte[] compressImage(MultipartFile mpFile) {
    float quality = 0.3f;
    String imageName = mpFile.getOriginalFilename();
    String imageExtension = imageName.substring(imageName.lastIndexOf(".") + 1);
    // Returns an Iterator containing all currently registered ImageWriters that claim to be able to encode the named format.
    // You don't have to register one yourself; some are provided.
    ImageWriter imageWriter = ImageIO.getImageWritersByFormatName(imageExtension).next();
    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // Check the api value that suites your needs.
    // A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
    // while a setting of 1.0 is most generically interpreted as "high image quality is important."
    imageWriteParam.setCompressionQuality(quality);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // MemoryCacheImageOutputStream: An implementation of ImageOutputStream that writes its output to a regular
    // OutputStream, i.e. the ByteArrayOutputStream.
    ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(baos);
    // Sets the destination to the given ImageOutputStream or other Object.
    imageWriter.setOutput(imageOutputStream);
    BufferedImage originalImage = null;
    try (InputStream inputStream = mpFile.getInputStream()) {
        originalImage = ImageIO.read(inputStream); 
    } catch (IOException e) {
        String info = String.format("compressImage - bufferedImage (file %s)- IOException - message: %s ", imageName, e.getMessage());
        logger.error(info);
        return baos.toByteArray();
    }
    IIOImage image = new IIOImage(originalImage, null, null);
    try {
        imageWriter.write(null, image, imageWriteParam);
    } catch (IOException e) {
        String info = String.format("compressImage - imageWriter (file %s)- IOException - message: %s ", imageName, e.getMessage());
        logger.error(info);
    } finally {
        imageWriter.dispose();
    }
    return baos.toByteArray();
}

Why don't you resize it on the client before upload? That will save some bandwidth

BlueImp JQuery Upload can do this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM