public class ImgHelper {
// 输入参数
boolean flag = true;// 是否是删除原图片
boolean ratio = true;// 是否是等比压缩
public static void main(String[] args) {
String root = "D:\\dd";
File file = new File(root);
new ImgHelper().show(file);
}
// 遍历文件夹
public void show(File file) {
if (file.isDirectory()) {
File[] fs = file.listFiles();
for (File f : fs) {
show(f);
}
} else {
if(file.getName().endsWith(".jpg")){
String inpath = file.getAbsolutePath();
String outpath = file.getParentFile().getAbsolutePath()
+ File.separator + file.getName();
boolean img = getImg(inpath, outpath, flag);
System.out.println("图片压缩结果:"+img+",位置"+outpath);
}
}
}
// 得到700的图片,处理单件图片的总流程
// 输入路径+文件名,输出路径+文件名,源文件是否删除(删除,是true)
public boolean getImg(String inpath, String outpath, boolean flag) {
try {
File file = new File(inpath);
if (file.exists()) {
Image image = ImageIO.read(file);
if (image == null) {
System.out.println(file.getAbsoluteFile());
} else {
int height = image.getHeight(null);
int width = image.getWidth(null);
BufferedImage suitImgOut = getSuitImgOut(image, width, height);
return getImgFile(suitImgOut, outpath);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// 原子性,输入Image,尺寸大小,返回BufferedImage流
// 输入想得到的尺寸,原图片的地址,名称,新图片的地址,名称,原图片是否删除
public BufferedImage getSuitImgOut(Image img, int sizewidth, int sizeheight) {
int newWidth = sizewidth;
int newHeight = sizeheight;
BufferedImage tag = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH),
0, 0, null);
return tag;
}
// 根据图像包装流生成文件
public boolean getImgFile(BufferedImage buffimg, String outpath) {
try {
FileOutputStream out;
out = new FileOutputStream(outpath);
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(buffimg);
out.close();
return true;
} catch (Exception e) {
System.out.println("根据图像包装流生成文件发生异常");
return false;
}
}
public boolean isRatio() {
return ratio;
}
public void setRatio(boolean ratio) {
this.ratio = ratio;
}
}
图片压缩
最新推荐文章于 2024-10-23 19:30:23 发布