HarmonyOS 关于获取pixelmap对象代码示例

示例代码:

// 加载本地图片
  static async loadLocalPixelMap(resource: Resource, type: boolean): Promise<image.PixelMap | undefined> {
    if(!resource || !resource.params || resource.params.length < 1) {
      return
    }
    let name = resource.params[0] as string;
    let imageSource: image.ImageSource | undefined = undefined
    let context = getContext()
    if (type === true) {
      let fileBuffer = await context!.resourceManager.getRawFileContent(name);
      imageSource = image.createImageSource(fileBuffer.buffer.slice(fileBuffer.byteOffset, fileBuffer.byteLength + fileBuffer.byteOffset))
    } else {
      // load pixel map by uri
      let f = await fs.open(name, fs.OpenMode.READ_ONLY)
      imageSource = image.createImageSource(f.fd)
    }
    let options:  Record<string, number | boolean > = {
      'alphaType': 0, // 透明度
      'editable': false, // 是否可编辑
      'pixelFormat': 3, // 像素格式
      'scaleMode': 1, // 缩略值
    }
    let pixelMap = await imageSource.createPixelMap(options)
    return pixelMap
  }
  // 加载网络图片
  static async loadRemotePixelMap(url: string): Promise<image.PixelMap | undefined> {
    let outData: http.HttpResponse | undefined = undefined;
    let pixelMap: image.PixelMap | undefined = undefined;
    try {
      outData = await http.createHttp().request(url);
      let code: http.ResponseCode | number = (outData as http.HttpResponse).responseCode
      if (ResponseCode.ResponseCode.OK === code) {
        let imageData: ArrayBuffer = (outData as http.HttpResponse).result as ArrayBuffer;
        let imageSource: image.ImageSource = image.createImageSource(imageData);
        let options:  Record<string, number | boolean > = {
          'alphaType': 0, // 透明度
          'editable': false, // 是否可编辑
          'pixelFormat': 3, // 像素格式
          'scaleMode': 1, // 缩略值
        }
        pixelMap = await imageSource.createPixelMap(options)
      }
    } catch (e) {
      Logger.error(`http reqeust failed with | code: ${JSON.stringify(e.code)} | msg: ${JSON.stringify(e.message)}`)
    } finally {
      return pixelMap;
    }
  }
HarmonyOS
22h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

参考代码如下:

import { hilog } from '@kit.PerformanceAnalysisKit';
import { TextReader, TextReaderIcon, ReadStateCode } from '@kit.SpeechKit';
@Entry
@Component
struct Index {
  @State message: string = '';
  /**
   * 待加载的文章
   */
  @State readInfoList: TextReader.ReadInfo[] = [];
  @State selectedReadInfo: TextReader.ReadInfo = this.readInfoList[0];
  /**
   * 播放状态
   */
  @State readState: ReadStateCode = ReadStateCode.WAITING;
  /**
   * 用于显示当前页的按钮状态
   */
  @State isInit: boolean = false;
  @State isListening: boolean = false;
  async aboutToAppear() {
    /**
     * 加载数据
     */
    console.info('ReadStateCode', JSON.stringify(this.readState))
    let readInfoList: TextReader.ReadInfo[] = [{
      id: '001',
      title: {
        text: '水调歌头.明月几时有',
        isClickable: true
      },
      author: {
        text: '宋.苏轼',
        isClickable: true
      },
      date: {
        text: '2024/01/01',
        isClickable: false
      },
      bodyInfo: '明月几时有?把酒问青天。不知天上宫阙,今夕是何年。'
    }];
    this.readInfoList = readInfoList;
    this.selectedReadInfo = readInfoList[0];
    this.init();
  }
  /**
   * 初始化
   */
  async init() {
    const readerParam: TextReader.ReaderParam = {
      isVoiceBrandVisible: true,
      businessBrandInfo: {
        panelName: '小艺朗读',
        panelIcon: $r('app.media.startIcon')
      }
    }
    try {
      await TextReader.init(getContext(this), readerParam);
      this.isInit = true;
    } catch (err) {
      hilog.error(0x0001, TAG, 'init error: %{public}s', JSON.stringify(err))
    }
  }
  // 设置操作监听
  setActionListener() {
    TextReader.on('setArticle', (id: string) => {
    });
    TextReader.on('clickArticle', (id: string) => {
    });
    TextReader.on('clickAuthor', (id: string) => {
    });
    TextReader.on('clickNotification', (id: string) => {
      hilog.info(0x0001, TAG, `onClickNotification ${id}`)
    });
    TextReader.on('showPanel', () => {
      hilog.info(0x0001, TAG, `onShowPanel`)
    });
    TextReader.on('hidePanel', () => {
      hilog.info(0x0001, TAG, `onHidePanel`)
    });
    TextReader.on('stop', () => {
      hilog.info(0x0001, TAG, `onStop`)
    });
    TextReader.on('release', () => {
      hilog.info(0x0001, TAG, `onRelease`)
    });
    TextReader.on('stateChange', (state: TextReader.ReadState) => {
      hilog.info(0x1, TAG, `ReadState: %{public}s`, JSON.stringify(state));
      this.onStatusChanged(state)
    });
    TextReader.on('requestMore', () => this.onStatusChanged);
  }
  onStatusChanged = (state: TextReader.ReadState) => {
    hilog.info(0x1, TAG, `selectedReadInfo.id: %{public}s`, this.selectedReadInfo?.id);
    if (this.selectedReadInfo?.id === state.id) {
      hilog.warn(0x1, TAG, `match, changeState to %{public}s`, JSON.stringify(state))
      this.readState = state.state;
    } else {
      this.readState = ReadStateCode.WAITING;
    }
  }
  // 设置事件监听
  setEventListener() {
    TextReader.on('eventNotification', (event: TextReader.NotificationEvent) => {
      hilog.info(0x0001, TAG, `event: ${JSON.stringify(event)}`)
    })
    TextReader.on('eventPanel', (event: TextReader.PanelEvent) => {
      hilog.info(0x0001, TAG, `event: ${JSON.stringify(event)}`)
    })
    TextReader.on('eventReadList', (event: Array<TextReader.ListEventState>) => {
      hilog.info(0x0001, TAG, `event: ${JSON.stringify(event)}`)
    })
  }
  build() {
    Column() {
      TextReaderIcon({ readState: this.readState })
        .margin({ right: 20 })
        .width(32)
        .height(32)
        .onClick(async () => {
          // 若未初始化,先初始化并启动
          try {
            this.setActionListener();
            this.setEventListener();
            await TextReader.start(this.readInfoList, this.selectedReadInfo?.id);
          } catch (err) {
            hilog.error(0x0001, TAG, 'init message: %{public}s', JSON.stringify(err))
          }
        })
      Text('click icon to play').fontSize(10)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
  }
}
分享
微博
QQ
微信
回复
20h前
相关问题
如何获取经纬度示例代码
1043浏览 • 1回复 待解决
使用hiappevent获取崩溃日志的示例代码
1926浏览 • 1回复 待解决
xComponet示例代码不能使用
900浏览 • 1回复 待解决
HarmonyOS AVCodec Kit 示例代码/Codelab
8浏览 • 1回复 待解决
HarmonyOS 关于合并对象
48浏览 • 2回复 待解决
HarmonyOS 数据库的相关示例代码参考
204浏览 • 1回复 待解决
有使用华为支付的示例代码
1810浏览 • 1回复 待解决
HarmonyOS 获取网络图片PixelMap
43浏览 • 1回复 待解决