没有介绍,只有代码,拿着就能用
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;
import org.springframework.stereotype.Component;
@Component
public class ImgCompress {
public static String compress(String fileSource) {
String str = null;
try {
BufferedImage templateImage = ImageIO.read(new File(fileSource));
int height = templateImage.getHeight();
int width = templateImage.getWidth();
float scale = 0.7f;
int doWithHeight = (int) (scale * height);
int dowithWidth = (int) (scale * width);
BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);
finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
str = fileSource.substring(0,fileSource.lastIndexOf("."));
String suffix = fileSource.substring(fileSource.lastIndexOf("."));
str += "2" + suffix;
System.out.println(str);
FileOutputStream fileOutputStream = new FileOutputStream(str);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(finalImage);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return str.substring(str.lastIndexOf("/"));
}
}