Java实现的不同图片居中剪裁生成同一尺寸缩略图功能示例
作者:送人玫瑰手留余香 时间:2023-08-23 14:53:15
本文实例讲述了Java实现的不同图片居中剪裁生成同一尺寸缩略图功能。分享给大家供大家参考,具体如下:
因为业务需要,写了这样一个简单类,希望能帮助对有这方面需要的人,高手莫笑
源码如下:
package platform.edu.resource.utils;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 图片工具类
* @author hjn
* @version 1.0 2013-11-26
*
*/
public class ImageUtil {
/**
* 图片等比缩放居中剪裁
* 不管尺寸不等的图片生成的缩略图都是同一尺寸,方便用于页面展示
* @param imageSrc图片所在路径
* @param thumbWidth缩略图宽度
* @param thumbHeight缩略图长度
* @param outFilePath缩略图存放路径
* @throws InterruptedException
* @throws IOException
*/
public static void createImgThumbnail(String imgSrc, int thumbWidth, int thumbHeight, String outFilePath) throws InterruptedException, IOException {
File imageFile=new File(imgSrc);
BufferedImage image = ImageIO.read(imageFile);
Integer width = image.getWidth();
Integer height = image.getHeight();
double i = (double) width / (double) height;
double j = (double) thumbWidth / (double) thumbHeight;
int[] d = new int[2];
int x = 0;
int y = 0;
if (i > j) {
d[1] = thumbHeight;
d[0] = (int) (thumbHeight * i);
y = 0;
x = (d[0] - thumbWidth) / 2;
} else {
d[0] = thumbWidth;
d[1] = (int) (thumbWidth / i);
x = 0;
y = (d[1] - thumbHeight) / 2;
}
File outFile = new File(outFilePath);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
/*等比例缩放*/
BufferedImage newImage = new BufferedImage(d[0],d[1],image.getType());
Graphics g = newImage.getGraphics();
g.drawImage(image, 0,0,d[0],d[1],null);
g.dispose();
/*居中剪裁*/
newImage = newImage.getSubimage(x, y, thumbWidth, thumbHeight);
ImageIO.write(newImage, imageFile.getName().substring(imageFile.getName().lastIndexOf(".") + 1), outFile);
}
}
希望本文所述对大家java程序设计有所帮助。
来源:http://blog.csdn.net/h348592532/article/details/16981271
标签:Java,图片,缩略图
0
投稿
猜你喜欢
SpringMVC Restful api接口实现的代码
2023-11-29 12:34:27
WPF设置窗体可以使用鼠标拖动大小的方法
2023-05-11 12:38:50
Android 图片处理避免出现oom的方法详解
2023-09-07 07:26:12
C# 给PPT中的图表添加趋势线的方法
2022-02-27 10:18:40
C#实现给Word每一页设置不同文字水印的方法详解
2023-07-01 18:49:40
详解Android XML中引用自定义内部类view的四个why
2023-06-01 19:40:41
springboot 跨域配置类及跨域请求配置
2023-01-31 14:27:19
asp.net之生成验证码的方法集锦(一)
2022-09-07 22:37:13
Java使用 try-with-resources 实现自动关闭资源的方法
2022-01-09 06:54:46
公共POI导出Excel方法详解
2023-09-10 22:51:31
C#程序提示“正由另一进程使用,因此该进程无法访问该文件”的解决办法
2022-06-27 04:34:11
mybatis中<if>标签bool值类型为false判断方法
2023-11-20 11:28:33
Android自定义View仿大众点评星星评分控件
2023-07-22 22:37:28
Android Studio实现补间动画
2022-07-01 11:09:44
Java 开发的几个注意点总结
2021-11-30 20:07:11
java实现多线程之定时器任务
2021-07-10 08:56:14
Spring一步到位精通拦截器
2022-01-03 18:31:50
java实现一次性压缩多个文件到zip中的方法示例
2021-11-16 07:24:47
详解kafka中的消息分区分配算法
2021-06-02 08:16:15
java抓包后对pcap文件解析示例
2022-11-23 20:21:53