HarmonyOS 鸿蒙Next 切图之后保存为图片文件,开发应可通过id获取资源,但目前无法获取id 图标库

HarmonyOS 鸿蒙Next 切图之后保存为图片文件,开发应可通过id获取资源,但目前无法获取id 图标库

切图之后,保存为图片文件,开发应该可以通过id拿到资源,但是现在没办法拿到id 图标库:https://developer.huawei.com/consumer/cn/doc/design-guides/system-icons-0000001929854962#section161242864516


更多关于HarmonyOS 鸿蒙Next 切图之后保存为图片文件,开发应可通过id获取资源,但目前无法获取id 图标库的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

参考下这个demo:

import { common } from '[@kit](/user/kit).AbilityKit';
import { BusinessError, request } from '[@kit](/user/kit).BasicServicesKit';
import fs from '[@ohos](/user/ohos).file.fs';
import { fileUri } from '[@kit](/user/kit).CoreFileKit';
import { joinPicture } from '../../utils/JoinPicture'
import { photoAccessHelper } from '[@kit](/user/kit).MediaLibraryKit';
import { image } from '[@kit](/user/kit).ImageKit';

[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
 [@State](/user/State) imageUri: string = '';
 [@State](/user/State) combineImageUri: string = '';
 context = getContext(this) as common.UIAbilityContext;
 filePath = this.context.filesDir + '/test.jpg';
 combinePath = this.context.filesDir + '/combine.jpg';
 saveButtonOptions: SaveButtonOptions = {
   icon: SaveIconStyle.FULL_FILLED,
   text: SaveDescription.SAVE_IMAGE,
   buttonType: ButtonType.Capsule
 } // 设置安全控件按钮属性

 onPageShow(): void {
   this.checkImageExist()
 }

 checkImageExist(notExistCallback?: Function) {
   fs.access(this.filePath).then((res: boolean) => {
     if (res) {
       console.info("PictureJoinTogether file exists");
       this.imageUri = fileUri.getUriFromPath(this.filePath);
     } else {
       console.info("PictureJoinTogether file not exists");
       if (notExistCallback) {
         notExistCallback()
       }
     }
   }).catch((err: BusinessError) => {
     console.info("PictureJoinTogether access failed with error message: " + err.message + ", error code: " + err.code);
   });
 }

 // 只是为了分享图片,随便找个图片下载
 downloadFile(callback: Function) {
   this.checkImageExist(() => {
     request.downloadFile(this.context, {
       url: 'https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2019-11-22%2F5dd7afa7df0fc.jpg&thumburl=https%3A%2F%2Fimg1.baidu.com%2Fit%2Fu%3D2205810988%2C4283060315%26fm%3D253%26fmt%3Dauto%26app%3D138%26f%3DJPEG%3Fw%3D800%26h%3D500',
       filePath: this.filePath,
       background: true
     }).then((downloadTask: request.DownloadTask) => {
       downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
         console.info("PictureJoinTogether download receivedSize:" + receivedSize + " totalSize:" + totalSize);
       });

       downloadTask.on('complete', () => {
         console.info('PictureJoinTogether download complete');
         callback()
       })
     }).catch((err: BusinessError) => {
       console.error(`PictureJoinTogether Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
     });
   })
 }

 build() {
   Column({space: 10}) {
     Button('下载图片')
       .onClick(() => {
         if (this.imageUri !== '') {
           return;
         }
         this.downloadFile(() => {
           this.imageUri = fileUri.getUriFromPath(this.filePath);
         })
       })

     Image(this.imageUri)
       .width(200)
       .height(200)
       .backgroundColor(Color.Gray)

     Button('合并图片并保存到应用内')
       .onClick(() => {
         joinPicture.join([this.filePath, this.filePath], this.combinePath, () => {
           this.combineImageUri = fileUri.getUriFromPath(this.combinePath);
         })
       })

     Image(this.combineImageUri)
       .width(400)
       .height(200)
       .backgroundColor(Color.Gray)

     // 通过安全控件保存应用图片到图库
     SaveButton(this.saveButtonOptions)
       .onClick(async (event, result: SaveButtonOnClickResult) => {
         if (result === SaveButtonOnClickResult.SUCCESS) {
           try {
             const context = getContext();
             const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
             const uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
             console.info('createAsset successfully, uri: ' + uri);
             const file = await fs.open(uri, fs.OpenMode.READ_WRITE);
             const imageSource = image.createImageSource(this.combinePath);
             const imageInfo = await imageSource.getImageInfo();
             const opts: image.DecodingOptions = {
               editable: true,
               // 注意和拼接图片时的格式统一
               desiredPixelFormat: image.PixelMapFormat.BGRA_8888,
               desiredSize: { width: imageInfo.size.width, height: imageInfo.size.height }
             };
             // 需要通过packing打包图片,直接获取buffer并写入会导致图库中图片无法显示
             const pixelMap = await imageSource.createPixelMap(opts);
             const imagePackerApi: image.ImagePacker = image.createImagePacker();
             let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 };
             const packingArrayBuffer = await imagePackerApi.packing(pixelMap, packOpts);
             console.info('packing succeeded.');
             fs.writeSync(file.fd, packingArrayBuffer, { offset: 0 })
             fs.closeSync(file.fd)
           } catch (err) {
             console.error('createAsset failed, message = ', err);
           }
         } else {
           console.error('SaveButtonOnClickResult createAsset failed');
         }
       })
   }
   .width('100%')
   .height('100%')
   .justifyContent(FlexAlign.Center)
 }
}

更多关于HarmonyOS 鸿蒙Next 切图之后保存为图片文件,开发应可通过id获取资源,但目前无法获取id 图标库的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙系统中,对于Next切图后保存为图片文件并通过ID获取资源的问题,首先需要确认几个关键点以确保流程无误。

  1. 资源文件路径与命名:确保切图后的图片资源已正确导入项目资源文件夹,且文件名(包括扩展名)与在代码中引用的ID完全匹配。HarmonyOS对资源命名有严格要求,通常使用小写字母、数字和下划线。

  2. 资源ID定义:检查资源文件是否在项目的资源定义文件(如resources.json或对应XML文件)中正确声明了ID,并且ID的命名遵循系统规则,无重复且格式正确。

  3. 代码引用:在代码中获取资源时,确保使用的ID与资源文件中定义的完全一致。通常通过资源管理系统(如ResourceManager)来获取资源。

  4. 编译与清理:尝试清理并重新编译项目,有时候IDE缓存或编译过程中的问题可能导致资源无法正确加载。

  5. 权限检查:确认应用是否具有访问存储资源(如读写外部存储)的权限,特别是如果资源文件存储在特定路径下。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。

回到顶部