java中图片Url,下载成压缩包放入指定文件夹
时间: 2024-04-27 14:21:12 浏览: 156
您可以使用Java的IO流来下载图片并保存到指定的文件夹中。以下是一个简单的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String savePath) throws IOException {
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(savePath));
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
public static void main(String[] args) throws IOException {
String imageUrl = "http://example.com/image.jpg";
String savePath = "/path/to/save/image.jpg";
downloadImage(imageUrl, savePath);
}
}
```
您可以将上述代码中的`imageUrl`替换为您要下载的图片的URL,将`savePath`替换为您要保存图片的文件路径。如果您需要将多个图片压缩成一个压缩包,可以使用Java的ZipOutputStream类来实现。以下是示例代码:
```java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String savePath) throws IOException {
URL url = new URL(imageUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(savePath));
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
public static void compressImagesToZip(String[] imageUrls, String zipFilePath) throws IOException {
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath)));
byte[] buf = new byte[1024];
for (int i = 0; i < imageUrls.length; i++) {
String imageUrl = imageUrls[i];
String fileName = "image" + i + ".jpg";
ZipEntry entry = new ZipEntry(fileName);
out.putNextEntry(entry);
BufferedInputStream in = new BufferedInputStream(new URL(imageUrl).openStream());
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.closeEntry();
}
out.close();
}
public static void main(String[] args) throws IOException {
String[] imageUrls = {"http://example.com/image1.jpg", "http://example.com/image2.jpg"};
String zipFilePath = "/path/to/save/images.zip";
compressImagesToZip(imageUrls, zipFilePath);
}
}
```
您可以将上述代码中的`imageUrls`替换为您要下载并压缩的图片的URL数组,将`zipFilePath`替换为您要保存压缩包的文件路径。
阅读全文