Java创建图片文件缩略图

public static void uploadImg(InputStream file, String filePath, String fileName, int widthdist, int heightdist) throws Exception {
File targetDir = new File(filePath + FS_FILE_APP_PATH);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
// 开始读取文件并进行压缩
Image src = ImageIO.read(file);

// 构造一个类型为预定义图像类型之一的 BufferedImage
BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

//绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
//Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

//创建文件输出流
FileOutputStream out = new FileOutputStream(filePath + FS_FILE_APP_PATH + fileName.substring(0,fileName.lastIndexOf(".")) + ".jpg");
//将图片按JPEG压缩,保存到out中
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
//关闭文件输出流
out.close();
}

//调用
uploadImg(file.getInputStream(), bootdoConfig.getUploadPath()+floderPath, fileName,100,100);

猜你喜欢

转载自www.cnblogs.com/liw66/p/10190125.html