ThumbnailGetter.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2023 Huawei Device Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import mediaLibrary from '@ohos.multimedia.mediaLibrary'
  16. import { Context } from '@ohos.abilityAccessCtrl'
  17. import Logger from '../utils/Logger'
  18. import { GlobalContext } from '../utils/GlobalThis'
  19. import image from '@ohos.multimedia.image';
  20. export default class ThumbnailGetter {
  21. private TAG = '[ThumbnailGetter]:'
  22. public async getThumbnailInfo(width: number, height: number, uri?: string): Promise<image.PixelMap | undefined> {
  23. Logger.info(`${this.TAG} getThumbnailInfo E`)
  24. Logger.debug(`${this.TAG} getThumbnailInfo width: ${width}, height: ${height}, uri: ${JSON.stringify(uri)}`)
  25. const fileKeyObj = mediaLibrary.FileKey;
  26. let fetchOp: any
  27. const media = mediaLibrary.getMediaLibrary(GlobalContext.getContext().getObject("context") as Context);
  28. let publicPath: string = await media.getPublicDirectory(mediaLibrary.DirectoryType.DIR_CAMERA)
  29. Logger.info(`${this.TAG} getThumbnailInfo media: ${media}`)
  30. fetchOp = {
  31. selections: `${fileKeyObj.RELATIVE_PATH}=?`,
  32. selectionArgs: [publicPath],
  33. order: `${fileKeyObj.DATE_ADDED} DESC LIMIT 0, 1`
  34. }
  35. Logger.info(`${this.TAG} getThumbnailInfo fetchOp: ${JSON.stringify(fetchOp)}`)
  36. const fetchFileResult = await media.getFileAssets(fetchOp);
  37. const count = fetchFileResult.getCount()
  38. Logger.info(`${this.TAG} getThumbnailInfo fetchFileResult.getCount: ${count}`)
  39. if (count == 0) {
  40. return undefined
  41. }
  42. const lastFileAsset = await fetchFileResult.getLastObject()
  43. await fetchFileResult.close()
  44. if (lastFileAsset == null) {
  45. Logger.error(`${this.TAG} getThumbnailInfo lastFileAsset is null`)
  46. return undefined
  47. }
  48. const thumbnailPixelMap = lastFileAsset.getThumbnail({
  49. width: width, height: height
  50. })
  51. Logger.info(`${this.TAG} getThumbnailInfo thumbnailPixelMap: ${JSON.stringify(thumbnailPixelMap)} X`)
  52. return thumbnailPixelMap
  53. }
  54. }