How to compress Picture size with Java
This article mainly explains "how to compress picture size with Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to compress the image size with Java".
Use the scene:
1. When using the picture upload function, the uploaded picture is too large, resulting in excessive occupation of server resources.
two。 Pictures uploaded by the client vary in size. When the front end needs to be shown to the user with a fixed size, the uploaded image can be processed uniformly through java.
Feature Preview
1. Before compression
two。 After compression
Code implementation: package com.linghu.test;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException / * * @ author is ordering Fox * @ describe to compress the image size * @ date 2020-6-12 * / public class TestCompressImage {public static void main (String [] args) {try {/ / the path where the image is located BufferedImage templateImage = ImageIO.read (new File ("f:/temp/linghu.jpg")) / / the length and width of the original picture int height = templateImage.getHeight (); int width = templateImage.getWidth (); / / by proportional compression float scale = 0.5f; / / by fixed length compression / * int doWithHeight = 100; int dowithWidth = 300 * / / the length and width after compression int doWithHeight = (int) (scale * height); int dowithWidth = (int) (scale * width); BufferedImage finalImage = new BufferedImage (dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB); finalImage.getGraphics (). DrawImage (dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0,0, null) / / the output path of the picture, and the picture name FileOutputStream fileOutputStream = new FileOutputStream ("f:/temp/linghuAfterDoWith.jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (fileOutputStream); encoder.encode (finalImage); fileOutputStream.close ();} catch (IOException e) {e.printStackTrace () At this point, I believe you have a deeper understanding of "how to compress picture size in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!