栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > Java面试题

如何用java压缩图片 生成缩略图

Java面试题 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何用java压缩图片 生成缩略图

package com.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class PicCompression {


public static String doCompress(String oldFile, int width, int height, float quality, String smallIcon, boolean percentage) {
if (oldFile != null && width > 0 && height > 0) {
String newImage = null;
try {
File file = new File(oldFile);
// 文件不存在
if (!file.exists()) {
return null;
}

Image srcFile = ImageIO.read(file);
int new_w = width;
int new_h = height;
if (percentage) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) srcFile.getWidth(null)) / (double) width + 0.1;
double rate2 = ((double) srcFile.getHeight(null)) / (double) height + 0.1;
double rate = rate1 > rate2 ? rate1 : rate2;
new_w = (int) (((double) srcFile.getWidth(null)) / rate);
new_h = (int) (((double) srcFile.getHeight(null)) / rate);
}

BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);


String filePrex = oldFile.substring(0, oldFile.lastIndexOf(‘.’));
newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());


FileOutputStream out = new FileOutputStream(newImage);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);


jep.setQuality(quality, true);
encoder.encode(tag, jep);

out.close();
srcFile.flush();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newImage;
} else {
return null;
}
}

//测试
public static void main(String str[]) {
System.out.println(PicCompression.doCompress(“F:/new.bmp”, 80, 50, 1, “_small”, false));
System.out.print(“ok…”);
}


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/359508.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号