ITeye博客

JMagick处理图片代码收集

ssxxjjii · 2012-10-10 09:22 · jmagick · 互联网 · Markdown

写在前面的话:

 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。