新增媒体图片file://格式

Signed-off-by: zgf <zenggaofeng2@h-partners.com>
This commit is contained in:
zgf 2024-06-06 15:15:20 +08:00
parent a3314d003a
commit 77b016fde9
6 changed files with 136 additions and 1 deletions

View File

@ -1,6 +1,7 @@
## 3.0.0-rc.7
- 修复成功回调获取不到宽高
- 新增svg图片解码
- 新增媒体图片file://格式
## 3.0.0-rc.6
- 支持多种组合变换

View File

@ -19,6 +19,8 @@ import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import { ImageKnife, InitImageKnife, LogUtil } from '@ohos/libraryimageknife';
import { CustomEngineKeyImpl } from '../common/CustomEngineKeyImpl';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base'
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
@ -31,6 +33,18 @@ export default class EntryAbility extends UIAbility {
async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
// Main window is created, set main page for this ability
let list: Array<Permissions> = ['ohos.permission.MEDIA_LOCATION', 'ohos.permission.READ_MEDIA'];
let permissionRequestResult: Object;
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err: BusinessError, result: Object) => {
if (err) {
} else {
permissionRequestResult = result;
}
})
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
LogUtil.mLogLevel = LogUtil.ALL

View File

@ -126,6 +126,13 @@ struct Index {
});
})
Button("测试媒体url").margin({top:10}).onClick(()=>{
router.push({
uri: 'pages/dataShareUriLoadPage',
});
})
}
} .width('100%')
.height('100%')

View File

@ -0,0 +1,96 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/libraryimageknife'
@Entry
@Component
struct DataShareUriLoadPage {
@State imageKnifeOption1: ImageKnifeOption =
{
loadSrc: $r('app.media.icon'),
placeholderSrc: $r('app.media.loading'),
errorholderSrc: $r('app.media.failed')
};
build() {
Scroll() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text("获取媒体图库的uri用ImageKnife展示").fontSize(15)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("点击加载Uri并展示")
.onClick(() => {
// 获取mediaLibrary实例后续用到此实例均采用此处获取的实例
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
let imageType = mediaLibrary.MediaType.IMAGE;
// 创建文件获取选项此处参数为获取image类型的文件资源
let imagesFetchOp:mediaLibrary.MediaFetchOptions = {
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
};
// 获取文件资源使用callback方式返回异步结果
media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
// 判断获取的文件资源的检索结果集是否为undefined若为undefined则接口调用失败
if (fetchFileResult == undefined) {
console.log('get fetchFileResult failed with error: ' + error);
return;
}
// 获取文件检索结果集中的总数
const count = fetchFileResult.getCount();
// 判断结果集中的数量是否小于0小于0时表示接口调用失败
if (count < 0) {
console.log('get count from fetchFileResult failed, count: ' + count);
return;
}
// 判断结果集中的数量是否等于0等于0时表示接口调用成功但是检索结果集为空请检查文件获取选项参数配置是否有误和设备中是否存在相应文件
if (count == 0) {
console.log('The count of fetchFileResult is zero');
return;
}
console.log('Get fetchFileResult successfully, count: ' + count);
// 获取文件检索结果集中的第一个资源使用callback方式返回异步结果
fetchFileResult.getFirstObject((error, fileAsset) => {
// 检查获取的第一个资源是否为undefined若为undefined则接口调用失败
if (fileAsset == undefined) {
console.log('get first object failed with error: ' + error);
return;
}
console.log("fileAsset id=" + fileAsset.id + " fileAsset uri=" + fileAsset.uri + " fileAsset displayName=" + fileAsset.displayName)
// 加载图库第一张图片的uri
this.imageKnifeOption1 = {
loadSrc: fileAsset.uri,
placeholderSrc: $r('app.media.loading'),
errorholderSrc: $r('app.media.failed')
}
// 释放FetchFileResult实例并使其失效。无法调用其他方法
fetchFileResult.close();
});
});
}).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300)
}.width('100%').backgroundColor(Color.Pink)
}
}
.width('100%')
.height('100%')
}
}

View File

@ -17,6 +17,7 @@
"pages/TestWriteCacheStage",
"pages/LoadStatePage",
"pages/TestHspPreLoadImage",
"pages/TestRemoveCache"
"pages/TestRemoveCache",
"pages/dataShareUriLoadPage"
]
}

View File

@ -464,6 +464,22 @@ async function requestJob(request: RequestJobRequest, requestList?: List<ImageKn
LogUtil.log("success get image from filecache for key = " + fileKey);
loadError = "success get image from filecache for key = " + fileKey;
}
} else if (request.src.startsWith('datashare://') || request.src.startsWith('file://')) {
await fs.open(request.src, fs.OpenMode.READ_ONLY).then(async (file) => {
await fs.stat(file.fd).then(async (stat) =>{
let buf = new ArrayBuffer(stat.size);
await fs.read(file.fd, buf).then((readLen) => {
resBuf = buf;
fs.close(file.fd);
}).catch((err:BusinessError) => {
loadError = 'LoadDataShareFileClient fs.read err happened uri=' + request.src + " err.msg=" + err?.message + " err.code=" + err?.code;
})
}).catch((err:BusinessError) => {
loadError = 'LoadDataShareFileClient fs.stat err happened uri=' + request.src + " err.msg=" + err?.message + " err.code=" + err?.code;
})
}).catch((err:BusinessError) => {
loadError ='LoadDataShareFileClient fs.open err happened uri=' + request.src + " err.msg=" + err?.message + " err.code=" + err?.code;
})
} else { //从本地文件获取
try {
let stat = fs.statSync(request.src);