HarmonyOS如何向模拟器相册添加一些图片?如何实现通过接口把从相册选的图片上传到服务器?

HarmonyOS如何向模拟器相册添加一些图片?如何实现通过接口把从相册选的图片上传到服务器?


HarmonyOS
2024-09-10 11:56:50
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

第一个问题,您可以用代码方式写入相册,demo如下:

import { resourceManager } from '@kit.LocalizationKit'; 
import { image } from '@kit.ImageKit'; 
import { Permissions } from '@kit.AbilityKit'; 
import PermissionsUtil from '../common/utils/PermissionsUtil'; 
import { photoAccessHelper } from '@kit.MediaLibraryKit'; 
import { dataSharePredicates } from '@kit.ArkData'; 
import fs from '@ohos.file.fs'; 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
  @State uriTemp: string = ''; 
  @State pixelMap:image.PixelMap  | undefined = undefined 
  private permissions: Array<Permissions> = ['ohos.permission.WRITE_IMAGEVIDEO','ohos.permission.READ_IMAGEVIDEO']; 
  async aboutToAppear(): Promise<void> { 
    PermissionsUtil.checkPermissions(this.permissions) 
  } 
  // 打包 PixelMap 为 jpg 格式 
  async packingPixelMap2Jpg(pixelMap: PixelMap): Promise<ArrayBuffer> { 
    const imagePackerApi = image.createImagePacker(); 
    const packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 }; 
    let imageBuffer: ArrayBuffer = new ArrayBuffer(1); 
    try { 
      // 图片压缩或重新打包 
      imageBuffer = await imagePackerApi.packing(pixelMap, packOpts); 
    } catch (err) { 
      console.error(`Invoke packingPixelMap2Jpg failed, err: ${JSON.stringify(err)}`); 
    } 
    return imageBuffer; 
  } 
  async getPixelMapByImage():Promise<image.PixelMap>{ 
    const context : Context = getContext(this); 
    // 获取resourceManager资源管理器 
    const resourceMgr : resourceManager.ResourceManager = context.resourceManager; 
    let rawFileDescriptor = await resourceMgr.getRawFd('food.png') 
    const imageSource : image.ImageSource = image.createImageSource(rawFileDescriptor); 
    let decodingOptions : image.DecodingOptions = { 
      editable: true, 
      desiredPixelFormat: 3, 
    } 
    // 创建pixelMap并进行简单的旋转和缩放 
    const pixelMap:image.PixelMap = await imageSource.createPixelMap(decodingOptions) 
    this.pixelMap =  pixelMap 
    return pixelMap; 
  } 
  //展示相册第一张图片 
  async showFirstPhoto() { 
    let context = getContext(this); 
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 
    console.info('getAssets'); 
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 
    let fetchOptions: photoAccessHelper.FetchOptions = { 
      fetchColumns: [], 
      predicates: predicates 
    }; 
    phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => { 
      if (fetchResult !== undefined) { 
        console.info('fetchResult success'); 
        let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); 
        this.uriTemp = photoAsset.uri 
        if (photoAsset !== undefined) { 
          console.info('photoAsset.displayName : ' + photoAsset.displayName); 
        } 
      } else { 
        console.error(`fetchResult fail with error: ${err.code}, ${err.message}`); 
      } 
    }); 
  } 
  async  WritePhoto() { 
    console.info('createAssetDemo'); 
    let context = getContext(this); 
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 
    let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE; 
    let extension:string = 'png'; 
    let options: photoAccessHelper.CreateOptions = { 
      title: 'testPhoto' 
    } 
    let uri = await phAccessHelper.createAsset(photoType, extension, options); 
    // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制 
    let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 
    try { 
      const imageBuffer = await this.packingPixelMap2Jpg(this.pixelMap as image.PixelMap) 
 
      // 写到媒体库文件中 
      await fs.write(file.fd, imageBuffer); 
      await fs.close(file.fd); 
      AlertDialog.show({message:'已保存至相册!'}); 
    } 
    catch (err) { 
      console.error("error is "+ JSON.stringify(err)) 
    } 
  } 
  build() { 
    Column() { 
      Column() { 
        Row() { 
          Button('创建Pixelmap') 
            .onClick(() => { 
              this.getPixelMapByImage() 
            }) 
          Button('保存Pixelmap') 
            .onClick(() => { 
 
              this.WritePhoto() 
            }) 
        } 
        Image(this.pixelMap as image.PixelMap) 
          .width(260) 
          .height(260) 
      } 
      Row() { 
        Column(){ 
          Button('uri图片展示') 
            .onClick(()=>{ 
              this.showFirstPhoto() 
            }) 
          Image(this.uriTemp) 
            .width(200) 
            .height(200) 
        } 
        Column(){ 
          Button('pixelMap图片展示') 
            .onClick(()=>{ 
 
            }) 
          Image(this.pixelMap) 
            .width(200) 
            .height(200) 
        } 
      } 
    } 
    .height('100%') 
  } 
}

PermissionsUtil.ets文件

import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit'; 
import { BusinessError } from '@kit.BasicServicesKit'; 
class PermissionsUtil { 
  async checkPermissions(permissions: Array<Permissions>): Promise<void> { 
    let applyResult: boolean = false; 
    for (let permission of permissions) { 
      let grantStatus: abilityAccessCtrl.GrantStatus = await this.checkAccessToken(permission); 
      if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { 
        applyResult = true; 
      } else { 
        applyResult = false; 
      } 
    } 
    if (!applyResult) { 
      this.requestPermissions(permissions); 
    } 
  } 
  async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> { 
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
    let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED; 
    // 获取应用程序的accessTokenID 
    let tokenId: number = 0; 
    try { 
      let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION); 
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; 
      tokenId = appInfo.accessTokenId; 
    } catch (error) { 
      let err: BusinessError = error as BusinessError; 
      console.error(`Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`); 
    } 
    // 校验应用是否被授予权限 
    try { 
      grantStatus = await atManager.checkAccessToken(tokenId, permission); 
    } catch (error) { 
      let err: BusinessError = error as BusinessError; 
      console.error(`Failed to check access token. Code is ${err.code}, message is ${err.message}`); 
    } 
 
    return grantStatus; 
  } 
  requestPermissions(permissions: Array<Permissions>): void { 
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
    atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext, permissions) 
      .then((data: PermissionRequestResult) => { 
        console.info('request Permissions success') 
      }) 
      .catch((err: BusinessError) => { 
        console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
      }) 
  } 
} 
export default new PermissionsUtil();

关于第二个问题,通过PhotoViewPicker获取到的图片不能直接用于传输,可以通过将其复制在应用沙箱路径下,然后再用沙箱路径下的文件进行传输。 下面是部分demo:

import { BusinessError } from '@ohos.base'; 
import { rcp } from '@kit.RemoteCommunicationKit'; 
import { picker } from '@kit.CoreFileKit'; 
import fs from '@ohos.file.fs'; 
import { http } from '@kit.NetworkKit'; 
let uploadUrl: string = 'http://192.xx.xxx.xx:8080/upload'; 
function example01(): string { 
  let uri = ''; 
  let photoViewPicker = new picker.PhotoViewPicker(); 
  let photoSelectOption = new picker.PhotoSelectOptions(); 
  photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; 
  photoViewPicker.select(photoSelectOption).then((photoSelectResult) => { 
    console.log("photoSelectResult:" + photoSelectResult); 
    uri = photoSelectResult.photoUris[0]; 
    console.log("uri:" + uri); 
    try { 
      let resultPhoto = fs.openSync(uri,fs.OpenMode.READ_ONLY); 
      let resultName = resultPhoto.name; 
      let fileTemp = fs.openSync(getContext().filesDir+resultPhoto.name,fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE); 
      let imageUri = fileTemp.path; 
      fs.copyFileSync(resultPhoto.fd,fileTemp.fd); 
      fs.closeSync(resultPhoto); 
      fs.closeSync(fileTemp); 
      const httpRequest = http.createHttp(); 
      httpRequest.request(uploadUrl,{ 
        method:http.RequestMethod.POST, 
        header:{ 'Content-Type': 'multipart/form-data', 'Connection':'keep-alive' }, 
        expectDataType:http.HttpDataType.ARRAY_BUFFER, 
        multiFormDataList: [ { name:'file', 
          contentType: 'image/jpg', 
          filePath: imageUri, 
          remoteFileName:'file.jpg' }, 
        ], 
      },(err,data) => { 
        console.log('test:上传结束') 
        httpRequest.destroy(); 
      } ) 
    } catch (err) { 
      console.error(fyh:Failed to request the upload. err: ${JSON.stringify(err)}); 
    } }).catch((err:BusinessError) => { 
    console.error(Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}); 
  }) 
  return uri; 
} 
function testRcpMultiPartUpload() { 
  example01(); 
} 
function clickget() { 
  const session = rcp.createSession(); 
  session.get("http://192.x.xx.xxx:8080/getText").then((response) => { 
    console.log("test"+JSON.stringify(response)); 
  }).catch((err: BusinessError) => { 
    console.error("err:" + JSON.stringify(err)); 
  }); 
} 
@Entry 
@Component struct Index { 
  @State message: string = 'Hello World'; 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            testRcpMultiPartUpload(); 
          }) 
        Text('getText') .fontSize(50) .fontWeight(FontWeight.Bold) 
          .onClick(() => { 
            clickget(); 
          }) 
      } .width('100%') 
    } .height('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-09-10 15:56:03
相关问题
HarmonyOS如何上传图片模拟器相册
640浏览 • 1回复 待解决
怎么往模拟器相册增加图片和视频
248浏览 • 1回复 待解决
HarmonyOS 文件上传服务器问题
210浏览 • 1回复 待解决
HarmonyOS如何图片保存到手机相册
332浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
704浏览 • 1回复 待解决
本机获取图片进行上传到spring后端
2258浏览 • 1回复 待解决
模拟器启动不了,创建时phone
6994浏览 • 3回复 已解决
如何编辑裁剪相册图片
360浏览 • 1回复 待解决
如何读取相册图片
716浏览 • 1回复 待解决
HarmonyOS如何下载模拟器
241浏览 • 1回复 待解决
HarmonyOS如何实现图片上传
282浏览 • 1回复 待解决