通过图片url 获取图片file对象

/**
 * 通过图片url 获取图片file对象
 * @param url
 * @param fileName 文件名称(一定要带后缀)
 * @param callback 回调函数
 * @returns {*}
 */
function getImageFileFromUrl(url, fileName,callback) {
    var blob = null;
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", url);
    xhr.setRequestHeader('Accept', 'image/jpeg');
    xhr.responseType = "blob";
    xhr.onload = () => {
	if (xhr.status == 200) {
      blob = xhr.response;
      let imgFile = new File([blob], fileName, {type: 'image/jpeg'});
      callback.call(this,imgFile);
    }};
    xhr.send();
}

demo:(用的图片url是百度上随便搜的)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>

<body>
<img/>
</body>

<script>
function getImageFileFromUrl(url, imageName,callback) {
  // imageName一定要带上后缀
    var blob = null;
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", url);
    xhr.setRequestHeader('Accept', 'image/jpeg');
    xhr.responseType = "blob";
    xhr.onload = () => {
	if (xhr.status == 200) {
      blob = xhr.response;
      let imgFile = new File([blob], imageName, {type: 'image/jpeg'});
	  console.log(imgFile)
      callback.call(this,imgFile);
    }};
    xhr.send();
}



  $(function () {
	getImageFileFromUrl('https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4085579248,162891217&fm=15&gp=0.jpg','testFile.jpg',function(file){
		console.log(file)
		var r = new FileReader()
        r.readAsDataURL(file)
        r.onload = function (e) {
          var base64 = e.target.result;
          $("img").attr('src', base64);         
        }

	});

  })
</script>

</html>

### 将Java中的图片URL地址转换为File对象 为了实现这一目标,可以采用多种方法来处理网络资源并将其存储为本地文件。下面介绍一种常见的方式,即通过`java.net.URL`类获取远程图像数据,并利用Apache Commons IO库简化操作过程。 #### 方法一:使用`java.net.URL`与`Files.copy` 此方式适用于较新版本的JDK(8及以上),它允许直接读取来自互联网的数据流并将这些字节写入指定位置创建新的文件实例[^1]。 ```java import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; public class ImageDownloader { public static void main(String[] args) throws IOException { URL imageUrl = new URL("http://example.com/path/to/image.jpg"); Path targetPath = Paths.get("./downloaded_image.jpg"); Files.copy(imageUrl.openStream(), targetPath); File downloadedImage = new File(targetPath.toString()); System.out.println("Download completed. Saved as " + downloadedImage.getAbsolutePath()); } } ``` 这种方法简单明了,适合大多数场景下的需求。然而,在某些情况下可能需要更灵活的操作选项,比如自定义HTTP请求头或处理重定向等问题,则推荐考虑其他高级解决方案。 #### 方法二:借助第三方工具包——Apache HttpClient 和 Apache Commons IO 当面对复杂的Web服务交互时,上述基础API可能会显得力不从心。此时引入专业的HTTP客户端如HttpClient以及用于便捷IO操作的Commons IO会更加得心应手[^2]。 ```java import org.apache.commons.io.FileUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.File; public class AdvancedImageDownloader { private final CloseableHttpClient httpClient = HttpClients.createDefault(); public File downloadImageFromUrl(String url, String outputFilePath) throws Exception { HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) throw new RuntimeException("Failed to fetch image: HTTP error code : " + statusCode); File outputFile = new File(outputFilePath); FileUtils.copyInputStreamToFile(response.getEntity().getContent(), outputFile); return outputFile; } // Remember to close the client after use. // httpClient.close(); } ``` 这段代码展示了如何结合两个强大的开源项目完成更为复杂的功能开发。值得注意的是,在实际应用中应当妥善管理连接池、设置合理的超时机制等细节以确保程序稳定运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值