zoukankan      html  css  js  c++  java
  • 微信小程序----相对路径图片不显示

    出现场景

    在本地调试的时候本地图片显示,但是手机浏览的时候本地图片不显示。

    出现图片不显示的原因

    小程序只支持网络路径和base64的图片。图片转base64在线工具

    处理方法

    1. 将图片都放到服务器,然后直接采用网络路径。
      1.1 优点是能够放大量的图片。
      1.2 缺点是有时开发中有大量的小图片,或者修改小图标,对于开发者来说,更换会很麻烦。

    2. 将图片都转换成 base64 的图片保存,使用时直接引入。图片转base64在线工具
      2.1 优点是方便快捷,开发过程中容易更换。
      2.2 缺点是由于微信小程序规定了每个文件不能超过500MB,超过另行打包。所以如果图片过大,或者量过大,都不方便。

    优化处理

    将网络路径图片和 base64 的图片结合使用。图片转base64在线工具

    1. 开发大图片(轮播等)或图片量大(商品图片等)的场景时,采用网络路径。

      优点是产品发布后方便图片的上下架,不用再提交审核,使用静态图片的尴尬和麻烦。

    2. 开发logo、导航等小图片时,采用 base64 的图片。图片转base64在线工具

      优点是开发时方便开发者更换,引入方便;转换快捷,用图片转base64在线工具可直接转换;不用开发时总是往服务器上传图片。

    实践开发

    开发效果图

    首页的轮播和网吧列表都是采用的网络路径,订单页面的右箭头和更多商品图标都是采用的 base64 图片。

    实践开发效果图

    开发代码

    1. 首页轮播和店铺列表JS
    const app = getApp();
    const urlList = require('../../utils/config.js');
    Page({
      data: {
        supplierList: [],
        iconList: iconList,
        bannerInfo: null,
        indicatorDots: true,//是否显示面板指示点
        autoplay: true,//是否开启自动切换
        interval: 3000,//自动切换时间间隔
        duration: 500,//滑动动画时长
        bannerList: [],
        shopList: [],
        currentPage: 1,
        pageSize: 10,
        total: 1000,
        myList: []
      },
      onLoad(){
        // 获取分享信息
        this.getShare();
      },
      onShow(){
        // 获取轮播列表
        this.getBannerList();
    
        // 获取当前地址
        wx.getLocation({
          success: res => {
            if (res.errMsg == 'getLocation:ok') {
              this.getShopList(res);
            }
          },
          fail: res => {
            this.wetoast.toast({ title: '获取定位失败,请打开定位,重新进入!' });
          }
        })
      },
      // 获取店铺列表
      getShopList(obj){
        // 判断是否还有更多数据
        if (!app.loadMoreData(this)) { return }
        // 请求数据
        let account = wx.getStorageSync('accountInfo');
        let location = obj;
        wx.request({
          url: urlList.shopListUrl,
          data: {
            // accountID: account.accountID,
            // passWord: account.passWord,
            longitude: location.longitude,
            latitude: location.latitude,
            currentPage: this.data.currentPage,
            pageSize: this.data.pageSize,
            sType: '1',
            token: app.globalData.token
          },
          success: res => {
            if(res.data.state == 'true'){
              console.log(res)
              this.setData({
                shopList: this.data.shopList.concat(res.data.data.supplierList),
                currentPage: ++this.data.currentPage,
                total: res.data.data.total,
                __noMoreData__: app.loadSuccessData(this, res.data.data.supplierList)
              })
            }else{
              console.log('网吧列表:' + res.data.exception)
              this.wetoast.toast({ title: '网吧列表加载失败!' });
            }
          }
        })
      },
      // 获取轮播列表
      getBannerList(){
        wx.request({
          url: urlList.advertPicListUrl,
          data: { appID: '4'},
          success: res => {
            if (res.data.state == 'true') {
              // console.log(res.data.data.picList)
              this.setData({
                bannerList: res.data.data.picList
              })
            }else{
              console.log('轮播列表:' + res.data.exception)
              this.wetoast.toast({ title: '轮播列表加载失败!' });
            }
          }
        })
      },
      //滚动加载
      onReachBottom(){
        this.getShopList(app.globalData.location);
      }
    })
    
    1. 首页轮播和店铺列表WXML
    <scroll-view  scroll-y="true">
      <swiper class="rui-swiper" style='height:{{bannerInfo.height}}px' current="0" indicator-dots="{{indicatorDots}}" vertical="{{vertical}}"
              autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}"
              indicator-color="rgba(0,0,0,.5)" indicator-active-color="#fff">
          <block wx:for-items="{{bannerList}}" wx:key="banner">
                <swiper-item>
                  <block wx:if="{{item}}">
                    // 读取轮播图片的网络路径
                    <image class="rui-full" bindtap='bannerUrl' data-banner="{{item}}" style='{{bannerInfo.width}}px;height:{{bannerInfo.height}}px' src="{{item.picUrl}}"></image>
                  </block>
                  <block wx:else>
                    <image class="rui-full" style='{{bannerInfo.width}}px;height:{{bannerInfo.height}}px' src="../../images/default_pic.png"></image>
                  </block>
                </swiper-item>
          </block>
      </swiper>
    </scroll-view> 
    
    <!--网吧列表  -->
    <view wx:if="{{shopList.length > 0}}" class='rui-shop-sort'>附近网吧</view>
    <view wx:if="{{shopList.length > 0}}" wx:for="{{shopList}}" wx:key="shopList">
        <view class='rui-shop-list' bindtap='goToGoodsList' data-shopid="{{item.shopID}}">
          // 读取网吧列表的网吧图片的网络路径
          <image class='rui-shop-img' src='{{item.sPicS}}'></image>
          <view class='rui-shop-box'>
            <view class='rui-shop-name'>
              {{item.userName}}
              <text class='rui-icon' wx:if="{{item.ishot == 1 && index < 3}}" style="background:url({{iconList.hotUrl}}) no-repeat center center/15px 15px;height:15px;15px;"></text>
            </view>
            <view class='rui-shop-distance'>
              <text style='margin-right:10px;color:#ff8e32;' wx:if="{{item.labels.length > 0 && labelsIndex < 4}}" wx:for-index="labelsIndex" wx:for="{{item.labels}}" wx:key="labels" wx:for-item="labels">{{labels}}</text>
              <text class='rui-fr'>{{item.gpsDistance}}</text>
            </view>
            <view class='rui-shop-address'>地址:{{item.corpAddress}}</view>
            <view class='rui-shop-active' wx:if="{{item.activeDesc}}">
              <text>{{item.activeDesc}}</text>
              <text class='active'></text>
            </view>
          </view>
        </view>
    </view>
    2. 订单页的右箭头和更多商品JS
    const app = getApp();
    const urlList = require('../../utils/config.js');
    const iconList = require('../../utils/iconPath.js');
    Page({
      data: {
        currentPage: 1,
        pageSize: 10,
        total: 1000,
        orderList: [],
        __noMoreData__: {
          isMore: false,
          title: '正在加载更多数据了...'
        }
      },
      onPullDownRefresh(){
        this.setData({
          currentPage: 1,
          pageSize: 10,
          total: 1000,
          orderList: [],
          __noMoreData__: {
            isMore: true,
            title: '正在加载更多数据了...'
          }
        })
        setTimeout(() => { 
          this.getOrderList();
        },1000);
      },
      onLoad(){
        // 将 base64 的文件保存到当前pagedatathis.setData({ iconList: iconList });
      },
      onShow(){
        // 获取订单列表
        this.getOrderList();
      },
      // 获取订单列表
      getOrderList(){
        // 判断是否还有更多数据
        if (!app.loadMoreData(this)){return}
        // 请求数据
        wx.request({
          url: urlList.orderListUrl,
          data: { 
            currentPage: this.data.currentPage,
            pageSize: this.data.pageSize,
            token: app.getToken()
          },
          success: res => {
            // console.log(res)
            app.withData(res, this, res => { 
              if (res.data.state == 'true'){
                // console.log(res.data.data.orderList)
                this.setData({
                  currentPage: ++this.data.currentPage,
                  total: res.data.data.total,
                  orderList: this.data.orderList.concat(res.data.data.orderList)
                })
                wx.stopPullDownRefresh();
              }
            })
          }
        })
      },
      // 滚动到底部加载
      onReachBottom() {
        this.getOrderList();
      }
    })
    2. 订单页的右箭头和更多商品WXML
    <view class='rui-order-li' wx:for="{{orderList}}" wx:key="orderList">
      <view class='rui-order-head'>
        <view class='rui-order-shop-name' data-shop='{{item}}' bindtap='goToShop'>
          {{item.userName}}
          // 读取右箭头的base64的图片
          <text class='rui-icon' style='background:url({{iconList.moreUrl}}) no-repeat center center/8px 15px;height:15px;15px;'></text>
        </view>
        <view class='rui-order-state {{item.orderState == 0 ? "rui-colory" : item.orderState == 4 ? "rui-colorg" : "rui-colorp"}}'>{{item.orderStateText}}</view>
      </view>
      <view class='rui-order-goodslist' id='{{item.orderID}}' bindtap='getOrderId'>
        <view class='rui-fl'>
          <image wx:for="{{item.goodsList}}" wx:if="{{goodsnum < 5}}" wx:for-index="goodsnum" wx:key="goodsList" wx:for-item="goods" class='rui-order-goodsimg' src="{{goods.sPics}}"></image>
          // 读取更多商品的base64的图片
          <view class='rui-order-detail-btn' style='background:url({{iconList.moreGoodsUrl}}) no-repeat center center/25px 5px;'></view>
        </view>
        <view class='rui-order-price'>
          <view class='rui-colory'>{{item.goodsAmountAll}}</view>
          <view class='rui-colorp rui-fs12'>{{item.totalGoodsNum}}</view>
        </view>
      </view>
      <view class='rui-order-head'>
        {{item.orderTime}}
        <view wx:if="{{item.orderState == 0}}" class='order-btn' data-orderid="{{item}}" bindtap='goToPay'>立即支付</view>
        <view wx:if="{{item.orderState == 4}}" class='order-btn' data-orderid="{{item}}" bindtap='repeatBuy'>再次购买</view>
      </view>
    </view>

    base64 的保存文件编辑

    const iconPath = {
      starUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA4RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTMyIDc5LjE1OTI4NCwgMjAxNi8wNC8xOS0xMzoxMzo0MCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo4OWIzY2I4MC1jMGU1LTQxNGMtODg4My0yNjNjODQ1MTRjOWUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ODg1REFBQjg0Nzg2MTFFOEJBNzc5NDg4NzE1MUY0QUMiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6ODg1REFBQjc0Nzg2MTFFOEJBNzc5NDg4NzE1MUY0QUMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKFdpbmRvd3MpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6ZmUyYzhkYWYtOTUyZi0yYjRlLWFjODYtNzY3OGM2NzNmNDA1IiBzdFJlZjpkb2N1bWVudElEPSJhZG9iZTpkb2NpZDpwaG90b3Nob3A6ZmJjNjU3ZTktNDQ3Ny0xMWU4LWJjNzUtZjgyODA4NzM1M2M1Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+p+ef2gAAAMhJREFUeNpi/N9nxIADlEPp1UB8D12SEY/G/zA12CSZGHCD93jk8Go8S0ijEhCnAbEgA3EgFIiNmaCMmUB8F0q7YFEMMrwDiN8B8SqQRSxQv+yBakiD4ntILjgDsgHNC/eQQ1UQ5gwojez01VDD98CihgUtFGch8dOQbEhHD2UmHBGfBrWlE+qCDnRFLGj8NKii90i2uCD5uxObjcgmhyE5DcbuQHI+isYOaIB0QgMBBkA2VaD5G8WprlD/dWLx9yyoofDAAwgwAIUJMVmp6d19AAAAAElFTkSuQmCC'
    }
    module.exports = iconPath;

    base64 的保存文件引入

    const iconList = require('../../utils/iconPath.js');

    base64 的保存文件使用

    js

    // 将 base64 的文件保存到当前page的data中
    this.setData({ iconList: iconList });

    wxml

    // 读取更多商品的base64的图片
    <view class='rui-order-detail-btn' style='background:url({{iconList.moreGoodsUrl}}) no-repeat center center/25px 5px;'></view>

    总结

    解决问题的方法有很多,只要找到适合自己的最好。个人建议微信小程序的图片可以两种方式结合使用。

    其他

    我的博客,欢迎交流!

    我的CSDN博客,欢迎交流!

    微信小程序专栏

    前端笔记专栏

    微信小程序实现部分高德地图功能的DEMO下载

    微信小程序实现MUI的部分效果的DEMO下载

    微信小程序实现MUI的GIT项目地址

    微信小程序实例列表

    前端笔记列表

    游戏列表

  • 相关阅读:
    接口测试小结
    UI自动化例子
    SQL Server 索引结构及其使用(二)
    SQL Server 索引结构及其使用(一)
    SQL Server 索引结构及其使用(四)
    SQL Server 索引结构及其使用(三)
    SQL Server 索引和视图
    Nginx 代理配置
    Java常见框架和工具
    MYSQL 存储过程 范例
  • 原文地址:https://www.cnblogs.com/linewman/p/9918434.html
Copyright © 2011-2022 走看看