手把手教你整合Java+ImageMagick。

java 利用Img4JavaUtil 工具对图片做缩略图、裁剪等常用方法

  1. 安装ImageMagick最新版本, 并设置path系统环境变量。获取安装路径(用于设置java初始化ImageMagick)。
    1)下载地址:http://www.imagemagick.org/script/download.php
    2)选择版本:ImageMagick-7.0.8-33-Q16-x64-dll.exe
    3)在安装过程中记得勾选Install legacy utilities(e.g. convert)选项。

    4)添加到系统path环境变量:

    5)打开命令行运行magick -help测试是否配置成功


6) JDK版本选择1.8


2.ImageMagick添加pom.xml的支持
im4java是一个封装DOM操作的类,用于java中拼接cmd命令代码 来实现图片裁剪的。

     <dependency><groupId>org.im4java</groupId><artifactId>im4java</artifactId><version>1.4.0</version></dependency>
  1. 静态方法中初始化ImageMagick 。 只有windows环境下才需要,linux不需要。
    设置全局的方法:

    ProcessStarter.setGlobalSearchPath(“D:/Program Files/ImageMagick-7.0.8-Q16”);

4.献上我封装好的方法。(其中取中心化裁剪,和中心化缩略图最为好用!!!)

package com.bdxh.fileserver.utils;import java.io.File;
import java.io.IOException;import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.Info;
import org.im4java.core.InfoException;
import org.im4java.process.ProcessStarter;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;public class Img4JavaUtil {static {//判断是否是windows系统if(OSinfo.isWindows()) {System.out.println("------------ START 初始化ImageMagickPath -------------");ProcessStarter.setGlobalSearchPath("D:/Program Files/ImageMagick-7.0.8-Q16");System.out.println("------------ END 初始化ImageMagickPath -------------");}}/*** 裁剪图片* @param inImgPath 源图片地址* @param outImgPath 目标图片地址* @param width 宽* @param height 高* @param x 起点横坐标* @param y 起点纵坐标* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public static void cropImg(String inImgPath,String outImgPath,Integer width,Integer height,Integer x,Integer y) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//宽  高 起点横坐标 起点纵坐标operation.crop(width, height, x, y);operation.addImage(outImgPath);cmd.run(operation);}/*** 裁剪图片* @param inImgPath 源图片地址* @param outImgPath 目标图片地址* @param width 宽* @param height 高* @param x 起点横坐标* @param y 起点纵坐标* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void cropImg(String inImgPath,String outImgPath,Integer width,Integer height,Integer x,Integer y) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//宽  高 起点横坐标 起点纵坐标operation.crop(width, height, x, y);operation.addImage(outImgPath);cmd.run(operation);}/*** 裁剪中心化图片* @param inImgPath 源图片地址* @param outImgPath 目标图片地址* @param width 宽* @param height 高* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void cropCenterImg(String inImgPath,String outImgPath,Integer width,Integer height) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();Info info = new Info(inImgPath);Integer init_width = info.getImageWidth();Integer init_height = info.getImageHeight();// 如果裁剪的宽高都大于原始图片宽高 则先等比放大再裁剪if(width>init_width || height>init_height){// 等比放大Integer temp_width = width;if(init_height<init_width){// 如果原图宽大于高 则以高为准放大temp_width = null;}operation.resize(temp_width, height);}operation.addImage(inImgPath);//宽  高 起点横坐标 起点纵坐标operation.gravity("center");operation.crop(width, height, 0, 0);operation.addImage(outImgPath);cmd.run(operation);}/*** 得到图片的信息* @throws InfoException*/public static String getImgInfo(String inImgPath) throws InfoException{Info info = new Info(inImgPath);System.out.println(info.getImageHeight());System.out.println(info.getImageWidth());return info.getImageWidth()+"x"+info.getImageHeight();}/*** 等比缩放图片* @param inImgPath* @param outImgPath* @param width 宽度不为空时 以宽度为准,为空时以高度为准(不能同时为空)* @param height* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public static void resizeImg(String inImgPath,String outImgPath,Integer width,Integer height) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//等比缩放图片operation.resize(width, height);//高度为null则按宽度缩放operation.addImage(outImgPath);cmd.run(operation);}/*** 等比缩放   (使用像素平均缩小)* @param inImgPath* @param outImgPath* @param width* @param height* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public static void scaleImg(String inImgPath,String outImgPath,Integer width,Integer height) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//缩略图operation.scale(width,height);operation.addImage(outImgPath);cmd.run(operation);}/*** 把原图裁剪成正方形* @param inImgPath* @param operation* @return* @throws IM4JavaException*/public static IMOperation getCenterSquare(String inImgPath,IMOperation operation)throws IM4JavaException{Info info = new Info(inImgPath);Integer init_width = info.getImageWidth();Integer init_height = info.getImageHeight();if (init_width > init_height) {init_width = init_height;} else if (init_width < init_height) {init_height = init_width;}operation.gravity("center");operation.crop(init_width, init_height,0,0);return operation;}/*** 缩略图 (专门用于将非常大的图像缩小为小缩略图)* @param inImgPath* @param outImgPath* @param width* @param height* @param editType = c 取中心化缩略图,否则取原等比缩略图* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void thumbnailImg(String inImgPath,String outImgPath,Integer width,Integer height,String editType) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//取中心化或者原图同比if(editType!=null && editType.equals("c")) {//分析宽高 先原图等比生成缩略图(缩略规则按原图大的一边为准取值)Info info = new Info(inImgPath);Integer init_width = info.getImageWidth();Integer init_height = info.getImageHeight();double width_v = (double)init_width/width;double height_v = (double)init_height/height;//原图是正方形/*if(init_width == init_height){operation.thumbnail(width,height);//原图是宽大于高的长方形}else */if(init_width >= init_height){if (width_v >= height_v) {operation.thumbnail(null,height);} else if (width_v < height_v) {operation.thumbnail(width,null);}//原图是高大于宽的长方形}else if(init_width < init_height){if (width_v > height_v) {operation.thumbnail(null,height);} else if (width_v <= height_v) {operation.thumbnail(width,null);}}//再中心化截图operation.gravity("center");operation.crop(width, height,0,0);}else{operation.thumbnail(width,height);}operation.addImage(outImgPath);cmd.run(operation);}/*** 旋转图片* @param inImgPath* @param outImgPath* @param x 旋转角度* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void rotateImg(String inImgPath,String outImgPath,Double x) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);operation.rotate(x);operation.addImage(outImgPath);cmd.run(operation);}/*** 缩略图 (原图画质缩略)* @param inImgPath* @param outImgPath* @param width* @param height* @param editType* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void sampleImg(String inImgPath,String outImgPath,Integer width,Integer height,String editType) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);//取中心化或者原图同比if(editType!=null && editType.equals("center")) {getCenterSquare(inImgPath,operation);}operation.sample(width,height);
//        operation.quality(5.0); //设置生成图片质量operation.addImage(outImgPath);cmd.run(operation);}/*** 将图片变成黑白图片* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public void monochrome(String inImgPath,String outImgPath) throws IOException, InterruptedException, IM4JavaException{ConvertCmd cmd = new ConvertCmd();IMOperation operation = new IMOperation();operation.addImage(inImgPath);operation.monochrome();operation.addImage(outImgPath);cmd.run(operation);}/** * 给图片加水印 * @param srcPath            源图片路径 */public static void addImgText(String inImgPath,String outImgPath,String str)throws IOException, InterruptedException, IM4JavaException{IMOperation operation = new IMOperation();operation.font("宋体").gravity("southeast").pointsize(18).fill("#BCBFC8").draw("text 5,5 "+str);operation.encoding("UTF-8");operation.addImage();operation.addImage();ConvertCmd convert = new ConvertCmd();convert.run(operation, inImgPath,outImgPath);}/*** 创建文件名称* @param folder* @param fileName* @return*/public static File createFile(String folder, String fileName) {File serverFile;String suffix = getSuffix(fileName);String destFileName = null;long timeMillis = System.currentTimeMillis();int i = 1;do {if (suffix.length() == 0) {destFileName = String.format("%s_%d", timeMillis, i++);} else {destFileName = String.format("%s_%d.%s", timeMillis, i++, suffix);}serverFile = new File(folder, destFileName);} while (serverFile.exists());serverFile.getParentFile().mkdirs();return serverFile;}/*** 生成图片名称(根据旧的文件类型)* @param rootPath 文件目录地址* @param oldFileName 文件相对路径* @param type 操作类型 c :中心化、o :原比例、自定义* @return*/public  String  createFileName(String rootPath,String oldFileName,int width,int height,String type) {// 初始化目录String pathName = oldFileName.substring(0,oldFileName.lastIndexOf("/"));String newFilePath = rootPath + pathName;File dirFile = new File(newFilePath);if (!dirFile.exists()) {dirFile.mkdirs();}// 生成文件名String imgName =oldFileName.substring(oldFileName.lastIndexOf("/"));String a = imgName.substring(0,imgName.lastIndexOf("."));String b = imgName.substring(imgName.lastIndexOf("."));return  newFilePath + a + "_"+ width + "x"+ height +"_" + type + b;}/*** 截取文件名称* @param filePath* @return*/public static String getSuffix(String filePath){return filePath.substring(filePath.lastIndexOf("."));}/*** main方法测试* @param args* @throws IOException* @throws InterruptedException* @throws IM4JavaException*/public static void main(String[] args) throws IOException, InterruptedException, IM4JavaException{String inImgPath = "D:\\Documents\\Pictures\\1.jpg";String outImgPath = "D:\\Documents\\Pictures\\2.jpg";Img4JavaUtil test = new Img4JavaUtil();// 中心化缩略图(常用)test.thumbnailImg(inImgPath,outImgPath,400,400,"c");// 裁剪图片
//        test.cropImg(inImgPath,outImgPath+"裁剪-300x300.jpg",300,300,0,0);// 获取图片信息
//        test.getImgInfo(inImgPath);// 等比缩放
//        test.resizeImg(inImgPath,outImgPath+"等比缩放-w300.jpg",300,null);// 旋转图片
//        test.rotateImg(inImgPath,outImgPath+"旋转45.jpg",45.0);// 转黑白图片
//        test.monochrome(inImgPath,outImgPath+"转黑白.jpg");// 加水印
//        test.addImgText(inImgPath,outImgPath+"加水印.jpg","CCTV-100");// 原图质量缩放
//        test.scaleImg(inImgPath,outImgPath+"缩略图scale.jpg",100,null);// 自动中心化裁剪
//        test.cropCenterImg(inImgPath,outImgPath+"中心.jpg",400,300);}
}

5.测试一波
原图:

做了400x400的中心化缩略图效果:

完美!

Java整合ImageMagick图片裁剪工具,奉上实现图片处理的常用方法,如:自由裁剪、中心化裁剪、缩略图、中心化缩略图等。 工具方法类相关推荐

  1. java原生的Graphics2D_背景图上添加图片

    1.初始化 public void init(){private String backgroundImgPath="背景图片位置";private String contentI ...

  2. 如何显示服务器上的图片,显示服务器上的图片怎么写

    显示服务器上的图片怎么写 内容精选 换一换 内容审核服务输入图片参数"Image"是图片的base64编码,本节介绍利用谷歌浏览器进行图片格式转换,获取图片的base64编码信息. ...

  3. java将图片放进mysql中_在java代码中怎么从服务器上把图片拿来放到数据库里

    展开全部 看你用的是么数据库,一般是读取后转e68a84e8a2ad3231313335323631343130323136353331333431346430成二进制blob格式存入数据库的BLOB ...

  4. java 对话框 显示图片_Java对话框上显示图片

    手掌心 其实有很多种方法可以解决图片显示大小的问题:使用photoshop修改. 优点是可以节省系统资源, 显示图片的时候,不用做处理,缺点是需要了解ps的基本操作使用JDialog 自定义对话框. ...

  5. java读流方式,下载网络上的图片

    本工具类支持url的list集合,具体实现如下所示: public static void download(ArrayList<String> listUrl,String downlo ...

  6. 怎么压缩图片,电脑上压缩图片的方法

    怎样实现图片压缩呢?当下除了短视频,最盛行的信息传播方式应该就属图片信息传播了.所以日常生活中总是会通过图片来传递一些信息,那么在进行图片信息传输时就总会遇到关于图片压缩的问题,那么我们应给怎样实现这 ...

  7. js 裁剪图片压缩并且上传 图片

    今天接到一个比较懒的后台的要求:后台要求在裁剪图片的同时,根据文件大小来按不同比例压缩图片. 页面代码 <!--** * *----------Created by 黄伟峰 on 2018/6/ ...

  8. 爬虫 图片下载器:从图片分享网站下载图片并进行分类整理

    目录 前言 1. 图片下载器概述 2. 环境准备 3. 分析目标网站 4. 使用Python编写图片下载器 4.1 安装依赖库 4.2 获取图片链接 4.3 下载图片 4.4 图片分类整理 5. 总结 ...

  9. Java复习第11天---11.4---Java8新特性---Stream流常用方法3和综合案例

    Java复习第11天---11.4---Java8新特性---Stream流常用方法3和综合案例 目录 文章目录 1.count:计数-终结方法 2.limit:取前几个元素-延迟方法 3.skip: ...

最新文章

  1. 单例设计模式singleton
  2. 欢乐拼图发红包微信小程序开发过程实录成品展示
  3. 人月神话之阅读笔记01
  4. VTK:超树网格源用法实战
  5. 2018-2019-1 20165234 《信息安全系统设计基础》第四周学习总结
  6. 深度学习简明教程系列 —— 经典模型(合集)
  7. 计算机组成原理罗克露课后答案,计算机组成原理[完整版](罗克露)(全)原版教案.ppt...
  8. Kindle Touch 5.3.7上手使用指南
  9. linux日志过大怎么查看,Linux查看日志常用命令
  10. 《站在巨人的肩膀上-英语交流会有感》
  11. 谈谈用统一网关gate的利与弊
  12. python描述对象静态特性的数据为_对于需要几个单位共同负担的一张原始凭证上的支出,应根据其他单位负担部分为其提高( )。...
  13. 项目管理知识体系指南学习(三)项目整合管理
  14. 【无标题】2021年施工员-装饰方向-岗位技能(施工员)考试题及施工员-装饰方向-岗位技能(施工员)考试试卷
  15. 18行的python快递查询
  16. 微信小程序前端备忘录记事本搜索功能
  17. NULL,0,`0`,`\0`,0你分得清吗?
  18. 回溯法解决01背包-非递归算法-效率低
  19. 软件的破解原理是什么?
  20. 构建Lua解释器Part8:构建完整的语法分析器(下)

热门文章

  1. android自定义View之(六)------高仿华为荣耀3C的圆形刻度比例图(ShowPercentView)
  2. 前端必备技能之----节流
  3. java的matcher方法_Java-Android-正则表达式-Matcher方法
  4. switch 计算器?!
  5. java 乐观锁和悲观锁,Threadlocal
  6. 【Python正则表达式】 批量去除视频名称中的网址
  7. 关于Android 11HDMI设置-显示-HDMI无法选择呈灰色的定位流程及方式
  8. iOS之CALayer与核心动画(一)
  9. 删除表操作——drop、truncate和delete用法详解
  10. Java中request有哪些方法,Java--获取request中所有参数的方法