将url路径图片保存为base64 和 把base64图片保存在本地

男娘i 2022-09-16 11:09 311阅读 0赞

需求:

  1. 将url路径图片保存为base64

  2. 把base64图片保存在本地

案例:

图片url路径:https://img-blog.csdnimg.cn/20181029235258454.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BvcnJ5Q24=,size_16,color_FFFFFF,t_70

想要把图片转成 base64,存起来。

url转成Base64的工具类代码

imageBase64(String imgUrl) 方法,传入一个url图片路径,然后获取到base64字符串。

generateImage(String imgStr, String imgFilePath)方法,传入base64字符串,传入一个保存图片的路径(就是要把图片保存在哪里)

  1. package com.angus.tasks.utils;
  2. import java.io.*;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.net.URLEncoder;
  6. /**
  7. * @author angus
  8. * @date 2021/10/18 14:36
  9. * @description
  10. */
  11. public class ImageUtil {
  12. /**
  13. * 通过图片的url获取图片的base64字符串
  14. * @param imgUrl 图片url
  15. * @return 返回图片base64的字符串
  16. */
  17. public static String imageBase64(String imgUrl) {
  18. URL url = null;
  19. InputStream is = null;
  20. ByteArrayOutputStream outStream = null;
  21. HttpURLConnection httpUrl = null;
  22. try{
  23. //解决中午路径失效问题
  24. url = new URL(URLEncoder.encode(imgUrl, "utf-8").replace("%3A", ":").replace("%2F", "/"));
  25. //url = new URL(imgUrl);
  26. httpUrl = (HttpURLConnection) url.openConnection();
  27. httpUrl.connect();
  28. httpUrl.getInputStream();
  29. is = httpUrl.getInputStream();
  30. outStream = new ByteArrayOutputStream();
  31. //创建一个Buffer字符串
  32. byte[] buffer = new byte[1024];
  33. //每次读取的字符串长度,如果为-1,代表全部读取完毕
  34. int len = 0;
  35. //使用一个输入流从buffer里把数据读取出来
  36. while( (len=is.read(buffer)) != -1 ){
  37. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
  38. outStream.write(buffer, 0, len);
  39. }
  40. // 对字节数组Base64编码,注意这个Base64Util的类,是自己提供的。下边有提供代码。
  41. return Base64Util.encode(outStream.toByteArray());
  42. }catch (Exception e) {
  43. e.printStackTrace();
  44. try {
  45. System.out.println(URLEncoder.encode(imgUrl, "utf-8").replace("%3A", ":").replace("%2F", "/"));
  46. } catch (UnsupportedEncodingException unsupportedEncodingException) {
  47. unsupportedEncodingException.printStackTrace();
  48. }
  49. }
  50. finally{
  51. if(is != null) {
  52. try {
  53. is.close();
  54. } catch (IOException e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. if(outStream != null) {
  59. try {
  60. outStream.close();
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. if(httpUrl != null) {
  66. httpUrl.disconnect();
  67. }
  68. }
  69. return imgUrl;
  70. }
  71. /**
  72. * 对字节数组字符串进行Base64解码并生成图片
  73. * @param imgStr 图片数据
  74. * @param imgFilePath 保存图片全路径地址
  75. * @return
  76. */
  77. public static boolean generateImage(String imgStr, String imgFilePath) {
  78. //
  79. if (imgStr == null) // 图像数据为空
  80. return false;
  81. try {
  82. // Base64解码
  83. byte[] b = Base64Util.decode(imgStr);
  84. for (int i = 0; i < b.length; ++i) {
  85. if (b[i] < 0) {// 调整异常数据
  86. b[i] += 256;
  87. }
  88. }
  89. // 生成jpg图片
  90. OutputStream out = new FileOutputStream(imgFilePath);
  91. out.write(b);
  92. out.flush();
  93. out.close();
  94. return true;
  95. } catch (Exception e) {
  96. return false;
  97. }
  98. }
  99. public static void main(String[] args) throws UnsupportedEncodingException {
  100. String url = "https://img-blog.csdnimg.cn/20181029235258454.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3BvcnJ5Q24=,size_16,color_FFFFFF,t_70";
  101. String s = imageBase64(url);
  102. System.out.println(s);
  103. //generateImage(s, "C:\\Users\\angus\\Desktop\\image.jpg");
  104. //System.out.println(s);
  105. }
  106. }

Base64工具类

注意要引入的是自己写的工具类。

  1. package com.angus.tasks.utils;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import javax.imageio.stream.FileImageInputStream;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10. /**
  11. * @author angus
  12. * @date 2021/10/18 15:05
  13. * @description
  14. */
  15. public class Base64Util {
  16. /**
  17. * 字符串转图片
  18. * @param base64Str
  19. * @return
  20. */
  21. public static byte[] decode(String base64Str){
  22. byte[] b = null;
  23. BASE64Decoder decoder = new BASE64Decoder();
  24. try {
  25. b = decoder.decodeBuffer(replaceEnter(base64Str));
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. return b;
  30. }
  31. /**
  32. * 图片转字符串
  33. * @param image
  34. * @return
  35. */
  36. public static String encode(byte[] image){
  37. BASE64Encoder decoder = new BASE64Encoder();
  38. return replaceEnter(decoder.encode(image));
  39. }
  40. public static String encode(String uri){
  41. BASE64Encoder encoder = new BASE64Encoder();
  42. return replaceEnter(encoder.encode(uri.getBytes()));
  43. }
  44. /**
  45. *
  46. * @path 图片路径
  47. * @return
  48. */
  49. public static byte[] imageTobyte(String path){
  50. byte[] data = null;
  51. FileImageInputStream input = null;
  52. try {
  53. input = new FileImageInputStream(new File(path));
  54. ByteArrayOutputStream output = new ByteArrayOutputStream();
  55. byte[] buf = new byte[1024];
  56. int numBytesRead = 0;
  57. while((numBytesRead = input.read(buf)) != -1){
  58. output.write(buf, 0, numBytesRead);
  59. }
  60. data = output.toByteArray();
  61. output.close();
  62. input.close();
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. return data;
  67. }
  68. public static String replaceEnter(String str){
  69. String reg ="[\n-\r]";
  70. Pattern p = Pattern.compile(reg);
  71. Matcher m = p.matcher(str);
  72. return m.replaceAll("");
  73. }
  74. }

发表评论

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

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

相关阅读