微信小程序 将网络图片设置到background-image
上能显示,相关代码如下:
<image class="imgBox" style="background-image:url('http://ymzp.0633hr.com/upload/app/2019-08-02/1564730097202-2019-08-02.png')" >
</image>
微信小程序 将本地拍照/相机选择的图片设置到background-image
上是不能显示的。
<image class="imgBox" style="background-image:url('http://tmp/wx1e4dd12766f1b015.o6zAJs15FvORcBqF5xfEIJgbuAKI.ZtvcPNdqMc41f2dc8918f6a22cbecb7102e0cd2c3f6e.png')" >
</image>
解决办法1:使用wx.getFileSystemManager
将本地拍照/相机选择的图片转成base64
格式,设置到background-image
上。
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(e) { // 选择图片成功
console.log("本次选择图片" + JSON.stringify(e.tempFilePaths));
var baseImg = "";
wx.getFileSystemManager().readFile({
filePath: e.tempFilePaths[0], // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: res => { // 转码成功的回调
baseImg = 'data:image/png;base64,' + res.data;
console.log('data:image/png;base64,' + res.data);
// 后续的逻辑处理
...
...
}
})
},
fail: function(error) {
console.error("调用本地相册文件时出错")
console.warn(error)
},
complete: function() {
}
})
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABGUAAAmEEAIAAABz15itAAABYWlDQ1BrQ0dDb2xvclNwYWNlRGlzcGxheVAzAAAokWNgYFJJLCjIYWFgYMjNKykKcndSiIiMUmB/yMAOhLwMYgwKicnFBY4BAT5AJQwwGhV8u8bACKIv64LMOiU1tUm1XsDXYqbw1YuvRJsw1aMArpTU4mQg/QeIU5MLikoYGBhTgGzl8pICELsDyBYpAjoKyJ4DYqdD2BtA7CQI+whYTUiQM5B9A8hWSM5IBJrB+API1klCEk9HYkPtBQFul8zigpzESoUAYwKuJQOUpFaUgGjn/ILKosz0jBIFR2AopSp45iXr6SgYGRiaMzCAwhyi+nMgOCwZxc4gxJrvMzDY7v////9uhJjXfgaG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q46m0TldzK+DOv9DA4ILg+xwDpKkhi9p4Kq3T1dwKuPMvNDC4IPg+xwBpasiiNp5K63Q1twJ+yPC/Kt0lC/EZIyUggID43BKePZJORiQmcWmiHPS2AblsxjQmg9hY327N0RROW6Q9zW3emIzWuNXk2698NN75d/0EyEG9KoO0gbexgVPo+nH9BGhBvcqCtIG3sYFT6Ppx/QRoQb3KgrSBt7GBU+j6cf0EaEG9yoK0gbexgVPo
解决办法2:弃用background-image
赋值的方式,改用image组件的src
属性,本地拍照/相机选择的图片都能显示。
<image class="imgBox" mode="aspectFill" src="http://tmp/wx1e4dd12766f1b015.o6zAJs15FvORcBqF5xfEIJgbuAKI.ZtvcPNdqMc41f2dc8918f6a22cbecb7102e0cd2c3f6e.png">
</image>