Java 下载远端图片到本地

古城微笑少年丶 2022-05-15 01:10 341阅读 0赞

需求是这样的:

  1. {
  2. "gid":"question:9002511534732700001-subject:0-qtype:2",
  3. "qtypeId":"2",
  4. "qtypeName":"单选题",
  5. "qtypeAlias":"danxuan",
  6. "difficulty":1,
  7. "subjectId":"0",
  8. "subjectName":"",
  9. "intro":"",
  10. "prompt":"<p>以下三个选项不是小动物的是?</p>",
  11. "score":"0",
  12. "tip":"可能是一种文具。",
  13. "parse":"<p>选项AB都是动物,选项C是铅笔。</p>",
  14. "comment":"",
  15. "kplist":[
  16. {
  17. "id":28,
  18. "name":"词义",
  19. "school_id":0
  20. }
  21. ],
  22. "cognition":[
  23. ],
  24. "book":[
  25. ],
  26. "parent_id":"0",
  27. "options":{
  28. "A":"<img width="300px" src="http://static.dev.anoah.com/uploads/onlinedocument/fd/fa/c20cea6c/a7e617d4/bedf966e6aef/original.png"/>",
  29. "B":"<img width="300px" src="http://static.dev.anoah.com/uploads/onlinedocument/57/d0/75ffdd8e/cf7d4e87/1396663d1ee4/original.jpg"/>",
  30. "C":"<img width="300px" src="http://static.dev.anoah.com/uploads/onlinedocument/02/d4/a839b912/bc06fef9/8f0d40c362e7/original.jpg"/>"
  31. },
  32. "isPicRes":0,
  33. "answer":"C"
  34. }
  35. 返回的数据结构如上,我想下载这里面的三张图片到本地,作为资源本地化。

自己写的一个工具类:

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.InputStream;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. /**
  12. * 下载图片工具
  13. *
  14. * @author cm_wang
  15. *
  16. */
  17. public class DownloadImgUtils {
  18. // 获取img标签的正则
  19. private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
  20. // 获取src路径的正则
  21. private static final String IMGSRC_REG = "(http|https):\"?(.*?)(\"|>|\\s+)";
  22. /**
  23. * 获取img的url
  24. *
  25. * @param url
  26. * @return
  27. */
  28. public static List<String> getImageUrl(String url) {
  29. Matcher matcher = Pattern.compile(IMGURL_REG).matcher(url);
  30. List<String> listImgUrl = new ArrayList<String>();
  31. while (matcher.find()) {
  32. listImgUrl.add(matcher.group());
  33. }
  34. return listImgUrl;
  35. }
  36. /**
  37. * 获取img的src路径
  38. *
  39. * @param listImageUrl
  40. * @return
  41. */
  42. public static List<String> getImageSrc(List<String> listImageUrl) {
  43. List<String> listImgSrc = new ArrayList<String>();
  44. for (String image : listImageUrl) {
  45. Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
  46. while (matcher.find()) {
  47. listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
  48. }
  49. }
  50. return listImgSrc;
  51. }
  52. /**
  53. * 下载资源
  54. *
  55. * @param listImgSrc
  56. * @param savePath
  57. */
  58. public static void Download(List<String> listImgSrc, String savePath) {
  59. try {
  60. for (String url : listImgSrc) {
  61. if (url.indexOf("http") >= 0) {
  62. String imageName = url.substring(url.indexOf("/") + 46, url.length()).replace("\\", "");
  63. URL uri = new URL(url.replace("\\", ""));
  64. InputStream in = uri.openStream();
  65. File file = new File(savePath, imageName);
  66. if(!file.exists()){
  67. if(!file.getParentFile().exists()){
  68. file.getParentFile().mkdirs();
  69. }
  70. FileOutputStream fo = new FileOutputStream(file);
  71. byte[] buf = new byte[1024];
  72. int length = 0;
  73. logger.info("开始下载:" + url);
  74. while ((length = in.read(buf, 0, buf.length)) != -1) {
  75. fo.write(buf, 0, length);
  76. }
  77. in.close();
  78. fo.close();
  79. logger.info(savePath + imageName + "下载完成");
  80. }
  81. }
  82. }
  83. } catch (Exception e) {
  84. logger.info("下载失败");
  85. }
  86. }
  87. }
  88. 使用方法大概是这样子的:
  89. JSONObject data = JSONObject.parseObject(result);
  90. // 获取img
  91. List<String> imgList = DownloadImgUtils.getImageUrl(data.toString());
  92. // 判断json里有没有流媒体资源
  93. if(!CollectionUtils.isEmpty(imgList)) {
  94. // 获取img的src
  95. List<String> srcList = DownloadImgUtils.getImageSrc(imgList);
  96. String savePath = "D:/files/";
  97. // 开始下载
  98. DownloadImgUtils.Download(srcList, savePath);
  99. }
  • 思路大概就是:我首先去通过正则找到<img>这个标签,然后在找到src属性,根据src对应的url进行下载,可能写的比较粗糙,有些细节没有考虑的很全面,后面完善。
  • 还有就是有些时候不一定只是下载图片,还有一些别的流媒体资源,这个时候就不需要正则取匹配img,直接去匹配http或者https就可以了。

发表评论

表情:
评论列表 (有 0 条评论,341人围观)

还没有评论,来说两句吧...

相关阅读

    相关 git将本地分支推送

    场景 开发的时候经常遇到,一个新的定制项目加紧来,而该项目的功能和基线功能不同,不便于在基线的开发分支上修改,需要新建一个分支用于并行开发。那么怎么创建分支用来本地和远端