JMagick处理图片代码收集

写在前面的话:

如果要在Web Application Server(Resin,Tomcat),需要再运行时加入参数: -Djmagick.systemclassloader=no

或者在程序中写入:System.setProperty("jmagick.systemclassloader", "no");

但是,个人在JBoss上,后者不太管用,所以,建议大家用前者,即启动服务器时加启动参数!

(//Tell jmagick.magick.Magick to not use the system ClassLoader)

 

可能遇到的问题:

 

Exceptions/Errors:
java.lang.NoClassDefFoundError: Could not initialize class magick.ImageInfo
java.lang.UnsatisfiedLinkError: no JMagick in java.library.path

Things I've tried so far:
1) copied jmagick.jar to JAVA_HOME/jre/lib/ext
2) copied jmagick.jar to tomcat(your server) common lib & webapp/web-inf/lib
3) set LD_LIBRARY_PATH=/usr/local/lib in tomcat startup script
4) tried setting -Djava.library.path=/usr/local/lib -Djmagick.systemclassloader=no in tomcat startup script

自己收藏一下JMagick处理图片的代码,方便随时查阅:

Java代码 复制代码  收藏代码
  1. package org.wsr.util;   
  2.   
  3. import java.awt.Dimension;     
  4. import java.awt.Point;     
  5. import java.awt.Rectangle;     
  6. import java.io.File;     
  7.      
  8. import magick.CompositeOperator;     
  9. import magick.CompressionType;     
  10. import magick.DrawInfo;     
  11. import magick.ImageInfo;     
  12. import magick.MagickException;     
  13. import magick.MagickImage;     
  14. import magick.PixelPacket;     
  15. import magick.PreviewType;     
  16.      
  17. public class JMagicjWrapper {     
  18.        
  19. public static void main(String[] args) throws MagickException{     
  20.            
  21.         //test for function imageResize      
  22.              
  23. //        JMagicjWrapper.imageResize("pics.jpg", "reSize20x30.png", 20, 30);     
  24. //        JMagicjWrapper.imageResize("pics.jpg", "reSize250x200.jpeg", 250, 200);     
  25. //        JMagicjWrapper.imageResize("pics.jpg", "reSize50x50.jpg", 50, 50);     
  26. //        JMagicjWrapper.imageResize("pics.jpg", "reSize120x120.bmp", 120, 120);     
  27. //        JMagicjWrapper.imageResize("pics.jpg", "reSize.tif", 20, 30);//not create file      
  28. //             
  29.              
  30.         //test for function createWaterPrintByImg      
  31.         JMagicjWrapper.createWaterPrintByImg("f://1.jpg""f://4.jpg""f://watermark.gif"new Point(0,0));     
  32.         //JMagicjWrapper.imageResize("wpl.gif", "logo250x200.gif", 250, 200);     
  33.         //Because file "wpl.gif" may not be release, the later function cause a error, can not open file handle.      
  34.         //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoFull.jpg", new Point(1680,1050));//not create file      
  35.         //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoExt.jpg", new Point(2000,1000));//not create file      
  36.              
  37.         //test for function createWaterPrintByText      
  38.         //This function can not handle Chinese Character, I'll continue to takle the issue       
  39.         //JMagicjWrapper.createWaterPrintByText("pics1.jpg", "wpt.gif", "For Test", new Point(300,300), 100);     
  40.     }     
  41.      
  42.     private static final String[] Type = {     
  43.         ".JPG",     
  44.         ".JPEG",     
  45.         ".BMP",     
  46.         ".GIF",     
  47.         ".PNG"     
  48.     };     
  49.          
  50.     public static boolean checkType(String path){     
  51.         for (int i = 0; i < Type.length; i++) {     
  52.             if (path.toUpperCase().endsWith(Type[i])) {     
  53.                 return true;     
  54.             }else {     
  55.                 continue;     
  56.             }     
  57.         }     
  58.         return false;     
  59.     }     
  60.          
  61.     /**改变图片大小   
  62.      * @param   filePath    原图片位置   
  63.      *          toPath      新图片位置   
  64.      *          width       新图片的宽度   
  65.      *          height      新图片的高度   
  66.      * @return    
  67.      * @throw   
  68.      * @author [email protected] 2010-8-11   
  69.      */     
  70.     public static void imageResize(String filePath, String toPath, int width, int height)     
  71.             throws MagickException {     
  72.         ImageInfo info = null;     
  73.         MagickImage image = null;     
  74.         Dimension imageDim = null;     
  75.         MagickImage scaled = null;     
  76.              
  77.         if (!checkType(filePath) || !checkType(toPath)) {     
  78.             return;     
  79.         }     
  80.              
  81.         try {     
  82.             info = new ImageInfo();   
  83.             image = new MagickImage(info);     
  84.             imageDim = image.getDimension();     
  85.             if (width <= 0 || height <= 0) {     
  86.                 height = 120;     
  87.                 width = 120;     
  88.             }     
  89.             scaled = image.scaleImage(width, height);     
  90.             scaled.setFileName(toPath);     
  91.             scaled.writeImage(info);     
  92.         } finally {     
  93.             if (scaled != null) {     
  94.                 scaled.destroyImages();     
  95.             }     
  96.         }     
  97.     }     
  98.      
  99.     /**创建图片水印   
  100.      * @param       filePath    源文件路径   
  101.      *              toImg       生成文件位置   
  102.      *              logoPath    logo路径   
  103.      *              pos         logo在源图片中的相对位置,以像素点为单位   
  104.      * @return    
  105.      * @throw   MagickException   
  106.      * @author [email protected] 2010-8-11   
  107.      */     
  108.     public static void createWaterPrintByImg(String filePath, String toImg,     
  109.             String logoPath, Point pos) throws MagickException {     
  110.         if (!checkType(filePath) || !checkType(toImg) || !checkType(logoPath)) {     
  111.             return;     
  112.         }   
  113.              
  114.        ImageInfo info = new ImageInfo();     
  115.         MagickImage fImage = null;     
  116.         MagickImage sImage = null;     
  117.         MagickImage fLogo = null;     
  118.         MagickImage sLogo = null;     
  119.         Dimension imageDim = null;   
  120.         Dimension logoDim = null;   
  121.         try {   
  122.             //原来图片   
  123.             fImage = new MagickImage(new ImageInfo(filePath));   
  124.             imageDim = fImage.getDimension();   
  125.             int width = imageDim.width;   
  126.             int height = imageDim.height;   
  127.             sImage = fImage.scaleImage(width, height);   
  128.                  
  129.             fLogo = new MagickImage(new ImageInfo(logoPath));   
  130.             logoDim = fLogo.getDimension();   
  131.             int lw = logoDim.width;   
  132.             int lh = logoDim.height;   
  133.             sLogo = fLogo.scaleImage(lw, lh);   
  134.                  
  135.             //开始打水印,从左上角开始;如果到右边界则重新开始一行的打印(x=0,y=y+h)   
  136.             int startX = 0;   
  137.             int startY = 0;   
  138.             do {                   
  139.                 sImage.compositeImage(CompositeOperator.AtopCompositeOp, sLogo,     
  140.                         startX, startY);   
  141.                 startX += (logoDim.width + 60);   
  142.                 if (startX >= width){   
  143.                     startY += logoDim.height * 2;   
  144.                     startX = 0;   
  145.                 }   
  146.             } while(startY <= height);   
  147.                
  148.             sImage.setFileName(toImg);   
  149.             sImage.writeImage(info);   
  150.         } finally {   
  151.             if (fImage != null) {   
  152.                 fImage.destroyImages();   
  153.             }   
  154.             if (sImage != null) {   
  155.                 sImage.destroyImages();   
  156.             }   
  157.             if (fLogo != null) {   
  158.                 fLogo.destroyImages();   
  159.             }   
  160.             if (sLogo != null) {   
  161.                 sLogo.destroyImages();   
  162.             }   
  163.         }   
  164.     }   
  165.      
  166.     /**创建文字水印   
  167.      * @param       filePath    源文件路径   
  168.      *              toImg       生成文件位置   
  169.      *              text        水印文本   
  170.      *              pos         logo在源图片中的相对位置,以像素点为单位   
  171.      *              pointSize   用于设置点阵大小   
  172.      * @return    
  173.      * @throw   MagickException   
  174.      * @author [email protected] 2010-8-11   
  175.      */     
  176.     public static void createWaterPrintByText(String filePath, String toImg, String text     
  177.             , Point pos, int pointSize)     
  178.             throws MagickException {     
  179.         if (!checkType(filePath) || !checkType(toImg)) {     
  180.             return;     
  181.         }     
  182.              
  183.         if (null == text || "".equals(text)) {     
  184.             text = "[email protected]";     
  185.         }     
  186.              
  187.         ImageInfo info = new ImageInfo(filePath);     
  188.         if (filePath.toUpperCase().endsWith("JPG")     
  189.                 || filePath.toUpperCase().endsWith("JPEG")) {     
  190.             info.setCompression(CompressionType.JPEGCompression); // 压缩类别为JPEG格式      
  191.             info.setPreviewType(PreviewType.JPEGPreview); // 预览格式为JPEG格式      
  192.             info.setQuality(95);     
  193.         }     
  194.         MagickImage aImage = new MagickImage(info);     
  195.         Dimension imageDim = aImage.getDimension();     
  196.         int width = imageDim.width;     
  197.         int height = imageDim.height;     
  198.              
  199.         if (width <= (int)pos.getX() || height <= (int)pos.getY()) {     
  200.             pos.setLocation(00);     
  201.         }     
  202.              
  203.         int a = 0;     
  204.         int b = 0;     
  205.         String[] as = text.split("");     
  206.         for (String string : as) {     
  207.             if (string.matches("[/u4E00-/u9FA5]")) {     
  208.                 a++;     
  209.             }     
  210.             if (string.matches("[a-zA-Z0-9]")) {     
  211.                 b++;     
  212.             }     
  213.         }     
  214.         int tl = a * 12 + b * 6 ;//字符长度      
  215.         MagickImage scaled = aImage.scaleImage(width, height);     
  216.         if (width > tl && height > 5) {     
  217.             DrawInfo aInfo = new DrawInfo(info);     
  218.             aInfo.setFill(PixelPacket.queryColorDatabase("white"));     
  219.             aInfo.setUnderColor(new PixelPacket(65535655356553565535));//设置为透明颜色      
  220.             aInfo.setPointsize(pointSize);     
  221.             // 解决中文乱码问题,自己可以去随意定义个自己喜欢字体,我在这用的微软雅黑      
  222.             String fontPath = "C:/WINDOWS/Fonts/MSIMHEI.TTF";     
  223.             // String fontPath = "/usr/maindata/MSYH.TTF";      
  224.             aInfo.setFont(fontPath);     
  225.             aInfo.setTextAntialias(true);     
  226.             aInfo.setOpacity(0);//透明度      
  227.             aInfo.setText(text);     
  228.             aInfo.setGeometry("+" + ((int)pos.getX() + "+" + (int)pos.getY()));     
  229.             scaled.annotateImage(aInfo);     
  230.         }     
  231.         scaled.setFileName(toImg);     
  232.         scaled.writeImage(info);     
  233.         scaled.destroyImages();     
  234.     }     
  235.      
  236.     /**切取图片   
  237.      * @param       imgPath     原图路径   
  238.      *              toPath      生成文件位置   
  239.      *              w           左上位置横坐标   
  240.      *              h           左上位置竖坐标   
  241.      *              x           右下位置横坐标   
  242.      *              y           右下位置竖坐标   
  243.      * @return    
  244.      * @throw   MagickException   
  245.      * @author [email protected] 2010-8-11   
  246.      */     
  247.     public static void cutImg(String imgPath, String toPath, int w, int h,     
  248.             int x, int y) throws MagickException {     
  249.         ImageInfo infoS = null;     
  250.         MagickImage image = null;     
  251.         MagickImage cropped = null;     
  252.         Rectangle rect = null;     
  253.         try {     
  254.             infoS = new ImageInfo(imgPath);     
  255.             image = new MagickImage(infoS);     
  256.             rect = new Rectangle(x, y, w, h);     
  257.             cropped = image.cropImage(rect);     
  258.             cropped.setFileName(toPath);     
  259.             cropped.writeImage(infoS);     
  260.      
  261.         } finally {     
  262.             if (cropped != null) {     
  263.                 cropped.destroyImages();     
  264.             }     
  265.         }     
  266.     }     
  267.          
  268.     /**删除图片文件   
  269.      * @param   src     图片位置   
  270.      * @return    
  271.      * @throw   
  272.      * @author [email protected] 2010-8-11   
  273.      */     
  274.     public static boolean removeFile(String src) throws SecurityException{     
  275.         try {     
  276.             if (!checkType(src)) {     
  277.                 return false;     
  278.             }     
  279.                  
  280.             File file = new File(src);     
  281.             return file.delete();            
  282.         } catch (Exception e) {     
  283.             e.printStackTrace();     
  284.             return false;     
  285.         }     
  286.     }   
  287.        
  288. }    
package org.wsr.util;

import java.awt.Dimension;  
import java.awt.Point;  
import java.awt.Rectangle;  
import java.io.File;  
  
import magick.CompositeOperator;  
import magick.CompressionType;  
import magick.DrawInfo;  
import magick.ImageInfo;  
import magick.MagickException;  
import magick.MagickImage;  
import magick.PixelPacket;  
import magick.PreviewType;  
  
public class JMagicjWrapper {  
	
public static void main(String[] args) throws MagickException{  
        
        //test for function imageResize   
          
//        JMagicjWrapper.imageResize("pics.jpg", "reSize20x30.png", 20, 30);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize250x200.jpeg", 250, 200);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize50x50.jpg", 50, 50);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize120x120.bmp", 120, 120);  
//        JMagicjWrapper.imageResize("pics.jpg", "reSize.tif", 20, 30);//not create file   
//          
          
        //test for function createWaterPrintByImg   
        JMagicjWrapper.createWaterPrintByImg("f://1.jpg", "f://4.jpg", "f://watermark.gif", new Point(0,0));  
        //JMagicjWrapper.imageResize("wpl.gif", "logo250x200.gif", 250, 200);  
        //Because file "wpl.gif" may not be release, the later function cause a error, can not open file handle.   
        //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoFull.jpg", new Point(1680,1050));//not create file   
        //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoExt.jpg", new Point(2000,1000));//not create file   
          
        //test for function createWaterPrintByText   
        //This function can not handle Chinese Character, I'll continue to takle the issue    
        //JMagicjWrapper.createWaterPrintByText("pics1.jpg", "wpt.gif", "For Test", new Point(300,300), 100);  
    }  
  
    private static final String[] Type = {  
        ".JPG",  
        ".JPEG",  
        ".BMP",  
        ".GIF",  
        ".PNG"  
    };  
      
    public static boolean checkType(String path){  
        for (int i = 0; i < Type.length; i++) {  
            if (path.toUpperCase().endsWith(Type[i])) {  
                return true;  
            }else {  
                continue;  
            }  
        }  
        return false;  
    }  
      
    /**改变图片大小 
     * @param   filePath    原图片位置 
     *          toPath      新图片位置 
     *          width       新图片的宽度 
     *          height      新图片的高度 
     * @return  
     * @throw 
     * @author [email protected] 2010-8-11 
     */  
    public static void imageResize(String filePath, String toPath, int width, int height)  
            throws MagickException {  
        ImageInfo info = null;  
        MagickImage image = null;  
        Dimension imageDim = null;  
        MagickImage scaled = null;  
          
        if (!checkType(filePath) || !checkType(toPath)) {  
            return;  
        }  
          
        try {  
            info = new ImageInfo();
            image = new MagickImage(info);  
            imageDim = image.getDimension();  
            if (width <= 0 || height <= 0) {  
                height = 120;  
                width = 120;  
            }  
            scaled = image.scaleImage(width, height);  
            scaled.setFileName(toPath);  
            scaled.writeImage(info);  
        } finally {  
            if (scaled != null) {  
                scaled.destroyImages();  
            }  
        }  
    }  
  
    /**创建图片水印 
     * @param       filePath    源文件路径 
     *              toImg       生成文件位置 
     *              logoPath    logo路径 
     *              pos         logo在源图片中的相对位置,以像素点为单位 
     * @return  
     * @throw   MagickException 
     * @author [email protected] 2010-8-11 
     */  
    public static void createWaterPrintByImg(String filePath, String toImg,  
            String logoPath, Point pos) throws MagickException {  
        if (!checkType(filePath) || !checkType(toImg) || !checkType(logoPath)) {  
            return;  
        }
          
       ImageInfo info = new ImageInfo();  
        MagickImage fImage = null;  
        MagickImage sImage = null;  
        MagickImage fLogo = null;  
        MagickImage sLogo = null;  
        Dimension imageDim = null;
        Dimension logoDim = null;
        try {
        	//原来图片
            fImage = new MagickImage(new ImageInfo(filePath));
            imageDim = fImage.getDimension();
            int width = imageDim.width;
            int height = imageDim.height;
            sImage = fImage.scaleImage(width, height);
              
            fLogo = new MagickImage(new ImageInfo(logoPath));
            logoDim = fLogo.getDimension();
            int lw = logoDim.width;
            int lh = logoDim.height;
            sLogo = fLogo.scaleImage(lw, lh);
              
            //开始打水印,从左上角开始;如果到右边界则重新开始一行的打印(x=0,y=y+h)
            int startX = 0;
            int startY = 0;
            do {            	
                sImage.compositeImage(CompositeOperator.AtopCompositeOp, sLogo,  
                        startX, startY);
                startX += (logoDim.width + 60);
            	if (startX >= width){
            		startY += logoDim.height * 2;
            		startX = 0;
            	}
    		} while(startY <= height);
            
            sImage.setFileName(toImg);
            sImage.writeImage(info);
        } finally {
            if (fImage != null) {
                fImage.destroyImages();
            }
            if (sImage != null) {
            	sImage.destroyImages();
            }
            if (fLogo != null) {
            	fLogo.destroyImages();
            }
            if (sLogo != null) {
            	sLogo.destroyImages();
            }
        }
    }
  
    /**创建文字水印 
     * @param       filePath    源文件路径 
     *              toImg       生成文件位置 
     *              text        水印文本 
     *              pos         logo在源图片中的相对位置,以像素点为单位 
     *              pointSize   用于设置点阵大小 
     * @return  
     * @throw   MagickException 
     * @author [email protected] 2010-8-11 
     */  
    public static void createWaterPrintByText(String filePath, String toImg, String text  
            , Point pos, int pointSize)  
            throws MagickException {  
        if (!checkType(filePath) || !checkType(toImg)) {  
            return;  
        }  
          
        if (null == text || "".equals(text)) {  
            text = "[email protected]";  
        }  
          
        ImageInfo info = new ImageInfo(filePath);  
        if (filePath.toUpperCase().endsWith("JPG")  
                || filePath.toUpperCase().endsWith("JPEG")) {  
            info.setCompression(CompressionType.JPEGCompression); // 压缩类别为JPEG格式   
            info.setPreviewType(PreviewType.JPEGPreview); // 预览格式为JPEG格式   
            info.setQuality(95);  
        }  
        MagickImage aImage = new MagickImage(info);  
        Dimension imageDim = aImage.getDimension();  
        int width = imageDim.width;  
        int height = imageDim.height;  
          
        if (width <= (int)pos.getX() || height <= (int)pos.getY()) {  
            pos.setLocation(0, 0);  
        }  
          
        int a = 0;  
        int b = 0;  
        String[] as = text.split("");  
        for (String string : as) {  
            if (string.matches("[/u4E00-/u9FA5]")) {  
                a++;  
            }  
            if (string.matches("[a-zA-Z0-9]")) {  
                b++;  
            }  
        }  
        int tl = a * 12 + b * 6 ;//字符长度   
        MagickImage scaled = aImage.scaleImage(width, height);  
        if (width > tl && height > 5) {  
            DrawInfo aInfo = new DrawInfo(info);  
            aInfo.setFill(PixelPacket.queryColorDatabase("white"));  
            aInfo.setUnderColor(new PixelPacket(65535, 65535, 65535, 65535));//设置为透明颜色   
            aInfo.setPointsize(pointSize);  
            // 解决中文乱码问题,自己可以去随意定义个自己喜欢字体,我在这用的微软雅黑   
            String fontPath = "C:/WINDOWS/Fonts/MSIMHEI.TTF";  
            // String fontPath = "/usr/maindata/MSYH.TTF";   
            aInfo.setFont(fontPath);  
            aInfo.setTextAntialias(true);  
            aInfo.setOpacity(0);//透明度   
            aInfo.setText(text);  
            aInfo.setGeometry("+" + ((int)pos.getX() + "+" + (int)pos.getY()));  
            scaled.annotateImage(aInfo);  
        }  
        scaled.setFileName(toImg);  
        scaled.writeImage(info);  
        scaled.destroyImages();  
    }  
  
    /**切取图片 
     * @param       imgPath     原图路径 
     *              toPath      生成文件位置 
     *              w           左上位置横坐标 
     *              h           左上位置竖坐标 
     *              x           右下位置横坐标 
     *              y           右下位置竖坐标 
     * @return  
     * @throw   MagickException 
     * @author [email protected] 2010-8-11 
     */  
    public static void cutImg(String imgPath, String toPath, int w, int h,  
            int x, int y) throws MagickException {  
        ImageInfo infoS = null;  
        MagickImage image = null;  
        MagickImage cropped = null;  
        Rectangle rect = null;  
        try {  
            infoS = new ImageInfo(imgPath);  
            image = new MagickImage(infoS);  
            rect = new Rectangle(x, y, w, h);  
            cropped = image.cropImage(rect);  
            cropped.setFileName(toPath);  
            cropped.writeImage(infoS);  
  
        } finally {  
            if (cropped != null) {  
                cropped.destroyImages();  
            }  
        }  
    }  
      
    /**删除图片文件 
     * @param   src     图片位置 
     * @return  
     * @throw 
     * @author [email protected] 2010-8-11 
     */  
    public static boolean removeFile(String src) throws SecurityException{  
        try {  
            if (!checkType(src)) {  
                return false;  
            }  
              
            File file = new File(src);  
            return file.delete();         
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }
    
}  

参考:

1、http://blog.csdn.net/sulliy/article/details/5805709

2、http://txf2004.iteye.com/blog/989659

3、http://txf2004.iteye.com/blog/989658

猜你喜欢

转载自tdcq.iteye.com/blog/1694824