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的扩展组件:图片上传的组件,使用的是字节流的方式获取图片并显示。

原文地址:https://www.cnblogs.com/zys2019/p/14279075.html