JAVA压缩图片并打成ZIP

阅读更多
引用

  JAVA 获取网络图片或本地图片压缩后打成ZIP,但是获取网络流存在问题:每次获取图片流的大小不一样(图片不完整),以致无法构建图片进行压缩?


 /*
注释以下代码:即可获取完整图片流网络不稳定情况且网络流是顺序读取,所以获得前部份流,不需要关闭连接,只需要将用完的流关闭即可
 */
 finally{
     if(httpCon != null)
	    httpCon.disconnect();
 }

package com.sunshine.monitor.comm.util.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import sun.net.www.protocol.ftp.FtpURLConnection;

/**
 * 获取网络图片
 * 
 * @author OY
 */
public abstract class HttpHelpers {

	private static final String KEY = "file.encoding";

	private static final String ENCODING = "GBK";

	public static InputStream getInputStream(String url) throws Exception{
		URLConnection con = null;
		HttpURLConnection httpCon = null;
		FtpURLConnection ftpCon= null;
		try {
			System.setProperty(KEY, ENCODING);
			URL _url = new URL(url);
			con = _url.openConnection();
			con.setConnectTimeout(3000);
			con.setUseCaches(false);// 不缓存
			con.setDefaultUseCaches(false);
			if (con instanceof HttpURLConnection) {
				httpCon = (HttpURLConnection) con;
				httpCon.setInstanceFollowRedirects(true);
				//httpCon.setRequestProperty("Accept-Charset", "utf-8");
				if (httpCon.getResponseCode() >= 300) {
					System.out.println("URL:" + url
							+ ",HTTP Request is not success, Response code is "
							+ httpCon.getResponseCode());
				} else {
					return httpCon.getInputStream();
				}
			} else if(con instanceof FtpURLConnection){
				ftpCon = (FtpURLConnection)con;
				return ftpCon.getInputStream();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(httpCon != null)
				httpCon.disconnect();
		}
		return null;
	}
	
	public static void main(String[] args) {
		// 1图片本地存储大小
		OutputStream fout = null;
		InputStream input = null;
		try {
			fout = new FileOutputStream("F:" + File.separator + "1.jpg");
			input = getInputStream("http://192.168.1.200/t.jpg");
			byte[] buffer = new byte[1024];
			int count = 0 ;
			while((count=input.read(buffer)) != -1){
				fout.write(buffer, 0, count);
			}
			fout.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(input != null) input.close();
				if(fout != null) fout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		// 2是否可以构建图片
		try {
			input = getInputStream("http://192.168.1.200/t.jpg");
			ImageInputStream iis = ImageIO.createImageInputStream(input);
			if(iis != null) {
				Iterator it = ImageIO.getImageReaders(iis);
				if(!it.hasNext()){
					System.out.println("流不完整或不是图片!");
				} else {
					System.out.println(it.next().getFormatName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



引用

图片压缩采用thumbnailator,可以按大小、按比例、按质量压缩并增加水印,API简单

 package com.sunshine.monitor.comm.util.compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * 图片压缩:按大小、按比例压缩、按质量
 * 增加水印
 * @author OY
 * 
 */
public abstract class CompressPictureTools {

	private static float QUALITY = 0.6f;
	
	/**
	 * 按大小缩小
	 * 
	 * @param file
	 * @param width
	 * @param height
	 * @return
	 * @throws Exception
	 */
	public static byte[] compressOfSize(File file, int width, int height)
			throws Exception {
		byte[] bs = null;
		InputStream input = null;
		try {
			input = new FileInputStream(file);
			bs = compressOfSize(input, width, height);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bs;
	}

	/**
	 * 按大小缩小
	 * 
	 * @param input 原图
	 * @param width 目标宽席
	 * @param height 目标高度
	 * @return
	 * @throws Exception
	 */
	public static byte[] compressOfSize(InputStream input, int width, int height)
			throws Exception {
		ByteArrayOutputStream output = null;
		try {
			output = new ByteArrayOutputStream();
			Thumbnails.of(input).size(width, height).toOutputStream(output);
			return output.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 按指定比例进行缩小和放大: percent=1不变 percent>1放大 percent<1缩小
	 * 
	 * @param input 原图
	 * @param percent 压缩比例
	 * @return
	 * @throws Exception
	 */
	public static byte[] compressOfPercent(InputStream input, float percent)
			throws Exception {
		ByteArrayOutputStream output = null;
		try {
			output = new ByteArrayOutputStream();
			Thumbnails.of(input).scale(percent).toOutputStream(output);
			return output.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 按指定比例进行缩小和放大: percent=1不变 percent>1放大 percent<1缩小
	 * 
	 * @param file 原图
	 * @param percent 压缩比例
	 */
	public static byte[] compressOfPercent(File file, float percent)
			throws Exception {
		byte[] bs = null;
		InputStream input = null;
		try {
			input = new FileInputStream(file);
			bs = compressOfPercent(input, percent);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bs;
	}

	/**
	 * 按质量压缩:图片尺寸不变,压缩图片文件大小
	 * 
	 * @param file 原图
	 * @param quality
	 *            =1为最高质量
	 * @return
	 * @throws Exception
	 */
	public static byte[] compressOfQuality(File file, float quality)
			throws Exception {
		byte[] bs = null;
		InputStream input = null;
		try {
			input = new FileInputStream(file);
			bs = compressOfQuality(input, quality);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bs;
	}

	/**
	 * 按质量压缩:图片尺寸不变,压缩图片文件大小
	 * 
	 * @param input 原图
	 * @param quality
	 *            =1为最高质量
	 * @return
	 * @throws Exception
	 */
	public static byte[] compressOfQuality(InputStream input, float quality)
			throws Exception {
		ByteArrayOutputStream output = null;
		try {
			output = new ByteArrayOutputStream();
			if(quality == 0){
				Thumbnails.of(input).scale(1f).outputQuality(QUALITY)
				.toOutputStream(output);
			} else {
				Thumbnails.of(input).scale(1f).outputQuality(quality)
					.toOutputStream(output);
			}
			return output.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 图片右下角添加水印
	 * 
	 * @param fromPic
	 *            原图
	 * @param markPic
	 *            水印图
	 * @param transparent
	 *            透明度
	 * @return
	 * @throws Exception
	 */
	public static byte[] waterMark(byte[] fromPic, InputStream markPic,
			float transparent) throws Exception {
		InputStream finput = null;
		ByteArrayOutputStream output = null;
		try {
			finput = new ByteArrayInputStream(fromPic);
			output = new ByteArrayOutputStream();
			Thumbnails
					.of(finput)
					.scale(1f)
					.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(markPic),
							transparent).toOutputStream(output);
			return output.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
				if (finput != null)
					finput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 图片格式转换
	 * 
	 * @param fromPic
	 *            原图
	 * @param picFormat
	 *            格式 png,jpg...
	 * @return
	 * @throws Exception
	 */
	public static byte[] transferPicFormat(byte[] fromPic, String picFormat)
			throws Exception {
		ByteArrayInputStream finput = null;
		ByteArrayOutputStream output = null;
		try {
			finput = new ByteArrayInputStream(fromPic);
			output = new ByteArrayOutputStream();
			Thumbnails.of(finput).outputFormat(picFormat)
					.toOutputStream(output);
			return output.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
				if (finput != null)
					finput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}


引用

因JDK1.7以下,不可以设置编码,以致中文乱码问题,未采用java.util.ZipOutputStream,而是Apache ant下的ZipOutputStream

package com.sunshine.monitor.comm.util.compress;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.sunshine.monitor.comm.util.http.HttpHelpers;
/**
 * 图片压缩成ZIP,支持并发多线程;
 * java.util.ZipOutputStream中文乱码 
 * 方法一、JDK1.7可以设置编码 
 * 方法二、换成Apache ant
 * @author OY
 * 
 */
public class PicturePackZipTools {

private static String DEFAULT_COMPRESS_ENCODE = "GBK";
	
	private static ZipOutputStream getZipStreamEncode(OutputStream output,
			String encode) {
		ZipOutputStream zipStream = new ZipOutputStream(output);
		if (encode == null || "".equals(encode)) {
			zipStream.setEncoding(DEFAULT_COMPRESS_ENCODE);
		} else {
			zipStream.setEncoding(encode);
		}
		return zipStream;
	}

	/**
	 * 访问本地路径下的所有文件
	 * 
	 * @param path
	 * @return
	 */
	public static List loadFiles(String path) {
		List list = null;
		try {
			File fold = new File(path);
			if (fold.isDirectory()) {
				File[] files = fold.listFiles();
				list = Arrays.asList(files);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 读取本地系统路径下的所有图片打成ZIP
	 * 
	 * @param path
	 * @param output
	 * @param compress
	 */
	public static void compressZip(String path, OutputStream output,
			String encode, boolean compress) {
		List listfiles = null;
		ZipOutputStream zipStream = null;
		try {
			zipStream = getZipStreamEncode(output, encode);
			listfiles = loadFiles(path);
			for (File file : listfiles) {
				compressZip(file, zipStream, compress);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (zipStream != null) {
					zipStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 读取网络图片打成打成ZIP
	 * @param urls
	 *            key = 图片名, value = 图片URL
	 * @param output 
	 * @param encode 编码
	 * @param compress 是否压缩
	 */
	public static void compressZip(Map urls,
			OutputStream output, String encode, boolean compress) {
		ZipOutputStream zipStream = null;
		try {
			zipStream = getZipStreamEncode(output, encode);
			Map synUrls = Collections.synchronizedMap(urls);
			Set> set = synUrls.entrySet();
			Iterator> it = set.iterator();
			while (it.hasNext()) {
				Entry entry = it.next();
				compressZip(entry.getValue(), zipStream, entry.getKey(),
						compress);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (zipStream != null) {
					zipStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 压缩单个文件为ZIP
	 * @param file
	 * @param output
	 * @param encode
	 * @param compress
	 */
	public static void compressZip(File file, OutputStream output,
			String encode, boolean compress) throws Exception{
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
			compressZip(input,file.getName(),output,encode,compress);
		} catch (Exception e) {
			e.printStackTrace();
		}  finally {
			try {
				if (input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 压缩单个文件为ZIP
	 * @param input
	 * @param fileName
	 * @param output
	 * @param encode
	 * @param compress
	 */
	public static void compressZip(InputStream input, String fileName,
			OutputStream output, String encode, boolean compress) throws Exception {
		ZipOutputStream zipStream = null;
		try {
			zipStream = getZipStreamEncode(output, encode);
			zip(input, zipStream, fileName, compress);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (zipStream != null)
					zipStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 本地图片
	 */
	private static void compressZip(File file, ZipOutputStream zipStream,
			boolean compress) throws Exception{
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
			zip(input, zipStream, file.getName(), compress);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 网络图片
	 * 
	 * @param url
	 * @param zipStream
	 * @param compress
	 */
	private static void compressZip(String url, ZipOutputStream zipStream,
			String fileName, boolean compress) throws Exception{
		InputStream input = null;
		try {
			input = HttpHelpers.getInputStream(url);
			zip(input, zipStream, fileName, compress);
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(input != null)
					input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param input
	 * @param zipStream
	 * @param zipEntryName
	 * @param compress
	 */
	private static void zip(InputStream input, ZipOutputStream zipStream,
			String zipEntryName, boolean compress) throws Exception{
		byte[] bytes = null;
		BufferedInputStream bufferStream = null;
		try {
			if(input == null)
				throw new Exception("获取压缩的数据项失败! 数据项名为:" + zipEntryName);
			// 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
			ZipEntry zipEntry = new ZipEntry(zipEntryName);
			// 定位到该压缩条目位置,开始写入文件到压缩包中
			zipStream.putNextEntry(zipEntry);
			if (compress) {
				bytes = CompressPictureTools.compressOfQuality(input, 0);
				zipStream.write(bytes, 0, bytes.length);
			} else {
				bytes = new byte[1024 * 5];// 读写缓冲区
				bufferStream = new BufferedInputStream(input);// 输入缓冲流
				int read = 0;
				while ((read = bufferStream.read(bytes)) != -1) {
					zipStream.write(bytes, 0, read);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != bufferStream)
					bufferStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

你可能感兴趣的:(java)