import java.awt.Image;
import java.awt.p_w_picpath.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.p_w_picpathio.ImageIO;
import com.sun.p_w_picpath.codec.jpeg.JPEGCodec;
import com.sun.p_w_picpath.codec.jpeg.JPEGEncodeParam;
import com.sun.p_w_picpath.codec.jpeg.JPEGImageEncoder;
public class testStatic {
@SuppressWarnings("restriction")
public static String doCompress(String oldFile) throws FileNotFoundException {
if (oldFile != null) {
Image srcFile=null;
String newImage = null;
try {
File file = new File(oldFile);
// 文件不存在
if (!file.exists()) {
return null;
}
/*读取图片信息*/
srcFile = ImageIO.read(file);
int new_w = srcFile.getHeight(null);
int new_h = srcFile.getHeight(null);
int maxWH = 200;
if(new_w>maxWH||new_h>maxWH){
if (new_w > new_h) {
new_w = maxWH;
new_h = maxWH * new_h / new_w;
} else {
new_w = maxWH * new_w / new_h;
new_h = maxWH;
}
}
/* 宽高设定*/
BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);
//随机数
Random rnd = new Random();
int num = rnd.nextInt(89999) + 10000;
/*压缩后的文件名 */
String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.'));
newImage = filePrex + num + oldFile.substring(filePrex.length());
/*压缩之后临时存放位置*/
FileOutputStream out = new FileOutputStream(newImage);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
//压缩质量
jep.setQuality(1, true);
encoder.encode(tag, jep);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
srcFile.flush();
}
return newImage;
} else {
return null;
}
}
//测试
public static void main(String str[]) throws FileNotFoundException {
System.out.println(doCompress("D:/aa.jpg"));
}
}
一个很好的图片等比压缩类
原创阿山哥258 ©著作权
文章标签 image 等比压缩 文章分类 后端开发
©著作权归作者所有:来自51CTO博客作者阿山哥258的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
java等比压缩图片工具类
java等比压缩图片工具类
Image java System -
Unity等比压缩图片
Unity压缩图片
unity sed 压缩图片 System