最近工作中遇到图片上传的问题。
但是上传的时候要求大小不能超过300K,
所以想写一个压缩图片的方法,尝试写了一个,大小确实变小了,但是色彩变化太大了。
所以想问一下有没有什么好的方法压缩图片,尺寸不变,存储空间变小,质量尽量减少损失。
有的话希望发一下代码。
但是上传的时候要求大小不能超过300K,
所以想写一个压缩图片的方法,尝试写了一个,大小确实变小了,但是色彩变化太大了。
所以想问一下有没有什么好的方法压缩图片,尺寸不变,存储空间变小,质量尽量减少损失。
有的话希望发一下代码。
昨天讨论帖
http://bbs.csdn.net/topics/390346316
第一种你说不行,这是第二种:public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) {
// 设置图片长宽
setWidthAndHeight(width, height);
// 是否是等比缩放 标记
this.proportion = gp;
try {
//获得源文件
file = new File(inputDir + inputFileName);
//file = new File("D://test/1/1.jpg");
//D://test/1/1.jpg
//d:\test\11 (2)-300k.jpg
System.out.println("图片地址:"+inputDir + inputFileName);
if (!file.exists()) {
System.out.println("图片不存在");
return "";
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
System.out.println(" can't read,retry!" + "<BR>");
return "no";
} else {
int newWidth; int newHeight;
// 判断是否是等比缩放
if (this.proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;
double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = outputWidth; // 输出的图片宽度
newHeight = outputHeight; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
/* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
优先级比速度高 生成的图片质量比较好 但速度慢 */
tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(outputDir+outputFileName);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}