package jtest;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* @author anquan
* @desc: 根据图片URL裁切并生成缩略图
* @date 2015-3-21 下午7:16:37
*/
public class CopyOfImgTest {
/**
* 根据图片URL裁切并生成缩略图
* @param imgUrl 上传的图片的URL
* @param destDir 存放目录
* @param width 图片宽
* @param height 图片高
* @throws IOException
*/
public void resizeImage(String imgUrl, String destDir, Integer width, Integer height) throws IOException {
HttpURLConnection httpUrl = null;
InputStream fis = null;
FileOutputStream fos = null;
URL url = null;
try {
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
fis = httpUrl.getInputStream();
BufferedImage bi = ImageIO.read(fis);
int src_w = bi.getWidth();
int src_h = bi.getHeight();
if (width == null || width <= 0 ) {
width = src_w;
}
if (height == null || height <= 0) {
height = src_h;
}
//(1)图片长大于宽,去掉长的左右两边
//(2)图片长小于宽,去掉宽上面的三分之一,去掉宽下面的三分之二
int top = 0;//左
int left = 0;//左
if(src_w > src_h){
left = (src_w - src_h)/2;
src_w = src_h;
}else{
top = (src_h - src_w)/3;
src_h = src_w;
}
// 裁切图片
ImageFilter cropFilter = new CropImageFilter(left, top, src_w, src_h);
Image cutImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(bi.getSource(), cropFilter));
Image image_s = cutImage.getScaledInstance(width, height,Image.SCALE_DEFAULT);//获取缩放后的图片大小
//图片缩小处理
BufferedImage tag_s = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g_s = tag_s.getGraphics();
g_s.drawImage(image_s, 0, 0, null); // 绘制缩小后的图
g_s.dispose();
// 输出为文件
fos = new FileOutputStream(destDir);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(tag_s);
} catch (Exception e) {
e.printStackTrace();
}finally{
fos.flush();
fis.close();
fos.close();
}
}
public static void main(String[] args) {
CopyOfImgTest dw = new CopyOfImgTest();
String destUrl1 = "http://localhost:8080/wedding/resources/upload/ushop/1//album//20150321230218658.jpg";
String destUrl2 = "http://localhost:8080/wedding/resources/upload/ushop/1//album//20150315002308968.jpg";
try {
dw.resizeImage(destUrl1, "f://b1.gif", 300, 300);
dw.resizeImage(destUrl2, "f://b2.gif", 300, 300);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}