java实现图片下载

// 设置相应类型,告诉浏览器输出的内容为图片
response.setContentType("image/jpeg");
// 设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
// 将内存中的图片通过流动形式输出到客户端
ImageIO.write(image, "JPEG", response.getOutputStream());
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java可以使用HttpURLConnection或者HttpClient来下载图片,以下是一个基本的实现示例: ```java import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class ImageDownloader { public static void main(String[] args) { List<String> urls = new ArrayList<>(); // 添加需要下载图片链接 urls.add("https://example.com/image1.jpg"); urls.add("https://example.com/image2.jpg"); // ... for (String url : urls) { downloadImage(url); } } private static void downloadImage(String imageUrl) { try { URL url = new URL(imageUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); // 从链接中解析出文件名 String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1); File file = new File(fileName); FileOutputStream fos = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); bis.close(); is.close(); System.out.println("Downloaded " + fileName); } else { System.out.println("Failed to download " + imageUrl); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例将会从`urls`列表中读取需要下载图片链接,然后逐个下载保存到本地文件。你可以根据自己的需求修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaodabaiaaa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值