鴻蒙HarmonyOS引用圖片的方法

前言

Image通過調(diào)用接口來創(chuàng)建,接口調(diào)用形式如下:

Image(src: string | Resource | media.PixelMap)

該接口通過圖片數(shù)據(jù)源獲取圖片,支持本地圖片和網(wǎng)絡(luò)圖片的渲染展示。其中,src是圖片的數(shù)據(jù)源。

加載圖片資源

Image支持加載存檔圖(重點(diǎn))、多媒體像素圖(了解即可)兩種類型。

存檔圖類型數(shù)據(jù)源

存檔圖類型的數(shù)據(jù)源可以分為本地資源、網(wǎng)絡(luò)資源、Resource資源、媒體庫資源和base64。

  • 本地資源

創(chuàng)建文件夾,將本地圖片放入ets文件夾下的任意位置。
Image組件引入本地圖片路徑,即可顯示圖片(根目錄為ets文件夾)。

Image('images/view.jpg')
.width(200)
  • 網(wǎng)絡(luò)資源

引入網(wǎng)絡(luò)圖片需申請權(quán)限ohos.permission.INTERNET,具體申請方式請參考權(quán)限申請聲明。此時,Image組件的src參數(shù)為網(wǎng)絡(luò)圖片的鏈接。

Image('https://www.example.com/example.JPG') // 實(shí)際使用時請?zhí)鎿Q為真實(shí)地址
  • Resource資源

使用資源格式可以跨包/跨模塊引入圖片,resources文件夾下的圖片都可以通過$r資源接口讀取到并轉(zhuǎn)換到Resource格式。

調(diào)用方式:

Image($r('app.media.icon'))

還可以將圖片放在rawfile文件夾下。


調(diào)用方式:

Image($rawfile('snap'))
  • 媒體庫file://data/storage
    支持file://路徑前綴的字符串,用于訪問通過媒體庫提供的圖片路徑。
    a. 調(diào)用接口獲取圖庫的照片url。
import picker from '@ohos.file.picker';

@Entry
@Component
struct Index {
  @State imgDatas: string[] = [];
  // 獲取照片url集
  getAllImg() {
    
    let result = new Array<string>();
    try {
      let PhotoSelectOptions = new picker.PhotoSelectOptions();
      PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
      PhotoSelectOptions.maxSelectNumber = 5;
      let photoPicker = new picker.PhotoViewPicker();
      photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult) => {
        this.imgDatas = PhotoSelectResult.photoUris;
        console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      }).catch((err) => {
        console.error(`PhotoViewPicker.select failed with. Code: ${err.code}, message: ${err.message}`);
      });
    } catch (err) {
      console.error(`PhotoViewPicker failed with. Code: ${err.code}, message: ${err.message}`);    }
  }

  // aboutToAppear中調(diào)用上述函數(shù),獲取圖庫的所有圖片url,存在imgDatas中
  async aboutToAppear() {
    this.getAllImg();
  }
  // 使用imgDatas的url加載圖片。
  build() {
    Column() {
      Grid() {
        ForEach(this.imgDatas, item => {
          GridItem() {
            Image(item)
              .width(200)
          }
        }, item => JSON.stringify(item))
      }
    }.width('100%').height('100%')
  }
}

b. 從媒體庫獲取的url格式通常如下。

Image('file://media/Photos/5')
.width(200)
  • base64
    路徑格式為data:image/[png|jpeg|bmp|webp];base64,[base64 data],其中[base64 data]Base64字符串?dāng)?shù)據(jù)。
    Base64格式字符串可用于存儲圖片的像素數(shù)據(jù),在網(wǎng)頁上使用較為廣泛。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容