图片压缩

 

/**
 * WriteImage.java Create on 2012-3-10
 * 
 * Copyright  HeNan New Creatsoft. All rights reserved.
 */
package com.xcy.image;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * Filename: 	WriteImage.java<br>
 * Description: 图片压缩
 * @author: 	ZhangLiangYong
 * @date 		2012-3-10下午12:14:03
 * @version: 	1.0.0
 */
public class WriteImage {
	/**
	 * 根据图片的源地址,生成压缩后的图片
	 * @param urlstr   图片的http的url地址
	 * @param savepath 生成图片的绝对路径
	 * @param width	       生成图片的宽度
	 * @param height   生成图片的高度	
	 * @param percent   压缩图片的百分比
	 * @return   图片名称
	 */
	public static String getImgFromUrl(String urlstr, String savepath,
			int width, int height, float percent) {
		
		int num = urlstr.indexOf('/', 8);
		int extnum = urlstr.lastIndexOf('.');
		String u = urlstr.substring(0, num);
		String imageName = urlstr.substring(urlstr.lastIndexOf("/")+1,
				urlstr.lastIndexOf(".")); //获取图片的源名称 (唯一)
		//String ext ="."+urlstr.substring(extnum+1,urlstr.length());
		String ext = ".png"; //生成png图片格式,在手机上以png图片展示	      
		try {
			long curTime = System.currentTimeMillis(); // 当前系统时间
			Random random = new Random(100000000); //随机数
			//String fileName = String.valueOf(curTime) +"_"+ random.nextInt(100000000) + ext;   //通过当前系统时间与随机数,生成图片的名字
			String fileName = imageName+ext;
			// 生成图片的绝对路径
			String realPath = savepath;
			File file = new File(realPath); 
			if (!file.exists()) {	//判断文件目录是否存在,如不存在,则进行创建
				file.mkdir();
			}
		    File fileimg = new File(realPath+fileName);
	        if(!fileimg.exists()){	//判断图片是否存在,不存在,则创建
				URL url = new URL(urlstr); //声明url对象	
				URLConnection connection = url.openConnection(); //打开连接
				connection.setDoOutput(true);
				connection.setRequestProperty("referer", u); //通过这个http头的伪装来反盗链
				BufferedImage src = ImageIO.read(connection.getInputStream()); //读取连接的流,赋值给BufferedImage对象
				// String img_midname=f+n.substring(0,n.indexOf("."))+ext+n.substring(n.indexOf(".")); 
				// String img_midname= fileName;
				int old_w = src.getWidth(null); //得到源图宽 
				int old_h = src.getHeight(null); //得到源图高
				int new_w = 0;
				int new_h = 0;
				double w2 = (old_w * 1.00) / (width * 1.00);
				double h2 = (old_h * 1.00) / (height * 1.00);
	
				//图片跟据长宽留白,成一个正方形图。 不对图片进行留白,如果需要留白,请去掉以下注释
				/*
				BufferedImage oldpic;
				if (old_w > old_h) {
					oldpic = new BufferedImage(old_w, old_w,
							BufferedImage.TYPE_INT_RGB);
				} else {
					if (old_w < old_h) {
						oldpic = new BufferedImage(old_h, old_h,
								BufferedImage.TYPE_INT_RGB);
					} else {
						oldpic = new BufferedImage(old_w, old_h,
								BufferedImage.TYPE_INT_RGB);
					}
				}
				Graphics2D g = oldpic.createGraphics();
				 g.setColor(Color.white);
				if (old_w > old_h) {
					g.fillRect(0, 0, old_w, old_w);
					g.drawImage(src, 0, (old_w - old_h) / 2, old_w, old_h,
							Color.white, null);
				} else {
					if (old_w < old_h) {
						g.fillRect(0, 0, old_h, old_h);
						g.drawImage(src, (old_h - old_w) / 2, 0, old_w, old_h,
								Color.white, null);
					} else {
						//g.fillRect(0,0,old_h,old_h); 
						g.drawImage(src.getScaledInstance(old_w, old_h,
								Image.SCALE_SMOOTH), 0, 0, null);
					}
				}
				g.dispose();
				src = oldpic;
				 */
				//图片调整为方形结束 
				if (old_w > width)
					new_w = (int) Math.round(old_w / w2);
				else
					new_w = old_w;
				if (old_h > height)
					new_h = (int) Math.round(old_h / h2);//计算新图长宽 
				else
					new_h = old_h;
				BufferedImage tag = new BufferedImage(new_w, new_h,
						BufferedImage.TYPE_INT_RGB);
				//tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图 
				tag.getGraphics().drawImage(
						src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0,
						0, null);
				FileOutputStream newimage = new FileOutputStream(realPath
						+ fileName); //输出到文件流 
				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
				JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
				/* 压缩质量 */
				jep.setQuality(percent, true);
				encoder.encode(tag, jep);
				//encoder.encode(tag); //近JPEG编码 
				newimage.close();
				System.out.println("生成图片耗时:"
						+ (System.currentTimeMillis() - curTime) + "毫秒");
			
	         }
			return fileName;
		} catch (Exception e) {
			System.out.print(e.getMessage().toString());
			return "";
		}
	}
	public static void main(String[] s){
		// System.out.println(getImgFromUrl("http://d.houdao.com/11884/09/02/09/179_1963859_05b3be327dff14c.jpg",""))	;
		//	System.out.println(getImgFromUrl("http://pic1a.nipic.com/2008-11-19/2008111912362920_2.jpg",""));
		//	System.out.println(getImgFromUrl("http://192.168.1.129:8000/xcinter/10041281581875225.jpg",""));
		System.out.println(getImgFromUrl("http://pic1a.nipic.com/2008-11-19/2008111912362920_2.jpg","d://html//",260,180,0.7f));
			
		}
}

你可能感兴趣的:(压缩)