Java按照给定大小自动裁剪图片
分类: Java 专栏: java 标签: Java缩略图 Java剪裁图片
2023-01-28 16:39:42 484浏览
给定图片最终大小,计算出从中心开始的缩放比例进行图片裁剪
<!-- 缩略图依赖 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
package s.jf3q.com.untils; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positions; import s.jf3q.com.cons.Sys; public class ThumbnailUntils { public static String crateImg(String fn ,Integer width,Integer height) throws IOException { File _file = new File(Sys.Upimg.absolute_path+fn); // 读入文件 if(!_file.exists()){ return null; } // 图片对象 BufferedImage bufferedImage = ImageIO.read(new FileInputStream(Sys.Upimg.absolute_path+fn)); // 宽度 int imgwidth = bufferedImage.getWidth(); // 高度 int imgheight = bufferedImage.getHeight(); System.out.println("原图:"+imgwidth+","+imgheight); System.out.println("设置大小:"+width+","+height); if(width==height ){ if(imgwidth>imgheight)imgwidth=imgheight; else imgheight=imgwidth; Thumbnails.of(Sys.Upimg.absolute_path+fn) .sourceRegion(Positions.CENTER,imgwidth,imgheight) .size(width, height).outputQuality(1f) .toFile(Sys.Upimg.absolute_path+fn); System.out.println("比例之后:"+imgwidth+","+imgheight); } else { if(imgwidth>imgheight)imgwidth=imgheight*width/height; else imgheight=imgwidth*height/width; Thumbnails.of(Sys.Upimg.absolute_path+fn) .sourceRegion(Positions.CENTER,imgwidth,imgheight) .size(width, height).outputQuality(1f) .toFile(Sys.Upimg.absolute_path+fn); System.out.println("比例之后:"+imgwidth+","+imgheight); } return fn; } }
好博客就要一起分享哦!分享海报
此处可发布评论
评论(0)展开评论
暂无评论,快来写一下吧
展开评论
他的专栏
他感兴趣的技术