程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

图片转为base64格式

发布于2023-02-04 17:37     阅读(912)     评论(0)     点赞(24)     收藏(5)


目录:

  1. 图片为什么要转base64格式
  2. base64概念
  3. java实现图片与base64互转(编码与解码)
  4. 后端图片转base64格式返回给前端,前端如何展示

一.图片为什么要转base64格式

图片的 base64 编码就是可以将一副图片数据编码成一串字符串,使用该字符串代替图像地址

1. 提升性能: 网页上的每一个图片,都是需要消耗一个 http 请求下载而来的, 图片的下载始终都要向服务器发出请求,要是图片的下载不用向服务器发出请求,base64可以随着 HTML 的下载同时下载到本地.减少https请求。

2. 加密: 让用户一眼看不出图片内容 , 只能看到编码。

3. 方便引用: 在多个文件同时使用某些图片时, 可以把图片转为base64格式的文件, 把样式放在全局中, 比如common.css, 以后在用的时候就可以直接加类名, 二不需要多层找文件路径, 会提升效率

二.base64概念

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。维基百科:base64_百度百科

原理:

  1. 将字符转二进制字节
  2. 3个字节为一组转为4个字节
  3. 根据转换表将4个字节转换为相对应的字符
  4. 输出结果
  1. byte[] b1 = "天明".getBytes("UTF-8");
  2. for(int i=0; i<b1.length; i++) {
  3. System.out.print(b1[i]+","); // -27,-92,-87,-26,-104,-114
  4. }
  5. byte[] b2 = new byte[]{-27,-92,-87};
  6. String name = new String(b2, "UTF-8");
  7. System.out.println(name); // 天
  8. // 如: "https://game.gtimg.cn/images/lol/act/img/passive/Annie_Passive.png";
  9. // 第一步:将字符转为byte
  10. String imgUrl = "http";
  11. byte[] b3 = imgUrl.getBytes();
  12. for(int i=0; i<b3.length; i++) {
  13. System.out.print(b3[i]+","); // 104,116,116,112
  14. }
  15. // 第二步:将十进制字节码转为二进制
  16. // 104 01101000
  17. // 116 01110100
  18. // 116 01110100
  19. // 112 01110000
  20. // 第三步:3个字节为一组,变为4个字节(上面的112没有分在这一组中)
  21. // 00011010 00000111 00010001 00110100
  22. // 转为10进制分别为:26 7 17 52
  23. // 第四步:根据转换表(base64转换表,维基百科有)得出结果为:aHA0

问题:负数(二进制)在计算机中如何表示?(转)负数在计算机中如何表示?(转) - 走看看

一般用补码方式表示,举例说明:
-52,假设存储的数据是8位二进制数,即8位二进制补码
先将52转换成二进制数:00110100B
取反:11001011B
加1:11001100B
则-52D的8位二进制补码为11001100B

三.java实现图片转base64

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.util.Base64;
  11. import java.util.Base64.Decoder;
  12. import java.util.Base64.Encoder;
  13. public class ImgToBase64 {
  14. public static void main(String[] args) throws UnsupportedEncodingException {
  15. System.out.println(getImgFileToBase642("f://user/12.jpg"));
  16. System.out.println(getImgUrlToBase64("https://game.gtimg.cn/images/lol/act/img/rune/Electrocute.png"));
  17. System.out.println(getImgBase64ToImgFile(getImgUrlToBase64("https://game.gtimg.cn/images/lol/act/img/rune/Electrocute.png"),"f://user/base2.jpg"));
  18. }
  19. /**
  20. * 本地图片转base64
  21. */
  22. public static String getImgFileToBase642(String imgFile) {
  23. //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  24. byte[] buffer = null;
  25. //读取图片字节数组
  26. try(InputStream inputStream = new FileInputStream(imgFile);){
  27. int count = 0;
  28. while (count == 0) {
  29. count = inputStream.available();
  30. }
  31. buffer = new byte[count];
  32. inputStream.read(buffer);
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. // 对字节数组Base64编码
  37. Encoder encode = Base64.getEncoder();
  38. return encode.encodeToString(buffer);
  39. }
  40. /**
  41. * 网络图片转base64
  42. */
  43. public static String getImgUrlToBase64(String imgUrl) {
  44. byte[] buffer = null;
  45. InputStream inputStream = null;
  46. try (
  47. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
  48. // 创建URL
  49. URL url = new URL(imgUrl);
  50. // 创建链接
  51. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  52. conn.setRequestMethod("GET");
  53. conn.setConnectTimeout(5000);
  54. inputStream = conn.getInputStream();
  55. // 将内容读取内存中
  56. buffer = new byte[1024];
  57. int len = -1;
  58. while ((len = inputStream.read(buffer)) != -1) {
  59. outputStream.write(buffer, 0, len);
  60. }
  61. buffer = outputStream.toByteArray();
  62. } catch (IOException e) {
  63. e.printStackTrace();
  64. } finally {
  65. if (inputStream != null) {
  66. try {
  67. // 关闭inputStream流
  68. inputStream.close();
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. // 对字节数组Base64编码
  75. Encoder encode = Base64.getEncoder();
  76. return encode.encodeToString(buffer);
  77. }
  78. /**
  79. * 本地或网络图片转base64
  80. */
  81. public static String getImgStrToBase64(String imgStr) {
  82. InputStream inputStream = null;
  83. byte[] buffer = null;
  84. try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
  85. //判断网络链接图片文件/本地目录图片文件
  86. if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) {
  87. // 创建URL
  88. URL url = new URL(imgStr);
  89. // 创建链接
  90. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  91. conn.setRequestMethod("GET");
  92. conn.setConnectTimeout(5000);
  93. inputStream = conn.getInputStream();
  94. // 将内容读取内存中
  95. buffer = new byte[1024];
  96. int len = -1;
  97. while ((len = inputStream.read(buffer)) != -1) {
  98. outputStream.write(buffer, 0, len);
  99. }
  100. buffer = outputStream.toByteArray();
  101. } else {
  102. inputStream = new FileInputStream(imgStr);
  103. int count = 0;
  104. while (count == 0) {
  105. count = inputStream.available();
  106. }
  107. buffer = new byte[count];
  108. inputStream.read(buffer);
  109. }
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. } finally {
  113. if (inputStream != null) {
  114. try {
  115. // 关闭inputStream流
  116. inputStream.close();
  117. } catch (IOException e) {
  118. e.printStackTrace();
  119. }
  120. }
  121. }
  122. // 对字节数组Base64编码
  123. Encoder encode = Base64.getEncoder();
  124. return encode.encodeToString(buffer);
  125. }
  126. /**
  127. * base64转图片存储在本地
  128. * @param imgBase64 图片base64
  129. * @param imgPath 图片本地存储地址
  130. */
  131. public static boolean getImgBase64ToImgFile(String imgBase64, String imgPath) {
  132. boolean flag = true;
  133. Decoder decode = Base64.getDecoder();
  134. try (OutputStream outputStream = new FileOutputStream(imgPath);){
  135. // 解密处理数据
  136. byte[] bytes = decode.decode(imgBase64);
  137. for (int i = 0; i < bytes.length; ++i) {
  138. if (bytes[i] < 0) {
  139. bytes[i] += 256;
  140. }
  141. }
  142. outputStream.write(bytes);
  143. } catch (Exception e) {
  144. e.printStackTrace();
  145. flag = false;
  146. }
  147. return flag;
  148. }
  149. }

四.后端图片转base64格式返回给前端,前端如何展示

图片以base64形式在页面上展示出来

在这里要说到Data URI scheme,它可以直接将一些小的数据直接嵌入到网页中,不需要再引入。支持格式如下

data:, 文本数据
data:text/plain, 文本数据
data:text/html, HTML代码
data:text/html;base64, base64编码的HTML代码
data:text/css, CSS代码
data:text/css;base64, base64编码的CSS代码
data:text/javascript, Javascript代码
data:text/javascript;base64, base64编码的Javascript代码
data:image/gif;base64, base64编码的gif图片数据
data:image/png;base64, base64编码的png图片数据
data:image/jpeg;base64, base64编码的jpeg图片数据
data:image/x-icon;base64, base64编码的icon图片数据

 所以此时只要是将base64格式的图片赋值给图片的src 属性即可。

<img src= "data:image/png;base64,图片的base64" />

如果想展示为jpg格式,前面变为data:image/jpeg;base64, 即可。



所属网站分类: 技术文章 > 博客

作者:javabb

链接:http://www.javaheidong.com/blog/article/641160/7b6690ffc67a2d3d30ff/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

24 0
收藏该文
已收藏

评论内容:(最多支持255个字符)