import
java.awt.Image;
import
java.awt.image.BufferedImage;
import
java.io.File;
import
java.io.IOException;
import
javax.imageio.ImageIO;
/**
*
* @author 周瑜
* 2018年3月23日 下午3:15:10
*/
public
final
class
PicUtils {
/**
* 判断要压缩的文件名是否是合法的图片文件
* @param fileName
* @return
*/
private
static
final
boolean
isImage(String fileName) {
if
(fileName ==
null
|| fileName.isEmpty()) {
throw
new
RuntimeException(
"要判断的文件名不能为空!"
);
}
fileName = fileName.toUpperCase();
return
fileName.endsWith(
".JPG"
) || fileName.endsWith(
".JPEG"
) ||
fileName.endsWith(
".PNG"
) || fileName.endsWith(
".BMP"
) || fileName.endsWith(
".GIF"
);
}
/**
* 读取文件,返回Image对象
* @param srcFile 要压缩的原始文件的文件路径
* @return
* @throws IOException
*/
private
static
final
Image readImage(String srcFile)
throws
IOException {
if
(!isImage(srcFile)) {
throw
new
RuntimeException(
"要压缩的文件的后缀名必须是jpg、jpeg、png、bmp或者gif!"
);
}
File _file =
new
File(srcFile);
if
(!_file.exists() || _file.isDirectory()) {
throw
new
RuntimeException(
"要压缩文件必须存在!"
);
}
return
javax.imageio.ImageIO.read(_file);
}
/**
* 根据指定的宽和高缩放图片,并将缩放后的图片输出到目标文件
* @param img 读取到的原始文件
* @param destFile 目标文件
* @param width 缩放后的宽
* @param height 缩放后的高
* @throws IOException
*/
private
static
final
void
resize(Image img,File destFile,
int
width,
int
height )
throws
IOException {
BufferedImage _image =
new
BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
_image.getGraphics().drawImage(img,
0
,
0
, width, height,
null
);
String fileName = destFile.getName();
ImageIO.write(_image, fileName.substring(fileName.lastIndexOf(
"."
)+
1
).toUpperCase(), destFile);
}
/**
* 强制压缩/放大图片到固定的大小
* @param srcFile 要压缩的原始文件的文件路径
* @param destFile 压缩后的文件
* @param width 压缩后的图片的宽
* @param height 压缩后的图片的高
* @throws IOException
*/
public
static
final
void
resize(String srcFile,File destFile,
int
width,
int
height)
throws
IOException {
resize(readImage(srcFile),destFile,width,height);
}
/**
* 按照固定的比例缩放图片
* @param srcFile
* @param destFile
* @param t
* @throws IOException
*/
public
static
final
void
resize(String srcFile,File destFile,
double
t)
throws
IOException {
Image img = readImage(srcFile);
resize(img,destFile,(
int
) (img.getWidth(
null
) * t),(
int
) (img.getHeight(
null
) * t));
}
/**
* 以宽度为基准,等比例放缩图片
* @param srcFile 要压缩的原始文件的文件路径
* @param destFile 压缩后的文件
* @param width 压缩后的图片的宽
* @throws IOException
*/
public
static
final
void
resizeByWidth(String srcFile,File destFile,
int
width)
throws
IOException {
Image img = readImage(srcFile);
int
h = img.getHeight(
null
);
int
w = img.getWidth(
null
);
double
nh =
1.0
*h*width/ w;
resize(img,destFile, width,(
int
) nh);
}
/**
* 以高度为基准,等比例缩放图片
* @param srcFile 要压缩的原始文件的文件路径
* @param destFile 压缩后的文件
* @param height 压缩后的图片的宽
* @throws IOException
*/
public
static
final
void
resizeByHeight(String srcFile,File destFile,
int
height)
throws
IOException {
Image img = readImage(srcFile);
int
h = img.getHeight(
null
);
int
w = img.getWidth(
null
);
double
nw =
1.0
*w*height / h;
resize(img,destFile,(
int
) nw, height);
}
}