当前位置:   article > 正文

base64 显示图片和pdf_image展示base64 pdf

image展示base64 pdf

base64 显示图片和pdf,通过base64 编码在页面上显示图片和pdf,实现如下

 

1、图片

图片

java 代码,将图片转成 base64 字符串

  1. package com.tmp;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.util.Base64;
  7. public class Demo1 {
  8. public static void main(String[] args) throws IOException {
  9. File file = new File("C:\\Users\\Administrator\\Desktop\\img\\xiyang.jpg");
  10. FileInputStream inputStream = new FileInputStream(file);
  11. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  12. byte[] bytes = new byte[1024];
  13. int len;
  14. while ((len = inputStream.read(bytes)) != -1) {
  15. baos.write(bytes, 0, len);
  16. }
  17. byte[] res = Base64.getEncoder().encode(baos.toByteArray());
  18. String str = new String(res);
  19. System.out.println(str);
  20. }
  21. }

base64 字符串

html 代码

在 img标签中显示 base64编码图片时,src后的 base64字符串添加前缀 data:image/png;base64,

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <img src="https://img-blog.csdnimg.cn/2022010700215296007.png" />
  9. </body>
  10. </html>

效果如下

2、pdf

 

pdf 内容

java代码

  1. package com.tmp;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.util.Base64;
  7. public class Demo1 {
  8. public static void main(String[] args) throws IOException {
  9. File file = new File("C:\\Users\\Administrator\\Desktop\\article\\纳兰词一首.pdf");
  10. FileInputStream inputStream = new FileInputStream(file);
  11. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  12. byte[] bytes = new byte[1024];
  13. int len;
  14. while ((len = inputStream.read(bytes)) != -1) {
  15. baos.write(bytes, 0, len);
  16. }
  17. byte[] res = Base64.getEncoder().encode(baos.toByteArray());
  18. String str = new String(res);
  19. System.out.println(str);
  20. }
  21. }

base64 字符串

html 代码

在 iframe中显示 base64编码pdf 时,src后的 base64字符串添加前缀 data:application/pdf;base64,

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/256264
推荐阅读
相关标签
  

闽ICP备14008679号