zoukankan      html  css  js  c++  java
  • base64图片显示问题

    1.问题描述

    小程序项目需要后端接口提供base64流的图片,对于H5的语法,前面拼接后面的代码即可: data:image/png;base64, 

    先看后台代码:

    @RestController
    @RequestMapping("/file")
    public class FileController {
    
    
        /**
         * 图片转为base64流
         */
        @GetMapping("/imgToBase64")
        public JSONObject imgToBase64() {
            JSONObject jsonObject = new JSONObject();
            try {
                //读取文件
                InputStream in = new BufferedInputStream(new FileInputStream("C:\Users\zhongyushi\Downloads\3.jpg"));
                byte[] srcBytes = new byte[in.available()];
                in.read(srcBytes);
                //把字节流转为base64字符流
                String encode = new BASE64Encoder().encode(srcBytes);
                jsonObject.put("data", encode);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    
        /**
         * 图片转为字节流
         */
        @GetMapping("/imgToByte")
        public JSONObject imgToByte() {
            JSONObject jsonObject = new JSONObject();
            try {
                //读取文件
                InputStream in = new BufferedInputStream(new FileInputStream("C:\Users\zhongyushi\Downloads\3.jpg"));
                byte[] srcBytes = new byte[in.available()];
                in.read(srcBytes);
                jsonObject.put("data", srcBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    以vue的代码为例说明:

    <template>
        <img :src="imageUrl">
    </template>
    <script>
        export default {
            name: '',
            created() {
                this.getImage()
            },
            data() {
                return {
                    imageUrl: ''
                }
            },
            methods: {
                getImage() {
                    axios.get('http://localhost:8081/file/imgToBase64').then(res => {
                        this.imageUrl = 'data:image/png;base64,' + res.data.data
                    }, err => {
                        console.log(err)
                    })
                }
            },
        }
    </script>
    <style scoped>
    </style>

    但对于微信小程序却不行,原因是在返回的字符串中,包含了换行符‘ ’,H5可以自动解析并去除,微信小程序却没有这么智能。

    2.解决方案

    在微信小程序中需要在获取到数据后把换行符替换。

    WXML代码:

    <view>
        <image src="{{imgUrl}}" style="100px;height:44px;"></image>
    </view>

    JAVASCRIPT代码:

    Page({
        data: {
            imgUrl: ''
        },
        onLoad() {
            this.getImg()
        },
        getImg() {
            let that = this
            wx.request({
                method: 'GET',
                url: 'http://localhost:8081/file/imgToBase64',
                success(res) {
                    let data = res.data.data
                    data = data.replace(/[
    ]/g, "")
                    that.setData({
                        imgUrl: 'data:image/png;base64,' +data
                    })
                }
            })
        }
    })

    3.扩展说明

    仔细观察会发现,我是后台代码有两种方法,另外一种是直接返回字节流而不是base64流,那么这种方式就不会存在上述的问题,我以另一种组件说明。

    JSON代码:

    {
      "usingComponents": {
          "mp-uploader": "weui-miniprogram/uploader/uploader"
      }
    }

    WXML代码:

    <view>
        <mp-uploader files="{{files}}" max-count="5" title="图片上传" tips="图片上传提示"></mp-uploader>
    </view>

    JAVASCRIPT代码:

    Page({
        data: {
            files: [],
        },
        onLoad() {
            this.getImg()
        },
        getImg() {
            let that = this
            wx.request({
                method: 'GET',
                url: 'http://localhost:8081/file/imgToBase64',
                success(res) {
                    let arr = []
                    arr.push({
                        url: 'data:image/png;base64,' + res.data.data
                    })
                    that.setData({
                        files: arr
                    })
                }
            })
        }
    })

    上述使用的是weui的扩展组件:图片上传的组件,使用的是字节流的方式获取图片并显示。

  • 相关阅读:
    线上redis禁止使用keys等时间复杂度高的命令
    组合索引的使用效果的总结
    Netty 断线重连解决方案
    可作为GC Root的对象
    在同一个sqlSession执行一个相同的查询时,Mybatis有一级缓存,不会去查数据库,由此引发的一个bug
    HashMap 和 currentHashMap JDK8总结
    Java程序导致服务器CPU占用率过高的问题排除过程
    一条sql执行的很慢的原因有哪些
    主键索引和非主键索引的区别
    黑马程序员
  • 原文地址:https://www.cnblogs.com/zys2019/p/14279075.html
Copyright © 2011-2022 走看看