工具包-图像裁剪
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageSubUtils {
private static final Logger log = LoggerFactory.getLogger(ImageSubUtils.class);
private static BufferedImage imgSub(BufferedImage src, int x, int y, int width, int height) {
BufferedImage back = src.getSubimage(x, y, width, height);
return back;
}
private static BufferedImage imgSub(BufferedImage src, int width, int height) {
int srcWidth = src.getWidth(); // 原图宽
int srcHeight = src.getHeight(); // 原图高
if (width > srcWidth) {
width = srcWidth;
}
if (height > srcHeight) {
height = srcHeight;
}
BufferedImage back = src.getSubimage(0, 0, width, height);
return back;
}
// 读取图片
private static BufferedImage file2img(File imgpath) {
try {
BufferedImage bufferedImage = ImageIO.read(imgpath);
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 保存图片,extent为格式,"jpg"、"png"等
private static void img2file(BufferedImage img, String extent, File newfile) {
try {
ImageIO.write(img, extent, newfile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 裁剪图片
*
* @param src 源文件
* @param tar 目标文件
* @return
*/
public static boolean subImg(File src, File tar, String imageType, int newSize ) {
if(imageType == null || imageType.length()==0)
{
imageType ="jpg";
}
try {
BufferedImage bi2 = file2img(src); // 读取图片
BufferedImage bii2 = imgSub(bi2, newSize, newSize);
img2file(bii2, imageType, tar); // 生成图片
} catch (Exception e) {
log.info("缩略图裁剪失败", e);
return false;
}
return true;
}
public static void main(String[] args) {
// 文件与BufferedImage间的转换
File src = new File("C:\\data\\image\\min.jpg");
File tar = new File("C:\\data\\image\\min_1.jpg");
boolean r = ImageSubUtils.subImg(src, tar,"png",300);
System.out.println("success " +r);
String name ="aaa.png";
String fileExt =name.substring(name.lastIndexOf("."));
System.out.println("fileExt:"+fileExt);
}
}