简体   繁体   中英

Java code to Compress Image in server side

I am working on a project in building a web Application to get an image from the user and compress/resize the image and upload it to the database.I have used multipart form to get the image data into the server and took it in a haspMap(to implement other business logics) using the following code :

                        filePath = item.getName();
                        int pos = filePath.lastIndexOf("\\");
                        fileName = filePath.substring(pos + 1).toLowerCase();
                        pos = fileName.lastIndexOf(".");
                        fileType = fileName.substring(pos + 1);
                        contentType = item.getContentType();
                        fileData = item.getInputStream();
                        len = item.getSize();
                        ImageUploadValues.put("filePath",filePath );
                        ImageUploadValues.put("fileName",fileName );
                        ImageUploadValues.put("fileType",fileType );
                        ImageUploadValues.put("fileData",fileData );
                        ImageUploadValues.put("filelen",len );

Can anyone please tell me how to compress/resize this image in the server side and upload in the Database as an BLOB object. I am using only JSP/servlets. Using 3rd Party libraries are not allowed in our client.

For better results, don't forget to interpolate on rescaling.

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;


public class Example {

    public static void main(String[] args) throws IOException {
        InputStream is = Example.class.getResourceAsStream("Lenna.png");
        BufferedImage bi = ImageIO.read(is);

        rescale(bi);

        for(int i=1;i<10;i++){
            compress(i,bi);
        }

    }

    private static void rescale(BufferedImage bi) throws IOException {
        int originalWidth = bi.getWidth();
        int originalHeight = bi.getHeight();
        int type = bi.getType() == 0? BufferedImage.TYPE_INT_ARGB : bi.getType();

        //rescale 50%
        BufferedImage resizedImage = new BufferedImage(originalWidth/2, originalHeight/2, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(bi, 0, 0, originalWidth/2, originalHeight/2, null);
        g.dispose();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        ImageIO.write(resizedImage, "jpg", new File("Lenna50.jpg"));
    }

    private static void compress(int compression, BufferedImage bi)
            throws FileNotFoundException, IOException {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter jpegWriter = i.next();

        // Set the compression quality
        ImageWriteParam param = jpegWriter.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.1f * compression);

        // Write the image to a file
        FileImageOutputStream out = new FileImageOutputStream(new File("Lenna"+compression+".jpg"));
        jpegWriter.setOutput(out);
        jpegWriter.write(null, new IIOImage(bi, null, null), param);
        jpegWriter.dispose();
        out.close();
    }

}

Load the image into a java.awt.Image and scale it:

Image image = ImageIO.read(item.getInputStream());
Image scaled = image.getScaledInstance(SCALED_WITDTH, SCALED_HEIGHT,
    Image.SCALE_SMOOTH);

To write out the image, you'll need to convert it to a java.awt.image.BufferedImage :

BufferedImage output = new BufferedImage(scaled.getWidth(), scaled.getHeight(), 
    image.getType());
output.createGraphics().drawImage(scaled, 0, 0, null);
ImageIO.write(output, "jpeg", outputStream);

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