图片压缩源码图片测试代码
图片压缩源码
package com.lyc.noJs.util;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
/**
* 图片压缩处理
* @author
*/
@Slf4j
@NoArgsConstructor
public class ImgCompress {
private static Image img;
private static int width;
private static int height;
private static String path;
private static int proportion;
public static ImgCompress
newImgCompress(){
return new ImgCompress();
}
/**
* 图片压缩算法
* @param inputPath
* @param outputPath
* @param pro
*/
public static void initCompression(String inputPath, String outputPath,
int pro){
boolean flag=
true;
proportion=pro;
URL url;
try {
url =
new URL(inputPath);
img = ImageIO.read(url);
}
catch (Exception e) {
e.printStackTrace();
}
width = img.getWidth(
null);
height = img.getHeight(
null);
if(width<
200){
flag=
false;
}
else if(height<
200){
flag=
false;
}
if(flag){
path = outputPath;
try {
resizeFix(width/proportion, height/proportion);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 按照宽度还是高度进行压缩
* @param w int 最大宽度
* @param h int 最大高度
*/
public static void resizeFix(
int w,
int h)
throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
}
else {
resizeByHeight(h);
}
}
/**
* 以宽度为基准,等比例放缩图片
* @param w int 新宽度
*/
public static void resizeByWidth(
int w)
throws IOException {
int h = (
int) (height * w / width);
resize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
* @param h int 新高度
*/
public static void resizeByHeight(
int h)
throws IOException {
int w = (
int) (width * h / height);
resize(w, h);
}
/**
* 强制压缩/放大图片到固定的大小
* @param w int 新宽度
* @param h int 新高度
*/
public static void resize(
int w,
int h)
throws IOException {
BufferedImage image =
new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img,
0,
0, w, h,
null);
File destFile =
new File(path);
FileOutputStream out =
new FileOutputStream(destFile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
}
图片测试代码
package
com.lyc.demo
import
com.lyc.noJs.util.ImgCompress
import lombok
.extern.slf4j
.Slf4j
import org
.junit.Test
@Slf4j
public class ImgCompressTest {
@Test
public void test(){
ImgCompress imgCompress = ImgCompress
.newImgCompress()
imgCompress
.initCompression(
"http://192.168.153.1:9080/no-js/upload/2018/04/09/1523257444813.jpg",
"C:\\temp\\1523257444813.jpg",
4)
}
}
上述代码的功能是根据指定的压缩比进行图片压缩操作,比如说刚才我就是将图片的压缩比定为4,即假设原来长度为100的图片,现在长度被等比例压缩到了原来的四分之一,即被压缩到了长度为25。
原图片:
压缩后的结果: