java获取图片打成压缩包

编程

java打压缩包时很简单的,使用ZipOutputStream写出来的流就是压缩包的流了,需要获取压缩包的zip的byte[]字节流,就写到ByteArrayOutputStream上,需要写到硬盘上就写到FileOutputStream上

 @Test

public void imgToZip(){

//百度随便搜的图片

List<String> list = Arrays.asList("http://f.hiphotos.baidu.com/image/pic/item/b151f8198618367aa7f3cc7424738bd4b31ce525.jpg",

"http://a.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa4e6e4b2194510fb30e24088f.jpg",

"http://c.hiphotos.baidu.com/image/pic/item/023b5bb5c9ea15ced43db9a0bc003af33b87b24c.jpg");

//需要获取byte字节流就用ByteArrayOutputStream,指向内存的流可以不用关闭,指向存储卡/硬盘的流一定要关闭

//ByteArrayOutputStream out = new ByteArrayOutputStream();

try (FileOutputStream out = new FileOutputStream("D:/1.zip");

ZipOutputStream zipOutputStream = new ZipOutputStream(out)) {

zipOutputStream.setMethod(ZipOutputStream.DEFLATED);

for (int i = 0 ; i < list.size(); i++) {

try (InputStream inputStream = new URL(list.get(i)).openStream()) {

if (inputStream != null && inputStream.available() > 0) {

zipOutputStream.putNextEntry(new ZipEntry(i+".png"));

byte[] b = new byte[1024];

int l;

while ((l = inputStream.read(b)) != -1) {

zipOutputStream.write(b, 0, l);

}

zipOutputStream.closeEntry();

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

 

以上是 java获取图片打成压缩包 的全部内容, 来源链接: utcz.com/z/511041.html

回到顶部