java通过url获取图片文件
【代码】java通过url获取图片文件。
·
1. 根据url下载Url中的图片
import java.net.URL;
import java.io.InputStream;
import java.io.FileOutputStream;
public class ImageDownloader {
public static void main(String[] args) throws Exception {
// URL of the image to download
String imageUrl = "https://example.com/image.jpg";
// Create URL object and open input stream to the image
URL url = new URL(imageUrl);
InputStream inputStream = url.openStream();
// Output stream to save the image to file
FileOutputStream outputStream = new FileOutputStream("image.jpg");
// Read bytes from the input stream and write to the output stream
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
// Close streams
inputStream.close();
outputStream.close();
System.out.println("Image downloaded successfully.");
}
}
2. 根据get请求url下载Url中的图片
import java.net.URL;
import java.io.InputStream;
import java.io.FileOutputStream;
public class ImageDownloader {
public static void main(String[] args) throws Exception {
// URL of the image to download
String imageUrl = "https://example.com/image.jpg";
// Create URL object and open input stream to the image
URL url = new URL(imageUrl);
InputStream inputStream = url.openStream();
// Output stream to save the image to file
FileOutputStream outputStream = new FileOutputStream("image.jpg");
// Read bytes from the input stream and write to the output stream
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
// Close streams
inputStream.close();
outputStream.close();
System.out.println("Image downloaded successfully.");
}
}
3. 考虑url中携带中文,需要做转义
imageUrl = URLEncoder.encode(imageUrl, "utf-8")
.replaceAll("%3A", ":")
.replaceAll("%2F", "/")
.replaceAll("%2C", ",")
.replaceAll("%7B", "{")
.replaceAll("%3F","?")
.replaceAll("%7D", "}")
.replaceAll("%26","&")
.replaceAll("%3D","=");
//new一个URL对象
URL url = new URL(imageUrl);
更多推荐
所有评论(0)