微信小程序----相對路徑圖片不顯示

出現場景

在本地調試的時候本地圖片顯示,但是手機瀏覽的時候本地圖片不顯示。

出現圖片不顯示的原因

小程序只支持網絡路徑和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='width:{{bannerInfo.width}}px;height:{{bannerInfo.height}}px' src="{{item.picUrl}}"></image>
              </block>
              <block wx:else>
                <image class="rui-full" style='width:{{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;width: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;width: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項目地址

微信小程序實例列表

前端筆記列表

遊戲列表

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章