java对图片的裁剪(包括来自网络的图片)

时间:2022-08-11 08:59:49
  1 import java.awt.Rectangle;
  2 import java.awt.image.BufferedImage;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.InputStream;
  6 import java.net.HttpURLConnection;
  7 import java.net.URL;
  8 import java.util.Calendar;
  9 import java.util.Date;
 10 import java.util.Iterator;
 11 import java.util.Random;
 12 
 13 import javax.imageio.ImageIO;
 14 import javax.imageio.ImageReadParam;
 15 import javax.imageio.ImageReader;
 16 import javax.imageio.stream.ImageInputStream;
 17 
 18 /**
 19  * 剪裁图片(从网络上获取图片) 21  * @description
 22  * @time  2013-2-24下午02:07:00 24  * @version
 25  */
 26 public class CutImageUtil {
 27 
 28     private static final String DESTIMAGEPATH = "e://";
 29     private static final String BASE_IMAGE_URL="http://pimages3.tianjimedia.com/resources/product/";
 30     /**剪切点X坐标*/
 31     private static int x=16;
 32     /**剪切点Y坐标*/
 33     private static int y=22;
 34     /**剪切点宽度*/
 35     private static int width=784;
 36     /**剪切点高度*/
 37     private static int height=560;
 38 
 39     /**
 40      *
 41      * @Description: 剪切网络图片
 42      * String
 43      */
 44     public static String cutFromUrl(String imageUrl) {
 45         String suffix=imageUrl.substring(imageUrl.lastIndexOf("."));
 46         String fileName="";
 47         String fileNameAndPath="";
 48         InputStream is = null;
 49         ImageInputStream iis = null;
 50         String result=null;
 51         try {
 52             /**读取图片*/
 53             Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
 54             ImageReader reader = it.next();
 55             /**获取图片流*/
 56             URL url = new URL(imageUrl);
 57             HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
 58             /**设置请求方式为"GET"*/
 59             httpConn.setRequestMethod("GET");
 60             /**超时响应时间为5秒*/
 61             httpConn.setConnectTimeout(5 * 1000);
 62             httpConn.connect();
 63             is = httpConn.getInputStream();
 64 
 65             iis = ImageIO.createImageInputStream(is);
 66             reader.setInput(iis, true);
 67 
 68             ImageReadParam param = reader.getDefaultReadParam();
 69             Rectangle rect = new Rectangle(x, y, width, height);
 70             param.setSourceRegion(rect);
 71             BufferedImage bi = reader.read(0, param);
 72 
 73             fileName=GlobalMethodUtil.createFileName(suffix);
 74             fileNameAndPath=GlobalMethodUtil.createDir("/home/tmp/resources/product/")+fileName;
 75             if(fileNameAndPath==null||fileNameAndPath.equals("")){
 76                 result="";
 77             }else{
 78                 result=BASE_IMAGE_URL+fileNameAndPath.substring(fileNameAndPath.indexOf("product/")+8);
 79             }
 80             ImageIO.write(bi, "jpg", new File(fileNameAndPath));
 81         } catch (Exception ex) {
 82             ex.printStackTrace();
 83         } finally {
 84             try {
 85                 if (is != null) {
 86                     is.close();
 87                 }
 88                 if (iis != null) {
 89                     iis.close();
 90                 }
 91             } catch (Exception ex) {
 92                 ex.printStackTrace();
 93             }
 94         }
 95         return result;
 96     }
 97 
 98     /**
 99      *
100      * @Description: 剪切本地图片
101      *  @param imagePath
102      * String
103      */
104     public static String cutLocalImage(String imagePath) {
105         String fileName="";
106         String fileNameAndPath="";
107         FileInputStream fis = null;
108         ImageInputStream iis = null;
109         try {
110             /**读取图片*/
111             Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
112             ImageReader reader = it.next();
113             /**获取图片流*/
114             fis = new FileInputStream(imagePath);
115             iis = ImageIO.createImageInputStream(fis);
116             reader.setInput(iis, true);
117 
118             ImageReadParam param = reader.getDefaultReadParam();
119             Rectangle rect = new Rectangle(x, y, width, height);
120             param.setSourceRegion(rect);
121             BufferedImage bi = reader.read(0, param);
122 
123             fileName=GlobalMethodUtil.createFileName("jpg");
124             fileNameAndPath=GlobalMethodUtil.createDir("/home/tmp/qicheInfo/resources/product/")+fileName;
125             ImageIO.write(bi, "jpg", new File(DESTIMAGEPATH + new Date().getTime() + "." + "jpg"));
126         } catch (Exception ex) {
127             ex.printStackTrace();
128         } finally {
129             try {
130                 if (fis != null) {
131                     fis.close();
132                 }
133                 if (iis != null) {
134                     iis.close();
135                 }
136             } catch (Exception ex) {
137                 ex.printStackTrace();
138             }
139         }
140         return BASE_IMAGE_URL+fileNameAndPath.substring(fileNameAndPath.indexOf("product/")+8);
141     }
142 
143     private static class GlobalMethodUtil {
144 
145         /**
146          * 返回文件名(file)
147          * @Description:
148          * @return
149          */
150         public static String createFileName(String suffix) {
151             /**结合目录和文件名 生成唯一标识符*/
152             Calendar c = Calendar.getInstance();
153             /**利用小时分钟毫秒和源文件的文件名生成新文件名+文件后缀*/
154             String name = c.get(Calendar.HOUR) + "" + c.get(Calendar.MINUTE) + "" + c.get(Calendar.SECOND)
155                     + c.get(Calendar.MILLISECOND) + randStr()
156                     + suffix;
157             return name;
158         }
159 
160         /**
161          * 利用26个字母生成随机字母组合
162          * @Description:
163          * @return
164          */
165         public static String randStr() {
166             String[] rands = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "k", "o", "p", "q",
167                     "r", "s", "t", "u", "v", "w", "x", "y", "z"};
168             String randstr = "";
169             /**生成8个随机字母组合*/
170             for (int i = 0; i < 8; i++) {
171                 randstr += rands[new Random().nextInt(26)];
172             }
173             return randstr;
174         }
175 
176         /**
177          * 创建文件目录
178          * @Description:
179          * @return 文件目录路径
180          */
181         public static String createDir(String path) {
182             Calendar c = Calendar.getInstance();
183             String dir = path;
184             dir += c.get(Calendar.YEAR) + "" + ((c.get(Calendar.MONTH) + 1)<10?"0"+(c.get(Calendar.MONTH) + 1):(c.get(Calendar.MONTH) + 1)) + "" + (c.get(Calendar.DATE)<10?"0"+c.get(Calendar.DATE):c.get(Calendar.DATE)) + "/";
185             File tempDir = new File(dir);
186             /**判断文件路径是否存在*/
187             if (!tempDir.exists()) {
188                 /**不存在就创建文件目录*/
189                 tempDir.mkdirs();
190             }
191             return dir;
192         }
193 
194         /**
195          *
196          * @Description: 获取分页的总页数
197          *  @param count 数据总量
198          *  @param size 每页分页数量
199          *  @return
200          * int
201          */
202         public static int getPageSize(int count,int size){
203             return count%size!=0?(count/size+1):(count/size);
204         }
205 
206     }
207 }