鸿蒙中如何加载本地视频缩略图

鸿蒙中如何加载本地视频缩略图 鸿蒙中如何加载本地视频缩略图,最好给出示例代码

2 回复

伙伴您好,参考官方文档: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/avimagegenerator-V5#完整示例

可以参考如下demo

import { common } from '@kit.AbilityKit';

import { picker } from '@kit.CoreFileKit';

import fs from '@ohos.file.fs';

import { photoAccessHelper } from '@kit.MediaLibraryKit';

import { dataSharePredicates } from '@kit.ArkData';

import { image } from '@kit.ImageKit';

import { media } from '@kit.MediaKit';

@Entry
@Component
struct Index {
  @State imagePath: string = ''
  @State pixelMap:image.PixelMap | undefined = undefined
  private controller:VideoController | undefined
  private context = getContext(this) as common.UIAbilityContext;
  build() {
    Row() {
      Column() {
        Video({
          src:this.imagePath,
          controller: this.controller
        }).height(300).width('100%').margin({ bottom: 20 })
        Button("选择视频")
          .onClick(() => {
            this.selectPhoto()
          })
        Image(this.pixelMap).width(300).height(400)
      }.width('100%')
    }.height('100%')
  }
  selectPhoto() {
    const photoSelectOptions = new picker.PhotoSelectOptions();
    const photoViewPicker = new picker.PhotoViewPicker();
    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.VIDEO_TYPE; // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
    photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
      const fileUri = photoSelectResult.photoUris[0]
      //this.getFileInfo(fileUri)
      //this.uriGetAssets(fileUri)
      this.testFetchFrameByTime(fileUri)
    })
  }
  async getFileInfo(filePathString: string) {
    let resFile = fs.openSync(filePathString, fs.OpenMode.READ_ONLY)
    const dateStr = (new Date().getTime()).toString()
    // 临时文件目录
    let newPath = this.context.filesDir +'/' + dateStr + resFile.name;
    // 转化路径
    fs.copyFileSync(resFile.fd, newPath);
    // 新的路径
    let realUri = 'file://' + newPath;
    this.imagePath = realUri
    console.log(this.imagePath)
  }
  async uriGetAssets(videoUri:string) {
    try {
      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
      let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
      // 配置查询条件,使用PhotoViewPicker选择图片返回的uri进行查询
      predicates.equalTo('uri', videoUri);
      let fetchOption: photoAccessHelper.FetchOptions = {
        fetchColumns: [],
        predicates: predicates
      };
      let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
      // 得到uri对应的PhotoAsset对象,读取文件的部分信息
      const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
      console.info('asset displayName: ', asset.displayName);
      console.info('asset uri: ', asset.uri);
      console.info('asset photoType: ', asset.photoType);
      console.info('asset width: ', asset.get('width'));
      // 获取缩略图
      asset.getThumbnail((err, pixelMap) => {
        if (err == undefined) {
          this.pixelMap = pixelMap
          console.info('getThumbnail successful ' + JSON.stringify(pixelMap));
        } else {
          console.error('getThumbnail fail', err.code + err.message);
        }
      });
    } catch (error){
      console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
    }
  }
  async testFetchFrameByTime(fileUri:string) {
    // 创建AVImageGenerator对象
    try {
      let avImageGenerator: media.AVImageGenerator = await media.createAVImageGenerator()
      // 设置fdSrc
      let resFile = fs.openSync(fileUri, fs.OpenMode.READ_ONLY)
      let fileLength = fs.statSync(resFile.fd).size
      avImageGenerator.fdSrc = { fd: resFile.fd, offset: 0, length: fileLength }
      // 初始化入参
      let timeUs = 0
      let queryOption = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC
      let param: media.PixelMapParams = {
        width: 300,
        height: 300
      }
      // 获取缩略图(promise模式)
      let pixelMap = await avImageGenerator.fetchFrameByTime(timeUs, queryOption, param)
      this.pixelMap = pixelMap
      // 释放资源(promise模式)
      avImageGenerator.release()
      fs.closeSync(resFile.fd)
    } catch (e) {
      console.info(`testTag fetchFrameByTime catch exception: ${JSON.stringify(e)}`)
    }
  }
}

更多关于鸿蒙中如何加载本地视频缩略图的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙系统中,加载本地视频缩略图可以通过AVImageGenerator类实现。首先,使用AVImageGeneratorcreateVideoThumbnail方法生成视频缩略图。该方法需要传入视频文件的路径和缩略图的目标尺寸。生成缩略图后,可以通过PixelMap对象获取图像的像素数据,并将其显示在UI组件上。以下是一个简化的代码示例:

import avImageGenerator from '@ohos.multimedia.avimagegenerator';

let videoPath = 'file:///path/to/video.mp4';
let options = {
  width: 100,
  height: 100
};

avImageGenerator.createVideoThumbnail(videoPath, options).then((pixelMap) => {
  // 使用pixelMap显示缩略图
}).catch((error) => {
  console.error('Failed to generate thumbnail:', error);
});
回到顶部