文档管理中心

如何保存网络图片到相册

本文导读

可以使用安全控件中的保存控件,省去权限申请和权限请求等环节,获得临时授权,保存对应图片。需要申请的权限为:ohos.permission.INTERNET。参考代码如下:

收起
自动换行
深色代码主题
复制
  1. import { http } from '@kit.NetworkKit';
  2. import { image } from '@kit.ImageKit';
  3. import { BusinessError } from '@kit.BasicServicesKit';
  4. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  5. import { fileIo } from '@kit.CoreFileKit';
  6. @Entry
  7. @Component
  8. struct SaveImage {
  9. @State pixelMap: PixelMap | undefined = undefined;
  10. loadImageWithUrl(url: string) {
  11. let responseCode = http.ResponseCode;
  12. let OutData: http.HttpResponse;
  13. let imagePackerApi = image.createImagePacker();
  14. let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 98 };
  15. // 确保网络正常
  16. http.createHttp().request(url, {
  17. method: http.RequestMethod.GET,
  18. connectTimeout: 60000,
  19. readTimeout: 60000
  20. },
  21. async (error: BusinessError, data: http.HttpResponse) => {
  22. if (error) {
  23. console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`);
  24. } else {
  25. OutData = data;
  26. let code: http.ResponseCode | number = OutData.responseCode;
  27. if (responseCode.OK === code) {
  28. let imageData: ArrayBuffer = OutData.result as ArrayBuffer;
  29. let imageSource: image.ImageSource = image.createImageSource(imageData);
  30. class tmp {
  31. height: number = 100
  32. width: number = 100
  33. };
  34. let options: Record<string, number | boolean | tmp> = {
  35. 'alphaType': 0, // Transparency
  36. 'editable': false, // Is it editable
  37. 'pixelFormat': 3, // Pixel Format
  38. 'scaleMode': 1, // Abbreviation
  39. 'size': { height: 100, width: 100 }
  40. }; // Create Image Size
  41. imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
  42. this.pixelMap = pixelMap;
  43. this.pixelMap.getImageInfo().then((info: image.ImageInfo) => {
  44. console.info('info.width = ' + info.size.width);
  45. }).catch((err: BusinessError) => {
  46. console.error('Failed ' + err);
  47. })
  48. imagePackerApi.packToData(pixelMap, packOpts).then(async (buffer: ArrayBuffer) => {
  49. try {
  50. const context = this.getUIContext().getHostContext()!;
  51. let helper = photoAccessHelper.getPhotoAccessHelper(context);
  52. let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png');
  53. let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  54. // Write to file
  55. await fileIo.write(file.fd, buffer);
  56. this.getUIContext().getPromptAction().showToast({ message: '已保存至相册!' });
  57. // Close the file
  58. await fileIo.close(file.fd);
  59. } catch (error) {
  60. console.error('error is ' + JSON.stringify(error));
  61. }
  62. }).catch((error: BusinessError) => {
  63. console.error('Failed to pack the image. And the error is: ' + error);
  64. }).finally(()=>{
  65. pixelMap.release();
  66. })
  67. })
  68. }
  69. }
  70. }
  71. )
  72. }
  73. build() {
  74. Row() {
  75. Column({ space: 10 }) {
  76. Image('https://agc-storage-drcn.platform.dbankcloud.cn/v0/test-rqcjj/test.png')
  77. .width('80%')
  78. SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
  79. if (result === SaveButtonOnClickResult.SUCCESS) {
  80. this.loadImageWithUrl('https://agc-storage-drcn.platform.dbankcloud.cn/v0/test-rqcjj/test.png');
  81. } else {
  82. this.getUIContext().getPromptAction().showToast({ message: '设置权限失败!' });
  83. }
  84. })
  85. }
  86. .width('100%')
  87. }
  88. .height('100%')
  89. .backgroundColor(0xF1F3F5)
  90. }
  91. }