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>

但對於微信小程序卻不行,原因是在返回的字符串中,包含了換行符‘\n’,H5可以自動解析並去除,微信小程序卻沒有這么智能。

2.解決方案

在微信小程序中需要在獲取到數據后把換行符替換。

WXML代碼:

<view>
    <image src="{{imgUrl}}" style="width: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(/[\r\n]/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的擴展組件:圖片上傳的組件,使用的是字節流的方式獲取圖片並顯示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM