源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java实现的不同图片居中剪裁生成同一尺寸缩略图功能示例

  • 时间:2022-08-17 14:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java实现的不同图片居中剪裁生成同一尺寸缩略图功能示例
本文实例讲述了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);
}
}

[b]PS:这里再为大家推荐几款比较实用的图片处理工具供大家参考使用:[/b] [b]在线图片转换BASE64工具: [/b][url=http://tools.jb51.net/transcoding/img2base64]http://tools.jb51.net/transcoding/img2base64[/url] [b]ICO图标在线生成工具: [/b][url=http://tools.jb51.net/aideddesign/ico_img]http://tools.jb51.net/aideddesign/ico_img[/url] [b]在线Email邮箱图标制作工具: [/b][url=http://tools.jb51.net/email/emaillogo]http://tools.jb51.net/email/emaillogo[/url] [b]在线图片格式转换(jpg/bmp/gif/png)工具: [/b][url=http://tools.jb51.net/aideddesign/picext]http://tools.jb51.net/aideddesign/picext[/url] 更多java相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/915.htm]Java图片操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/869.htm]java日期与时间操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/830.htm]Java操作DOM节点技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/687.htm]Java文件与目录操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/632.htm]Java数据结构与算法教程[/url]》。 希望本文所述对大家java程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部