im4java+GraphicsMagick图片处理

关于graphicsmagick,可以访问其官方网站了解详情点击打开链接 ,网上称之为图片处理领域的瑞士军刀,这评价真够牛逼的!

今天试用了一下,感觉还是不错的,先下载安装GraphicsMagick,再导入im4java开发包

  1. <dependency>  
  2.     <groupId>org.im4java</groupId>  
  3.     <artifactId>im4java</artifactId>  
  4.     <version>1.4.0</version>  
  5. </dependency>  
<dependency>
    <groupId>org.im4java</groupId>
    <artifactId>im4java</artifactId>
    <version>1.4.0</version>
</dependency>

测试代码如下:

  1.      /** 
  2.        * GraphicsMagick的安装目录 
  3.      */  
  4.      private static final String graphicsMagickPath = "C:\\Program Files (x86)\\GraphicsMagick-1.3.21-Q8";  
  5.      /**  
  6.      * 按九宫格位置添加水印  
  7.      * @param srcPath       原图片路径  
  8.      * @param distPath      新图片路径  
  9.      * @param watermarkImg  水印图片路径  
  10.      * @param position      九宫格位置[1-9],从上往下,从左到右排序  
  11.      * @param x         横向边距  
  12.      * @param y         纵向边距  
  13.      * @param alpha     透明度  
  14.      * @throws IOException  
  15.      * @throws InterruptedException  
  16.      * @throws IM4JavaException  
  17.      */    
  18.     public void watermarkImg(String srcPath,String distPath,String watermarkImg, int position, int x, int y, int alpha) throws IOException, InterruptedException, IM4JavaException{    
  19.         int[] watermarkImgSide = getImageSize(watermarkImg);    
  20.         int[] srcImgSide = getImageSize(srcPath);    
  21.         int[] xy = getXY(srcImgSide, watermarkImgSide, position, x, y);    
  22.         addWatermarkToImg(srcPath,distPath,watermarkImg,watermarkImgSide[0],watermarkImgSide[1],xy[0],xy[1],alpha);    
  23.     }    
  24.         
  25.     
  26.     /** 
  27.      * 获取图片尺寸 
  28.      * @param imgPath 
  29.      * @return 
  30.      * @throws IOException 
  31.      */  
  32.     private  int[] getImageSize(String imgPath) throws IOException {    
  33.         int[] size = new int[2];    
  34.         Image img = ImageIO.read(new File(imgPath));    
  35.         size[0] = img.getWidth(null);    
  36.         size[1] =img.getHeight(null);    
  37.         return size;    
  38.     }    
  39.       
  40.     private  int[] getXY(int[] image, int[] watermark, int position, int x, int y) {    
  41.         int[] xy = new int[2];    
  42.         if(position==1){    
  43.             xy[0] = x;    
  44.             xy[1] = y;    
  45.         }else if(position==2){    
  46.             xy[0] = (image[0]-watermark[0])/2;          //横向边距    
  47.             xy[1] = y;  //纵向边距    
  48.         }else if(position==3){    
  49.             xy[0] = image[0]-watermark[0]-x;    
  50.             xy[1] = y;    
  51.         }else if(position==4){    
  52.             xy[0] = x;    
  53.             xy[1] = (image[1]-watermark[1])/2;    
  54.         }else if(position==5){    
  55.             xy[0] = (image[0]-watermark[0])/2;    
  56.             xy[1] =  (image[1]-watermark[1])/2;    
  57.         }else if(position==6){    
  58.             xy[0] = image[0]-watermark[0]-x;    
  59.             xy[1] = (image[1] - watermark[1])/2;     
  60.         }else if(position==7){    
  61.             xy[0] = x;    
  62.             xy[1] = image[1] - watermark[1] - y;    
  63.         }else if(position==8){    
  64.             xy[0] =  (image[0]-watermark[0])/2;    
  65.             xy[1] = image[1] - watermark[1] - y;    
  66.         }else{    
  67.             xy[0] = image[0]-watermark[0]-x;    
  68.             xy[1] = image[1] - watermark[1] - y;    
  69.         }    
  70.         return xy;    
  71.     }  
  72.         
  73.         
  74.     /**  
  75.      * 添加图片水印  
  76.      * @param srcPath       原图片路径  
  77.      * @param distPath      新图片路径  
  78.      * @param watermarkImg      水印图片路径  
  79.      * @param width     水印宽度(可以于水印图片大小不同)  
  80.      * @param height    水印高度(可以于水印图片大小不同)  
  81.      * @param x     水印开始X坐标  
  82.      * @param y     水印开始Y坐标  
  83.      * @param alpha     透明度[0-100]  
  84.      * @throws IOException  
  85.      * @throws InterruptedException  
  86.      * @throws IM4JavaException  
  87.      */    
  88.     private void addWatermarkToImg(String srcPath,String distPath,String watermarkImg, int width, int height, int x, int y, int alpha) throws IOException, InterruptedException, IM4JavaException{    
  89.         CompositeCmd cmd = new CompositeCmd(true);  
  90.         cmd.setSearchPath(graphicsMagickPath);        
  91.         IMOperation op = new IMOperation();    
  92.         op.dissolve(alpha);    
  93.         op.geometry(width, height, x, y);  
  94.         op.addImage(watermarkImg,srcPath,distPath);      
  95.         cmd.run(op);    
  96.     }       
  97.     
  98.     /**  
  99.      * 把文字转化为一张背景透明的png图片  
  100.      * @param str 文字的内容  
  101.      * @param fontType 字体,例如宋体  
  102.      * @param fontSize 字体大小  
  103.      * @param colorStr 字体颜色,不带#号,例如"990033"  
  104.      * @param outfile  png图片的路径  
  105.      * @throws Exception  
  106.      */    
  107.     public  void converFontToImage(String str,String fontType,int fontSize,String colorStr, String outfile) throws Exception{    
  108.         Font font=new Font(fontType,Font.BOLD,fontSize);    
  109.         //获取font的样式应用在str上的整个矩形    
  110.         Rectangle2D r=font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(11),false,false));    
  111.         int unitHeight=(int)Math.floor(r.getHeight());//获取单个字符的高度    
  112.         //获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度    
  113.         int width=(int)Math.round(r.getWidth())+1;    
  114.         int height=unitHeight+3;//把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度    
  115.         //创建图片    
  116.         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
  117.         Graphics2D g2d = image.createGraphics();    
  118.         image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);    
  119.         g2d.dispose();    
  120.         g2d = image.createGraphics();    
  121.         g2d.setColor(Color.WHITE);    
  122.         g2d.setStroke(new BasicStroke(1));    
  123.         g2d.setColor(new Color(Integer.parseInt(colorStr, 16)));//在换成所需要的字体颜色    
  124.         g2d.setFont(font);    
  125.         g2d.drawString(str, 0,font.getSize());    
  126.           
  127.         File file=new File(outfile);  
  128.         ImageIO.write(image, "png", file);//输出png图片    
  129.     }  
  130.       
  131.     /**   
  132.      * 根据坐标裁剪图片   
  133.      *   
  134.      * @param srcPath   要裁剪图片的路径   
  135.      * @param newPath   裁剪图片后的路径   
  136.      * @param x   起始横坐标   
  137.      * @param y   起始纵坐标   
  138.      * @param x1  结束横坐标   
  139.      * @param y1  结束纵坐标   
  140.      */      
  141.     public void cutImage(String srcPath, String newPath, int x, int y, int x1,int y1)  throws Exception {      
  142.         int width = x1 - x;      
  143.         int height = y1 - y;      
  144.         IMOperation op = new IMOperation();      
  145.         op.addImage(srcPath);      
  146.         /**  width:裁剪的宽度    * height:裁剪的高度 * x:裁剪的横坐标 * y:裁剪纵坐标  */      
  147.         op.crop(width, height, x, y);      
  148.         op.addImage(newPath);      
  149.         ConvertCmd convert = new ConvertCmd(true);    
  150.         convert.setSearchPath(graphicsMagickPath);   
  151.         convert.run(op);      
  152.     }  
  153.       
  154.     /**   
  155.      * 根据尺寸缩放图片   
  156.      * @param width  缩放后的图片宽度   
  157.      * @param height  缩放后的图片高度   
  158.      * @param srcPath   源图片路径   
  159.      * @param newPath   缩放后图片的路径   
  160.      */      
  161.     public void zoomImage(Integer width, Integer height, String srcPath, String newPath) throws Exception {      
  162.         IMOperation op = new IMOperation();      
  163.         op.addImage(srcPath);      
  164.         if(width == null){//根据高度缩放图片    
  165.             op.resize(null, height);        
  166.         }else if(height == null){//根据宽度缩放图片    
  167.             op.resize(width, null);    
  168.         }else {    
  169.             op.resize(width, height);    
  170.         }    
  171.         op.addImage(newPath);      
  172.         ConvertCmd convert = new ConvertCmd(true);  
  173.         convert.setSearchPath(graphicsMagickPath);   
  174.         convert.run(op);      
  175.     }  
  176.       
  177.     /** 
  178.      * 给图片加文字水印 
  179.      * 可以加英文水印,中文会报错或者乱码,变通方法是将文字生成图片,然后加水印 
  180.      * @param srcPath 
  181.      * @param content 
  182.      * @throws Exception 
  183.      */  
  184.     public void addImgText(String srcPath,String content) throws Exception {      
  185. //      IMOperation op = new IMOperation();      
  186.         GMOperation op = new GMOperation();  
  187.         op.font("Vrinda");    
  188.         op.gravity("southeast");    
  189.         op.pointsize(38).fill("#000000").draw("text 10,10 "+new String(content.getBytes("utf-8"),"gbk"));   //("x1 x2 x3 x4") x1 格式,x2 x轴距离 x3 y轴距离  x4名称,文字内容        
  190.         op.addImage();      
  191.         op.addImage();      
  192.         ConvertCmd convert = new ConvertCmd(true);      
  193.         convert.setSearchPath(graphicsMagickPath);   
  194.         try {    
  195.           convert.run(op,srcPath,srcPath);    
  196.         } catch (Exception e) {    
  197.             e.printStackTrace();    
  198.         }    
  199.     }  
  200.       
  201.     /**  
  202.      * 图片旋转  
  203.      *  
  204.      * @param srcImagePath  
  205.      * @param destImagePath  
  206.      * @param angle  
  207.      */    
  208.     public void rotate(String srcImagePath, String destImagePath, double angle) {    
  209.         try {    
  210.             IMOperation op = new IMOperation();    
  211.             op.rotate(angle);    
  212.             op.addImage(srcImagePath);    
  213.             op.addImage(destImagePath);    
  214.             ConvertCmd cmd = new ConvertCmd(true);   
  215.             cmd.setSearchPath(graphicsMagickPath);  
  216.             cmd.run(op);    
  217.         } catch (Exception e) {    
  218.             e.printStackTrace();    
  219.         }    
  220.     }  
  221.       
  222.     /**  
  223.      * 图片合成  
  224.      * @param args  
  225.      * @param maxWidth  
  226.      * @param maxHeight  
  227.      * @param newpath  
  228.      * @param mrg  
  229.      * @param type 1:横,2:竖  
  230.      */    
  231.     public void montage(String[] args,Integer maxWidth,Integer maxHeight,String newpath,Integer mrg,String type) {    
  232.         IMOperation op = new IMOperation();    
  233.         ConvertCmd cmd = new ConvertCmd(true);  
  234.         cmd.setSearchPath(graphicsMagickPath);  
  235.         String thumb_size = maxWidth+"x"+maxHeight+"^";    
  236.         String extent = maxWidth+"x"+maxHeight;    
  237.         if("1".equals(type)){    
  238.             op.addRawArgs("+append");    
  239.         }else if("2".equals(type)){    
  240.             op.addRawArgs("-append");    
  241.         }    
  242.             
  243.         op.addRawArgs("-thumbnail",thumb_size);    
  244.         op.addRawArgs("-gravity","center");    
  245.         op.addRawArgs("-extent",extent);    
  246.             
  247.         Integer border_w = maxWidth / 40;    
  248.         op.addRawArgs("-border",border_w+"x"+border_w);    
  249.         op.addRawArgs("-bordercolor","#ccc");    
  250.             
  251.         op.addRawArgs("-border",1+"x"+1);    
  252.         op.addRawArgs("-bordercolor","#fff");    
  253.             
  254.         for(String img : args){    
  255.             op.addImage(img);    
  256.         }    
  257.         if("1".equals(type)){    
  258.             Integer whole_width = ((mrg / 2) +1 + border_w + maxWidth + border_w + (mrg / 2) +1)*args.length - mrg;    
  259.             Integer whole_height = maxHeight + border_w + 1;    
  260.             op.addRawArgs("-extent",whole_width + "x" +whole_height);    
  261.         }else if("2".equals(type)){    
  262.             Integer whole_width = maxWidth + border_w + 1;    
  263.             Integer whole_height = ((mrg / 2) +1 + border_w + maxHeight + border_w + (mrg / 2) +1)*args.length - mrg;    
  264.             op.addRawArgs("-extent",whole_width + "x" +whole_height);    
  265.         }    
  266.         op.addImage(newpath);    
  267.         try {    
  268.             cmd.run(op);    
  269.         } catch (Exception e) {    
  270.             e.printStackTrace();    
  271.         }    
  272.     }  
  273.       
  274.     public static void main(String[] args) {  
  275.         try {    
  276.             String src="F://src.jpg";  //需要加水印的源图片    
  277.             String desc="F://desc.jpg"; //生成的水印图片的路径    
  278.             String water="F://water.png"; //用中文转换成的背景透明的png图片    
  279.             String fontType="C:\\Windows\\Fonts\\simsun.ttc"//指定字体文件为宋体    
  280.             String colorStr="000"//颜色    
  281.             int fontSize=18;    
  282.                 
  283.             WaterTest watermark=new WaterTest();    
  284.                 
  285.    
  286.             watermark.converFontToImage("中国四川成都", fontType, fontSize, colorStr, water);    
  287.                 
  288.     
  289.             watermark.watermarkImg(src, desc, water, 520,20100);    
  290. //              watermark.cutImage(src, desc, 0, 0, 300, 300);  
  291. //              watermark.zoomImage(100, null, src, desc);  
  292. //              watermark.addImgText(src, "中国四成都");  
  293. //            watermark.rotate(src, desc, 90);  
  294.   
  295. //            String[] files = new String[5];    
  296. //            files[0] = "f://1.jpg";    
  297. //            files[1] = "f://2.png";  
  298. //            files[2] = "f://2.png";   
  299. //            files[3] = "f://2.png";   
  300. //            watermark.montage(files, 280, 200, "f://liboy1.jpg", 0,"2");  
  301.                 
  302.         } catch (Exception e) {    
  303.             // TODO Auto-generated catch block    
  304.             e.printStackTrace();    
  305.         }    
  306.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值