Java 壓縮圖片并打包成ZIP文件的示例
JAVA 獲取網(wǎng)絡(luò)圖片或本地圖片壓縮后打成ZIP,但是獲取網(wǎng)絡(luò)流存在問(wèn)題:每次獲取圖片流的大小不一樣(圖片不完整),以致無(wú)法構(gòu)建圖片進(jìn)行壓縮?
/*
釋以下代碼:即可獲取完整圖片流網(wǎng)絡(luò)不穩(wěn)定情況且網(wǎng)絡(luò)流是順序讀取,所以獲得前部份流,不需要關(guān)閉連接,只需要將用完的流關(guān)閉即可
*/
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;
/**
* 獲取網(wǎng)絡(luò)圖片
*
* @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圖片本地存儲(chǔ)大小
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是否可以構(gòu)建圖片
try {
input = getInputStream("http://192.168.1.200/t.jpg");
ImageInputStream iis = ImageIO.createImageInputStream(input);
if(iis != null) {
Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
if(!it.hasNext()){
System.out.println("流不完整或不是圖片!");
} else {
System.out.println(it.next().getFormatName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
圖片壓縮采用thumbnailator,可以按大小、按比例、按質(zhì)量壓縮并增加水印,API簡(jiǎn)單
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;
/**
* 圖片壓縮:按大小、按比例壓縮、按質(zhì)量
* 增加水印
* @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 目標(biāo)寬席
* @param height 目標(biāo)高度
* @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;
}
/**
* 按指定比例進(jìn)行縮小和放大: 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;
}
/**
* 按指定比例進(jìn)行縮小和放大: 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;
}
/**
* 按質(zhì)量壓縮:圖片尺寸不變,壓縮圖片文件大小
*
* @param file 原圖
* @param quality
* =1為最高質(zhì)量
* @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;
}
/**
* 按質(zhì)量壓縮:圖片尺寸不變,壓縮圖片文件大小
*
* @param input 原圖
* @param quality
* =1為最高質(zhì)量
* @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;
}
/**
* 圖片格式轉(zhuǎn)換
*
* @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以下,不可以設(shè)置編碼,以致中文亂碼問(wèn)題,未采用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,支持并發(fā)多線程;
* java.util.ZipOutputStream中文亂碼
* 方法一、JDK1.7可以設(shè)置編碼
* 方法二、換成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;
}
/**
* 訪問(wèn)本地路徑下的所有文件
*
* @param path
* @return
*/
public static List<File> loadFiles(String path) {
List<File> 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;
}
/**
* 讀取本地系統(tǒng)路徑下的所有圖片打成ZIP
*
* @param path
* @param output
* @param compress
*/
public static void compressZip(String path, OutputStream output,
String encode, boolean compress) {
List<File> 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();
}
}
}
/**
* 讀取網(wǎng)絡(luò)圖片打成打成ZIP
* @param urls
* key = 圖片名, value = 圖片URL
* @param output
* @param encode 編碼
* @param compress 是否壓縮
*/
public static void compressZip(Map<String, String> urls,
OutputStream output, String encode, boolean compress) {
ZipOutputStream zipStream = null;
try {
zipStream = getZipStreamEncode(output, encode);
Map<String, String> synUrls = Collections.synchronizedMap(urls);
Set<Entry<String, String>> set = synUrls.entrySet();
Iterator<Entry<String, String>> it = set.iterator();
while (it.hasNext()) {
Entry<String, String> 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();
}
}
}
/**
* 壓縮單個(gè)文件為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();
}
}
}
/**
* 壓縮單個(gè)文件為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();
}
}
}
/**
* 網(wǎng)絡(luò)圖片
*
* @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("獲取壓縮的數(shù)據(jù)項(xiàng)失敗! 數(shù)據(jù)項(xiàng)名為:" + zipEntryName);
// 壓縮條目不是具體獨(dú)立的文件,而是壓縮包文件列表中的列表項(xiàng),稱為條目,就像索引一樣
ZipEntry zipEntry = new ZipEntry(zipEntryName);
// 定位到該壓縮條目位置,開(kāi)始寫(xiě)入文件到壓縮包中
zipStream.putNextEntry(zipEntry);
if (compress) {
bytes = CompressPictureTools.compressOfQuality(input, 0);
zipStream.write(bytes, 0, bytes.length);
} else {
bytes = new byte[1024 * 5];// 讀寫(xiě)緩沖區(qū)
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 壓縮圖片并打成ZIP文件的示例的詳細(xì)內(nèi)容,更多關(guān)于Java 壓縮圖片打包成zip的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java面試為何阿里強(qiáng)制要求不在foreach里執(zhí)行刪除操作
那天,小二去阿里面試,面試官老王一上來(lái)就甩給了他一道面試題:為什么阿里的 Java 開(kāi)發(fā)手冊(cè)里會(huì)強(qiáng)制不要在 foreach 里進(jìn)行元素的刪除操作2021-11-11
java實(shí)現(xiàn)字符串和數(shù)字轉(zhuǎn)換工具
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)字符串和數(shù)字轉(zhuǎn)換工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
Java高級(jí)之HashMap中的entrySet()方法使用
這篇文章主要介紹了Java高級(jí)之HashMap中的entrySet()方法使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
在Java的Hibernate框架中使用SQL語(yǔ)句的簡(jiǎn)單介紹
這篇文章主要介紹了在Java的Hibernate框架中使用SQL語(yǔ)句的方法,Hibernate是Java的SSH三大web開(kāi)發(fā)框架之一,需要的朋友可以參考下2016-01-01
為spring get請(qǐng)求添加自定義的參數(shù)處理操作(如下劃線轉(zhuǎn)駝峰)
這篇文章主要介紹了為spring get請(qǐng)求添加自定義的參數(shù)處理操作(如下劃線轉(zhuǎn)駝峰),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
java批量下載將多個(gè)文件(minio中存儲(chǔ))壓縮成一個(gè)zip包代碼示例
在Java應(yīng)用程序中有時(shí)我們需要從多個(gè)URL地址下載文件,并將這些文件打包成一個(gè)Zip文件進(jìn)行批量處理或傳輸,這篇文章主要給大家介紹了關(guān)于java批量下載將多個(gè)文件(minio中存儲(chǔ))壓縮成一個(gè)zip包的相關(guān)資料,需要的朋友可以參考下2023-11-11
SpringCloud實(shí)戰(zhàn)小貼士之Zuul的路徑匹配
這篇文章主要介紹了SpringCloud實(shí)戰(zhàn)小貼士之Zuul的路徑匹配,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10
Spring Boot實(shí)現(xiàn)數(shù)據(jù)訪問(wèn)計(jì)數(shù)器方案詳解
在Spring Boot項(xiàng)目中,有時(shí)需要數(shù)據(jù)訪問(wèn)計(jì)數(shù)器,怎么實(shí)現(xiàn)數(shù)據(jù)訪問(wèn)計(jì)數(shù)器呢?下面小編給大家?guī)?lái)了Spring Boot數(shù)據(jù)訪問(wèn)計(jì)數(shù)器的實(shí)現(xiàn)方案,需要的朋友參考下吧2021-08-08

