---
title: "JMagick处理图片代码收集 "
author: "ssxxjjii"
date: "2012-10-10T09:22:04Z"
tags: []
categories: ["互联网"]
slug: "jmagick"
draft: false
lastmod: "2012-10-10T09:22:04Z"
id: 1694824
url: "https://tdcq.iteye.com/blog/1694824"
---

写在前面的话：

 

**如果要在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代码 [![复制代码](http://tdcq.iteye.com/images/icon_copy.gif)](http://tdcq.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://tdcq.iteye.com/images/icon_star.png)![](http://tdcq.iteye.com/images/spinner.gif)]()

001. **package** org.wsr.util;
002. **import** java.awt.Dimension;
003. **import** java.awt.Point;
004. **import** java.awt.Rectangle;
005. **import** java.io.File;
006. **import** magick.CompositeOperator;
007. **import** magick.CompressionType;
008. **import** magick.DrawInfo;
009. **import** magick.ImageInfo;
010. **import** magick.MagickException;
011. **import** magick.MagickImage;
012. **import** magick.PixelPacket;
013. **import** magick.PreviewType;
014. **public** **class** JMagicjWrapper {
015. **public** **static** **void** main(String\[] args) **throws** MagickException{
016. //test for function imageResize
017. //        JMagicjWrapper.imageResize("pics.jpg", "reSize20x30.png", 20, 30);
018. //        JMagicjWrapper.imageResize("pics.jpg", "reSize250x200.jpeg", 250, 200);
019. //        JMagicjWrapper.imageResize("pics.jpg", "reSize50x50.jpg", 50, 50);
020. //        JMagicjWrapper.imageResize("pics.jpg", "reSize120x120.bmp", 120, 120);
021. //        JMagicjWrapper.imageResize("pics.jpg", "reSize.tif", 20, 30);//not create file
022. //
023. //test for function createWaterPrintByImg
024. JMagicjWrapper.createWaterPrintByImg("f://1.jpg", "f://4.jpg", "f://watermark.gif", **new** Point(0,0));
025. //JMagicjWrapper.imageResize("wpl.gif", "logo250x200.gif", 250, 200);
026. //Because file "wpl.gif" may not be release, the later function cause a error, can not open file handle.
027. //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoFull.jpg", new Point(1680,1050));//not create file
028. //JMagicjWrapper.createWaterPrintByImg("pics.jpg", "wpl.gif", "logoExt.jpg", new Point(2000,1000));//not create file
029. //test for function createWaterPrintByText
030. //This function can not handle Chinese Character, I'll continue to takle the issue
031. //JMagicjWrapper.createWaterPrintByText("pics1.jpg", "wpt.gif", "For Test", new Point(300,300), 100);
032. }
033. **private** **static** **final** String\[] Type = {
034. ".JPG",
035. ".JPEG",
036. ".BMP",
037. ".GIF",
038. ".PNG"
039. };
040. **public** **static** **boolean** checkType(String path){
041. **for** (**int** i = 0; i &lt; Type.length; i++) {
042. **if** (path.toUpperCase().endsWith(Type\[i])) {
043. **return** **true**;
044. }**else** {
045. **continue**;
046. }
047. }
048. **return** **false**;
049. }
050. /\*\*改变图片大小
051. * @param   filePath    原图片位置
052. *          toPath      新图片位置
053. *          width       新图片的宽度
054. *          height      新图片的高度
055. * @return
056. * @throw
057. * @author sulliy@sina.com 2010-8-11
058. \*/
059. **public** **static** **void** imageResize(String filePath, String toPath, **int** width, **int** height)
060. **throws** MagickException {
061. ImageInfo info = **null**;
062. MagickImage image = **null**;
063. Dimension imageDim = **null**;
064. MagickImage scaled = **null**;
065. **if** (!checkType(filePath) || !checkType(toPath)) {
066. **return**;
067. }
068. **try** {
069. info = **new** ImageInfo();
070. image = **new** MagickImage(info);
071. imageDim = image.getDimension();
072. **if** (width &lt;= 0 || height &lt;= 0) {
073. height = 120;
074. width = 120;
075. }
076. scaled = image.scaleImage(width, height);
077. scaled.setFileName(toPath);
078. scaled.writeImage(info);
079. } **finally** {
080. **if** (scaled != **null**) {
081. scaled.destroyImages();
082. }
083. }
084. }
085. /\*\*创建图片水印
086. * @param       filePath    源文件路径
087. *              toImg       生成文件位置
088. *              logoPath    logo路径
089. *              pos         logo在源图片中的相对位置，以像素点为单位
090. * @return
091. * @throw   MagickException
092. * @author sulliy@sina.com 2010-8-11
093. \*/
094. **public** **static** **void** createWaterPrintByImg(String filePath, String toImg,
095. String logoPath, Point pos) **throws** MagickException {
096. **if** (!checkType(filePath) || !checkType(toImg) || !checkType(logoPath)) {
097. **return**;
098. }
099. 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 &gt;= width){
126. startY += logoDim.height * 2;
127. startX = 0;
128. }
129. } **while**(startY &lt;= 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 &lt;= (**int**)pos.getX() || height &lt;= (**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 &gt; tl && height &gt; 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](http://blog.csdn.net/sulliy/article/details/5805709)

2、[http://txf2004.iteye.com/blog/989659](http://txf2004.iteye.com/blog/989659)

3、[http://txf2004.iteye.com/blog/989658](http://txf2004.iteye.com/blog/989658)