【HarmonyOS】笔记八-图片处理

概念

开发者经常需要在应用中显示一些图片,例如:按钮中的icon、网络图片、本地图片等。在应用中显示图片需要使用Image组件实现,Image支持多种图片格式,包括png、jpg、bmp、svg和gif,该接口通过图片数据源获取图片,支持本地图片和网络图片的渲染展示。其中,src是图片的数据源,加载方式请参考加载图片资源

本地资源

创建文件夹,将本地图片放入ets文件夹下的任意位置。

Image组件引入本地图片路径,即可显示图片(根目录为ets文件夹)。

@Entry
@Component
struct Eight_1{
  build(){
    Column(){
      //图片存储在ets文件夹下的子文件夹中
      Image("images/image1.jpg").width("100%")
    }.width("100%")
  }
}

网络资源

引入网络图片需申请权限ohos.permission.INTERNET,具体申请方式请参考权限申请声明。此时,Image组件的src参数为网络图片的链接。

@Entry
@Component
struct Eight_2{
  build(){
    Column(){
      //加载网络图片,前提是需要添加网络权限
      Image("https://copyright.bdstatic.com/vcg/creative/cc9c744cf9f7c864889c563cbdeddce6.jpg@h_1280").width("100%")
    }.width("100%")
  }
}

Resource资源

使用资源格式可以跨包/跨模块引入图片,resources文件夹下的图片都可以通过$r资源接口读取到并转换到Resource格式。还可以将图片放在rawfile文件夹下。

@Entry
@Component
struct Eight_3{
  build(){
    Column(){
      //图片存储在resources文件夹下的media或者profile子文件夹中
      Image($r("app.media.image2")).width("100%")
    }.width("100%")
  }
}

媒体库file://data/storage

支持file://路径前缀的字符串,用于访问通过媒体库提供的图片路径。

  1. 调用接口获取图库的照片url。
import picker from '@ohos.file.picker';

@Entry
@Component
struct Eight_4 {
  @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中调用上述函数,获取图库的所有图片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%')
  }
}

请求网络图片请求,解码编码PixelMap。

//请求网络图片请求,解码编码PixelMap
import http from '@ohos.net.http';
import ResponseCode from '@ohos.net.http';
import image from '@ohos.multimedia.image';
@Entry
@Component
struct Eight_5{
  //创建PixelMap状态变量
  @State image: PixelMap = undefined;

  httpRequest(){
    //填写网络图片地址
    http.createHttp().request("https://copyright.bdstatic.com/vcg/creative/cc9c744cf9f7c864889c563cbdeddce6.jpg@h_1280",
      (error, data) => {
        if (error){
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          //将网络地址成功返回的数据,编码转码成pixelMap的图片格式
          let code = data.responseCode;
          if (ResponseCode.ResponseCode.OK === code) {
            let res: any = data.result
            let imageSource = image.createImageSource(res);
            let options = {
              alphaType: 0,                     // 透明度
              editable: false,                  // 是否可编辑
              pixelFormat: 3,                   // 像素格式
              scaleMode: 1,                     // 缩略值
              size: { height: 100, width: 100}
            }  // 创建图片大小
            imageSource.createPixelMap(options).then((pixelMap) => {
              this.image = pixelMap
            })
          }
        }
      }
    )
  }
  build(){
    Column(){
      //显示图片
      Button("获取网络图片")
        .onClick(() => {
          this.httpRequest()
        }).margin(10)
      Image(this.image).width("100%")
    }.width("100%")
  }
}

Image组件可显示矢量图(svg格式的图片),支持的svg标签为:svg、rect、circle、ellipse、path、line、polyline、polygon和animate。

通过objectFit属性使图片缩放到高度和宽度确定的框内。

@Entry
@Component
struct Eight_7 {
  scroller: Scroller = new Scroller()

  build() {
    Scroll(this.scroller) {

      Column(){

          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
            .objectFit(ImageFit.Contain).margin(15) // 保持宽高比进行缩小或者放大,使得图片完全显示在显示边界内。
            .overlay('Contain', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
            .objectFit(ImageFit.Cover).margin(15)
            // 保持宽高比进行缩小或者放大,使得图片两边都大于或等于显示边界。
            .overlay('Cover', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
              // 自适应显示。
            .objectFit(ImageFit.Auto).margin(15)
            .overlay('Auto', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })


          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
            .objectFit(ImageFit.Fill).margin(15)
            // 不保持宽高比进行放大缩小,使得图片充满显示边界。
            .overlay('Fill', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
              // 保持宽高比显示,图片缩小或者保持不变。
            .objectFit(ImageFit.ScaleDown).margin(15)
            .overlay('ScaleDown', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
          Image($r('app.media.image2')).width(200).height(150)
            .border({ width: 1 })
              // 保持原有尺寸显示。
            .objectFit(ImageFit.None).margin(15)
            .overlay('None', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })

      }.width("100%")

    }
  }
}
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔触狂放

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值