1.修复单帧gif图片加载不出来问题 2.修复xts用例获取不到context问题

Signed-off-by: baofeng <baofeng6@h-partners.com>
This commit is contained in:
baofeng 2024-03-08 17:00:13 +08:00
parent ec07480c42
commit 917ac424de
9 changed files with 265 additions and 315 deletions

View File

@ -22,33 +22,49 @@ import { TestDataSource } from './model/TestDataSource';
struct TestManyNetImageLoadWithPage2 { struct TestManyNetImageLoadWithPage2 {
private data: TestDataSource = new TestDataSource(); private data: TestDataSource = new TestDataSource();
private setting: DiskStrategy = new NONE(); private setting: DiskStrategy = new NONE();
private scroller: Scroller = new Scroller()
build() { build() {
Scroll() { Scroll() {
Column() { Column() {
Grid() { Grid(this.scroller) {
LazyForEach(this.data, (item: Material, index) => { LazyForEach(this.data, (item: Material, index) => {
GridItem() { if(index < 100) {
ImageKnifeComponent({ GridItem() {
imageKnifeOption: { Stack({ alignContent: Alignment.BottomEnd }) {
loadSrc: item.thumbnail, ImageKnifeComponent({
placeholderSrc: $r('app.media.icon_loading'), imageKnifeOption: {
mainScaleType: ScaleType.CENTER_CROP, loadSrc: item.thumbnail,
placeholderScaleType: ScaleType.CENTER_CROP, placeholderSrc: $r('app.media.icon_loading'),
isCacheable: false, mainScaleType: ScaleType.CENTER_CROP,
// strategy: this.setting placeholderScaleType: ScaleType.CENTER_CROP,
isCacheable: false,
// strategy: this.setting
}
}).width('100%').height('100%')
//Grid组件并发加载大量图片会出现白块对比使用image库也会出现
//Image(item.thumbnail).width('100%').backgroundColor(Color.Blue).objectFit(ImageFit.Contain)
Text(index+"."+item.name)
.fontSize(10)
.maxLines(1)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.layoutWeight(1)
.width('100%')
.backgroundColor(Color.Orange)
} }
}).width('100%').height('100%') }.width('45%').height(200)
}.width('45%').height(200) }
}, (item: string) => JSON.stringify(item)) }, (item: Material) => item.material_id)
} }
.columnsTemplate('1fr 1fr') .columnsTemplate('1fr 1fr')
.columnsGap(8) .columnsGap(8)
.maxCount(8)
.rowsGap(10) .rowsGap(10)
.width('100%') .width('100%')
.hitTestBehavior(HitTestMode.None) .hitTestBehavior(HitTestMode.None)
.maxCount(10) .maxCount(10)
.cachedCount(5) .cachedCount(3)
}.margin({ top: 5 }) }.margin({ top: 5 })
} }
} }

View File

@ -12,12 +12,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import hilog from '@ohos.hilog'; import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Hypium } from '@ohos/hypium' import { DiskLruCache, DiskCacheEntry } from '@ohos/imageknife'
import { DiskLruCache, ImageKnifeGlobal, ImageKnife, DiskCacheEntry } from '@ohos/imageknife' import { common } from '@kit.AbilityKit';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
import { AbilityConstant, common, UIAbility, Want } from '@kit.AbilityKit';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { GlobalContext } from '../testability/GlobalContext'
const BASE_COUNT: number = 2000; const BASE_COUNT: number = 2000;
@ -26,6 +25,7 @@ export default function DiskLruCacheTest() {
describe('DiskLruCacheTest', () => { describe('DiskLruCacheTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function. // Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => { beforeAll(() => {
//ImageKnife.with(this.context.createModuleContext("entry_test"));
// Presets an action, which is performed only once before all test cases of the test suite start. // Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
@ -45,115 +45,100 @@ export default function DiskLruCacheTest() {
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('testSetCahe', 0, () => { it('testSetCahe', 0, () => {
let context: Object | undefined = ImageKnifeGlobal.getInstance().getHapContext(); let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
if (context != undefined) { let disLruCache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let disLruCache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024); let startTime = new Date().getTime();
let startTime = new Date().getTime(); disLruCache.set('test', "Hello World Simple Example.");
disLruCache.set('test', "Hello World Simple Example."); disLruCache.set('testABC', "Hello World ABC");
disLruCache.set('testABC', "Hello World ABC"); disLruCache.set('testDE', "Hello World Simple DE");
disLruCache.set('testDE', "Hello World Simple DE"); expect(String.fromCharCode(...new Uint8Array(disLruCache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.") .assertTrue()
.assertTrue() expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testABC') as ArrayBufferLike)) == "Hello World ABC")
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testABC') as ArrayBufferLike)) == "Hello World ABC") .assertTrue()
.assertTrue() expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testDE') as ArrayBufferLike)) == "Hello World Simple DE")
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testDE') as ArrayBufferLike)) == "Hello World Simple DE") .assertTrue()
.assertTrue() let str: string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
let str: string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; for (let index = 0; index < 100; index++) {
for (let index = 0; index < 100; index++) { str += index;
str += index; disLruCache.set('test' + index, str);
disLruCache.set('test' + index, str);
}
expect(disLruCache.getSize() <= 1024).assertTrue()
endTime(startTime, 'testSetCahe');
disLruCache.cleanCacheData();
} }
expect(disLruCache.getSize() <= 1024).assertTrue()
endTime(startTime, 'testSetCahe');
disLruCache.cleanCacheData();
}) })
it('testGetCacheAsync', 1, () => { it('testGetCacheAsync', 1, () => {
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext; let filesDir: object | undefined = GlobalContext.getInstance().getObject("filesDir");
if (context != undefined) { let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let data = context.filesDir let startTime = new Date().getTime();
let cache: DiskLruCache = DiskLruCache.create(context); let path = filesDir + '/testFile.txt';
let startTime = new Date().getTime(); let file = fs.openSync(path, 0o102);
let path = data + '/testFile.txt'; fs.writeSync(file.fd, "hello, world!");
let file = fs.openSync(path, 0o102); let length = fs.statSync(path).size;
fs.writeSync(file.fd, "hello, world!"); let dataArr = new ArrayBuffer(length);
let length = fs.statSync(path).size; fs.readSync(file.fd, dataArr);
let dataArr = new ArrayBuffer(length); cache.set('testFile', dataArr);
fs.readSync(file.fd, dataArr); expect(cache.get('testFile')?.byteLength == 13).assertTrue()
cache.set('testFile', dataArr); endTime(startTime, 'testGetCacheAsync');
expect(cache.get('testFile')?.byteLength == 13).assertTrue() cache.cleanCacheData();
endTime(startTime, 'testGetCacheAsync');
cache.cleanCacheData();
}
}) })
it('testDeleteCacheDataByKey', 2, () => { it('testDeleteCacheDataByKey', 2, () => {
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext; let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
if (context != undefined) { let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let cache: DiskLruCache = DiskLruCache.create(context); let startTime = new Date().getTime();
let startTime = new Date().getTime(); cache.set('test', "Hello World Simple Example.");
cache.set('test', "Hello World Simple Example."); cache.set('testABC', "Hello World ABC");
cache.set('testABC', "Hello World ABC"); expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)))
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike))) .assertEqual("Hello World Simple Example.");
.assertEqual("Hello World Simple Example."); expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike)))
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike))) .assertEqual("Hello World ABC");
.assertEqual("Hello World ABC"); cache.deleteCacheDataByKey('test');
cache.deleteCacheDataByKey('test'); cache.deleteCacheDataByKey('testABC');
cache.deleteCacheDataByKey('testABC'); expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike))).assertEqual('');
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike))).assertEqual(''); expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike))).assertEqual('');
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike))).assertEqual(''); endTime(startTime, 'testDeleteCacheDataByKey');
endTime(startTime, 'testDeleteCacheDataByKey'); cache.cleanCacheData();
cache.cleanCacheData();
}
}) })
it('testGetPath', 3, async () => { it('testGetPath', 3, () => {
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext; let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
if (context != undefined) { let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let cache: DiskLruCache = DiskLruCache.create(context); let startTime = new Date().getTime();
let startTime = new Date().getTime(); cache.set('test', "Hello World Simple Example.");
cache.set('test', "Hello World Simple Example."); let path: string = cache.getFileToPath('test');
let path: string = '' expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
await cache.getFileToPathAsync('test').then((data) => { .assertTrue()
path = data expect(cache.getFileToPath('test') == path).assertTrue()
}) expect(cache.getPath() + cache.getCacheMap().getFirstKey() == path).assertTrue()
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.") endTime(startTime, 'testGetPath');
.assertTrue() cache.cleanCacheData();
expect(cache.getFileToPath('test') == path).assertTrue() })
expect(cache.getPath() + cache.getCacheMap().getFirstKey() == path).assertTrue() it('testGetCacheMap', 6, () => {
endTime(startTime, 'testGetPath'); let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
cache.cleanCacheData(); let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
} let startTime = new Date().getTime();
cache.set('test', "Hello World Simple Example.");
expect(cache.getCacheMap().getFirstKey() == '098f6bcd4621d373cade4e832627b4f6').assertTrue()
expect(cache.getCacheMap().hasKey('098f6bcd4621d373cade4e832627b4f6') == true).assertTrue()
endTime(startTime, 'testGetCacheMap');
cache.cleanCacheData();
}) })
it('testGetCacheMap', 6, async () => {
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext; it('testGetSize', 7, () => {
if (context != undefined) { let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let cache: DiskLruCache = DiskLruCache.create(context); let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime(); let startTime = new Date().getTime();
cache.set('test', "Hello World Simple Example."); cache.set('test', "Hello World Simple Example.");
expect(cache.getCacheMap().getFirstKey() == '098f6bcd4621d373cade4e832627b4f6').assertTrue() expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
expect(cache.getCacheMap().hasKey('098f6bcd4621d373cade4e832627b4f6') == true).assertTrue() .assertTrue()
endTime(startTime, 'testGetCacheMap'); expect(cache.getSize() == 27).assertTrue()
cache.cleanCacheData(); endTime(startTime, 'testGetSize');
} cache.cleanCacheData();
}) })
it('testGetSize', 7, async () => { it('testDiskCacheEntry', 8, () => {
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext;
if (context != undefined) {
let cache: DiskLruCache = DiskLruCache.create(context);
let startTime = new Date().getTime();
cache.set('test', "Hello World Simple Example.");
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
.assertTrue()
expect(cache.getSize() == 27).assertTrue()
endTime(startTime, 'testGetSize');
cache.cleanCacheData();
}
})
it('testDiskCacheEntry', 8, async () => {
let startTime = new Date().getTime(); let startTime = new Date().getTime();
let dentry = new DiskCacheEntry('test', 30 * 1024 * 1024) let dentry = new DiskCacheEntry('test', 30 * 1024 * 1024)
expect(dentry.getKey() == 'test').assertTrue() expect(dentry.getKey() == 'test').assertTrue()

View File

@ -0,0 +1,37 @@
/*
* The MIT License (MIT)
* Copyright (C) 2023 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*/
export class GlobalContext {
private constructor() {
}
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getInstance(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}

View File

@ -22,6 +22,7 @@ import {ImageKnife,ImageKnifeDrawFactory,ImageKnifeGlobal} from '@ohos/libraryim
import AbilityConstant from '@ohos.app.ability.AbilityConstant'; import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want'; import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base' import { BusinessError } from '@ohos.base'
import {GlobalContext } from './GlobalContext'
export default class TestAbility extends UIAbility { export default class TestAbility extends UIAbility {
onCreate(want: Want, param: AbilityConstant.LaunchParam) { onCreate(want: Want, param: AbilityConstant.LaunchParam) {
@ -33,6 +34,8 @@ export default class TestAbility extends UIAbility {
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
// 初始化xts的ImageKnife // 初始化xts的ImageKnife
ImageKnife.with(this.context.createModuleContext("entry_test")); ImageKnife.with(this.context.createModuleContext("entry_test"));
GlobalContext.getInstance().setObject("hapContext",this.context.createModuleContext("entry_test"));
GlobalContext.getInstance().setObject("filesDir",this.context.createModuleContext("entry_test").filesDir);
} }
onDestroy() { onDestroy() {

View File

@ -310,47 +310,24 @@ export class ImageKnife {
request.addHeaderMap(this.headerMap) request.addHeaderMap(this.headerMap)
} }
this.generateDataCacheKey(request)
// 首先执行占位图 解析任务 // 首先执行占位图 解析任务
if (request.placeholderSrc) { if (request.placeholderSrc) {
let loadKey = '';
if (typeof request.placeholderSrc == 'string') {
loadKey = request.placeholderSrc;
} else {
loadKey = JSON.stringify(request.placeholderSrc);
}
let size = JSON.stringify(request.size);
request.placeholderCacheKey = this.generateCacheKey(loadKey, size, request.dontAnimateFlag, request.signature)
this.taskpoolLoadResource(request, ResourceUsage.PLACEHOLDER); this.taskpoolLoadResource(request, ResourceUsage.PLACEHOLDER);
} }
// 其次执行重试占位图 解析任务 // 其次执行重试占位图 解析任务
if (request.retryholderSrc) { if (request.retryholderSrc) {
let loadKey = '';
if (typeof request.retryholderSrc == 'string') {
loadKey = request.retryholderSrc;
} else {
loadKey = JSON.stringify(request.retryholderSrc);
}
let size = JSON.stringify(request.size);
request.retryholderCacheKey = this.generateCacheKey(loadKey, size, request.dontAnimateFlag, request.signature)
this.taskpoolLoadResource(request, ResourceUsage.RETRYHODLER); this.taskpoolLoadResource(request, ResourceUsage.RETRYHODLER);
} }
// 最后解析错误占位图 // 最后解析错误占位图
if (request.errorholderSrc) { if (request.errorholderSrc) {
let loadKey = '';
if (typeof request.errorholderSrc == 'string') {
loadKey = request.errorholderSrc;
} else {
loadKey = JSON.stringify(request.errorholderSrc);
}
let size = JSON.stringify(request.size);
request.errorholderCacheKey = this.generateCacheKey(loadKey, size, request.dontAnimateFlag, request.signature)
this.taskpoolLoadResource(request, ResourceUsage.ERRORHOLDER); this.taskpoolLoadResource(request, ResourceUsage.ERRORHOLDER);
} }
return this.parseSource(request); return this.parseSource(request);
} }
loadResources(request: RequestOption) { generateDataCacheKey(request: RequestOption){
let factories: EngineKeyInterface; let factories: EngineKeyInterface;
let cacheKey: string; let cacheKey: string;
let transferKey: string; let transferKey: string;
@ -394,12 +371,36 @@ export class ImageKnife {
// 生成磁盘缓存源数据key 原始数据保存在磁盘 // 生成磁盘缓存源数据key 原始数据保存在磁盘
dataKey = factories.generateOriginalDiskCacheKey(loadKey, signature); dataKey = factories.generateOriginalDiskCacheKey(loadKey, signature);
if (request.placeholderSrc) {
let placeholderLoadKey = '';
if (typeof request.placeholderSrc == 'string') {
placeholderLoadKey = request.placeholderSrc;
} else {
placeholderLoadKey = JSON.stringify(request.placeholderSrc);
}
request.placeholderCacheKey = this.generateCacheKey(placeholderLoadKey, size, dontAnimateFlag, signature)
}
if (request.retryholderSrc) {
let retryholderLoadKey = '';
if (typeof request.retryholderSrc == 'string') {
retryholderLoadKey = request.retryholderSrc;
} else {
retryholderLoadKey = JSON.stringify(request.retryholderSrc);
}
request.retryholderCacheKey = this.generateCacheKey(retryholderLoadKey, size, dontAnimateFlag, signature)
}
if (request.errorholderSrc) {
let errorholderLoadKey = '';
if (typeof request.errorholderSrc == 'string') {
errorholderLoadKey = request.errorholderSrc;
} else {
errorholderLoadKey = JSON.stringify(request.errorholderSrc);
}
request.errorholderCacheKey = this.generateCacheKey(errorholderLoadKey, size, dontAnimateFlag, signature)
}
request.generateCacheKey = cacheKey; request.generateCacheKey = cacheKey;
request.generateResourceKey = transferKey; request.generateResourceKey = transferKey;
request.generateDataKey = dataKey; request.generateDataKey = dataKey;
this.loadCacheManager(request);
} }
private generateCacheKey(loadkey: string, size: string, dontAnimateFlag: boolean, signature?: ObjectKey) { private generateCacheKey(loadkey: string, size: string, dontAnimateFlag: boolean, signature?: ObjectKey) {
@ -528,40 +529,30 @@ export class ImageKnife {
//多线程请求加载资源 //多线程请求加载资源
private taskpoolLoadResource(request: RequestOption, usageType: ResourceUsage) { private taskpoolLoadResource(request: RequestOption, usageType: ResourceUsage) {
let mainCache = this.memoryCacheProxy.loadMemoryCache(request.generateCacheKey, request.isCacheable);
let placeholderCache = this.memoryCacheProxy.loadMemoryCache(request.placeholderCacheKey, true);
let retryholderCache = this.memoryCacheProxy.loadMemoryCache(request.retryholderCacheKey, true);
let errorholderCacheKey = this.memoryCacheProxy.loadMemoryCache(request.errorholderCacheKey, true);
if (usageType == "placeholder") { if (usageType == "placeholder" && placeholderCache && !mainCache && !retryholderCache && !errorholderCacheKey) {
// 先从内存中取值 LogUtil.info("imageknife load placeholder from MemoryCache")
let cache = this.memoryCacheProxy.loadMemoryCache(request.placeholderCacheKey, true); request.placeholderOnComplete(placeholderCache);
if (cache) { return;
LogUtil.info("imageknife load placeholder from MemoryCache") } else if (usageType == "retryholder" && retryholderCache && !mainCache && !errorholderCacheKey) {
request.placeholderOnComplete(cache); LogUtil.info("imageknife load retryholder from MemoryCache")
return; request.retryholderOnComplete(retryholderCache);
} return;
} else if (usageType == "retryholder") { } else if (usageType == "errorholder" && errorholderCacheKey && !mainCache) {
// 先从内存中取值 LogUtil.info("imageknife load errorholder from MemoryCache")
let cache = this.memoryCacheProxy.loadMemoryCache(request.retryholderCacheKey, true); request.errorholderOnComplete(errorholderCacheKey);
if (cache) { return;
LogUtil.info("imageknife load retryholder from MemoryCache") } else if (usageType == "main" && mainCache) {
request.retryholderOnComplete(cache); LogUtil.info("imageknife load mainsource from MemoryCache")
return; mainCache.waitSaveDisk = false;
} request.loadComplete(mainCache);
} else if (usageType == "errorholder") { return;
let cache = this.memoryCacheProxy.loadMemoryCache(request.errorholderCacheKey, true);
if (cache) {
LogUtil.info("imageknife load errorholder from MemoryCache")
request.errorholderOnComplete(cache);
return;
}
} else {
// 先从内存中取值
let cache = this.memoryCacheProxy.loadMemoryCache(request.generateCacheKey, request.isCacheable);
if (cache) {
LogUtil.info("imageknife load resource from MemoryCache")
cache.waitSaveDisk = false;
request.loadComplete(cache);
return;
}
} }
//图片变换方法无法直接传递到子线程,这里先把对象名和构造参数传递到子线程,然后在子线程中实例化变换方法 //图片变换方法无法直接传递到子线程,这里先把对象名和构造参数传递到子线程,然后在子线程中实例化变换方法
let transformations: string [][] = []; let transformations: string [][] = [];
if (usageType == ResourceUsage.MAIN) { if (usageType == ResourceUsage.MAIN) {
@ -670,14 +661,14 @@ export class ImageKnife {
request.loadComplete(imageKnifeData); request.loadComplete(imageKnifeData);
} else if (typeof request.loadSrc == 'string') { } else if (typeof request.loadSrc == 'string') {
// 进入三级缓存模型 // 进入三级缓存模型
return this.loadResources(request); return this.loadCacheManager(request);
} else { } else {
let res = request.loadSrc as Resource; let res = request.loadSrc as Resource;
if (typeof res.id != 'undefined' && typeof res.type != 'undefined') { if (typeof res.id != 'undefined' && typeof res.type != 'undefined') {
// 进入三级缓存模型 本地资源不参与磁盘缓存 // 进入三级缓存模型 本地资源不参与磁盘缓存
let none = new NONE(); let none = new NONE();
request.diskCacheStrategy(none); request.diskCacheStrategy(none);
this.loadResources(request); this.loadCacheManager(request);
} else { } else {
LogUtil.error("输入参数有问题!") LogUtil.error("输入参数有问题!")
} }
@ -696,63 +687,63 @@ export class ImageKnife {
async function taskExecute(taskParams: string, headers: Map<string, Object>, moduleContext: common.UIAbilityContext): Promise<PixelMap | GIFFrame[]> { async function taskExecute(taskParams: string, headers: Map<string, Object>, moduleContext: common.UIAbilityContext): Promise<PixelMap | GIFFrame[]> {
// try { // try {
let params: object = JSON.parse(taskParams); let params: object = JSON.parse(taskParams);
let option = params["request"] as RequestOption; let option = params["request"] as RequestOption;
let transformations = params["transformations"] as string [][]; let transformations = params["transformations"] as string [][];
let usageType = params["usageType"] as string; let usageType = params["usageType"] as string;
//子线程构造RequestOption对象 //子线程构造RequestOption对象
let newRequestOption = new RequestOption(); let newRequestOption = new RequestOption();
newRequestOption.uuid = option.uuid; newRequestOption.uuid = option.uuid;
newRequestOption.loadSrc = option.loadSrc; newRequestOption.loadSrc = option.loadSrc;
newRequestOption.dontAnimateFlag = option.dontAnimateFlag; newRequestOption.dontAnimateFlag = option.dontAnimateFlag;
newRequestOption.generateCacheKey = option.generateCacheKey; newRequestOption.generateCacheKey = option.generateCacheKey;
newRequestOption.generateResourceKey = option.generateResourceKey; newRequestOption.generateResourceKey = option.generateResourceKey;
newRequestOption.generateDataKey = option.generateDataKey; newRequestOption.generateDataKey = option.generateDataKey;
newRequestOption.thumbSizeMultiplier = option.thumbSizeMultiplier; newRequestOption.thumbSizeMultiplier = option.thumbSizeMultiplier;
newRequestOption.thumbDelayTime = option.thumbDelayTime; newRequestOption.thumbDelayTime = option.thumbDelayTime;
newRequestOption.size = option.size; newRequestOption.size = option.size;
newRequestOption.placeholderSrc = option.placeholderSrc; newRequestOption.placeholderSrc = option.placeholderSrc;
newRequestOption.errorholderSrc = option.errorholderSrc; newRequestOption.errorholderSrc = option.errorholderSrc;
newRequestOption.retryholderSrc = option.retryholderSrc; newRequestOption.retryholderSrc = option.retryholderSrc;
newRequestOption.onlyRetrieveFromCache = option.onlyRetrieveFromCache; newRequestOption.onlyRetrieveFromCache = option.onlyRetrieveFromCache;
newRequestOption.gpuEnabled = option.gpuEnabled; newRequestOption.gpuEnabled = option.gpuEnabled;
newRequestOption.headers = headers; newRequestOption.headers = headers;
newRequestOption.signature = option.signature; newRequestOption.signature = option.signature;
ImageKnifeGlobal.getInstance().setHapContext(moduleContext); ImageKnifeGlobal.getInstance().setHapContext(moduleContext);
newRequestOption.moduleContext = moduleContext; newRequestOption.moduleContext = moduleContext;
if (option.isCacheable != null && option.isCacheable != undefined) { if (option.isCacheable != null && option.isCacheable != undefined) {
newRequestOption.isCacheable = option.isCacheable; newRequestOption.isCacheable = option.isCacheable;
} }
//如果是本地图片不作磁盘缓存 //如果是本地图片不作磁盘缓存
if (typeof option.loadSrc !== 'string') { if (typeof option.loadSrc !== 'string') {
let none = new NONE(); let none = new NONE();
newRequestOption.diskCacheStrategy(none); newRequestOption.diskCacheStrategy(none);
} }
if (usageType == "placeholder") { if (usageType == "placeholder") {
let manager = new PlaceHolderManager<PixelMap>(newRequestOption); let manager = new PlaceHolderManager<PixelMap>(newRequestOption);
return await new Promise<PixelMap>(manager.process); return await new Promise<PixelMap>(manager.process);
} else if (usageType == "retryholder") { } else if (usageType == "retryholder") {
let manager = new RetryHolderManager<PixelMap>(newRequestOption); let manager = new RetryHolderManager<PixelMap>(newRequestOption);
return await new Promise<PixelMap>(manager.process); return await new Promise<PixelMap>(manager.process);
} else if (usageType == "errorholder") { } else if (usageType == "errorholder") {
let manager = new ErrorHolderManager<PixelMap>(newRequestOption); let manager = new ErrorHolderManager<PixelMap>(newRequestOption);
return await new Promise<PixelMap>(manager.process); return await new Promise<PixelMap>(manager.process);
} else { } else {
if (transformations) { if (transformations) {
for (let i = 0; i < transformations.length; i++) { for (let i = 0; i < transformations.length; i++) {
let className = transformations[i][0] as string; let className = transformations[i][0] as string;
let params = transformations[i][1] as string; let params = transformations[i][1] as string;
newRequestOption.addTransformations(className, params); newRequestOption.addTransformations(className, params);
}
} }
let newDataFetch = new DownloadClient();
let newResourceFetch = new ParseResClient();
let manager = new RequestManager(newRequestOption, newDataFetch, newResourceFetch);
return await new Promise<PixelMap | GIFFrame[]>(manager.process);
} }
let newDataFetch = new DownloadClient();
let newResourceFetch = new ParseResClient();
let manager = new RequestManager(newRequestOption, newDataFetch, newResourceFetch);
return await new Promise<PixelMap | GIFFrame[]>(manager.process);
}
// } catch (e) { // } catch (e) {
// console.log(e) // console.log(e)
// return await new Promise<PixelMap | GIFFrame[]>(() => { // return await new Promise<PixelMap | GIFFrame[]>(() => {

View File

@ -811,7 +811,7 @@ export struct ImageKnifeComponent {
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, pixelmap, px2vp(frameW), px2vp(frameH), compWidth, compHeight, px2vp(frame.dims.left), px2vp(frame.dims.top)) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, pixelmap, px2vp(frameW), px2vp(frameH), compWidth, compHeight, px2vp(frame.dims.left), px2vp(frame.dims.top))
// tips:worker如果不是在展示页面中创建,使用子线程回来的数据创建的图片,会导致canvas绘制不出来 // tips:worker如果不是在展示页面中创建,使用子线程回来的数据创建的图片,会导致canvas绘制不出来
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawMainSource end!') LogUtil.log('ImageKnifeComponent canvasDrawPixelMap end!')
} }
} }

View File

@ -92,7 +92,6 @@ export class RequestOption {
errorholderSrc: PixelMap | Resource | undefined = undefined; errorholderSrc: PixelMap | Resource | undefined = undefined;
errorholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined; errorholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
errorholderData: ImageKnifeData | undefined = undefined; errorholderData: ImageKnifeData | undefined = undefined;
;
thumbSizeMultiplier: number = 0; thumbSizeMultiplier: number = 0;
// 如果存在缩略图则主图延时1s加载 // 如果存在缩略图则主图延时1s加载
thumbDelayTime: number = 1000 thumbDelayTime: number = 1000
@ -528,7 +527,7 @@ export class RequestOption {
retryholderOnError = (error: BusinessError | string) => { retryholderOnError = (error: BusinessError | string) => {
LogUtil.log("重试占位图解析失败 error =" + error) LogUtil.log("重试占位图解析失败 error =" + error)
} }
loadComplete = async (imageKnifeData: ImageKnifeData) => { loadComplete = (imageKnifeData: ImageKnifeData) => {
this.setMemoryCache(imageKnifeData,this.generateCacheKey); this.setMemoryCache(imageKnifeData,this.generateCacheKey);
if (typeof this.loadSrc == 'string') { if (typeof this.loadSrc == 'string') {
this.setDiskCache(); this.setDiskCache();

View File

@ -24,7 +24,6 @@ export class ParseImageUtil implements IParseImage<PixelMap> {
this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction) this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction)
} }
// scale(0,1)
parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void) { parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void) {
let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一文件转为pixelMap 然后变换 给Image组件 let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一文件转为pixelMap 然后变换 给Image组件
@ -52,41 +51,5 @@ export class ParseImageUtil implements IParseImage<PixelMap> {
onErrorFunction(err); onErrorFunction(err);
imageSource.release() imageSource.release()
}) })
// taskPoolExecutePixelMap(imageinfo,scale,onCompleteFunction,onErrorFunction); //多线程接口
} }
}
@Concurrent
async function taskParseImage(arrayBuffer: ArrayBuffer, scale: number): Promise<PixelMap> {
let imageSource: image.ImageSource = image.createImageSource(arrayBuffer); // 步骤一文件转为pixelMap 然后变换 给Image组件
let value = await imageSource.getImageInfo();
let hValue = Math.round(value.size.height * scale);
let wValue = Math.round(value.size.width * scale);
let defaultSize: image.Size = {
height: hValue,
width: wValue
};
let opts: image.DecodingOptions = {
editable: true,
desiredSize: defaultSize
};
let pixelMap = await imageSource.createPixelMap(opts)
LogUtil.log("ceshi321 : Succeeded in creating pixelmap taskpool " + pixelMap.getPixelBytesNumber())
imageSource.release()
return pixelMap;
}
function taskPoolExecutePixelMap(arrayBuffer: ArrayBuffer, scale: number, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void) {
LogUtil.log("ceshi321 : arrayBuffer长度" + arrayBuffer.byteLength);
let task = new taskpool.Task(taskParseImage, arrayBuffer, scale);
task.setTransferList([]);
taskpool.execute(task).then((pixelmap: Object) => {
LogUtil.log('ceshi321 : Succeeded in creating pixelmap Ui .' + (pixelmap as image.PixelMap).getPixelBytesNumber())
onCompleteFunction(pixelmap as image.PixelMap);
}).catch((err: string) => {
LogUtil.log("ceshi321 : test occur error: " + err);
onErrorFunction(err);
});
} }

View File

@ -75,49 +75,5 @@ export class GIFParseImpl implements IParseGif {
imageSource.release(); imageSource.release();
callback(undefined,err) callback(undefined,err)
}) })
//taskPoolExecutePixelMapList(imageinfo,callback); //多线程接口
} }
}
@Concurrent
async function taskParseGif(arrayBuffer: ArrayBuffer): Promise<GIFFrame[]> {
let imageSource = image.createImageSource(arrayBuffer);
let data: GIFFrame[] = [];
let decodeOpts: image.DecodingOptions = {
sampleSize: 1,
editable: true,
rotate: 0
}
let pixelList = await imageSource.createPixelMapList(decodeOpts);
if (pixelList.length > 0) {
let pixelmap = pixelList[0];
let imageInfo = await pixelmap.getImageInfo();
let delayTimes = await imageSource.getDelayTimeList();
for (let i = 0; i < pixelList.length; i++) {
let frame = new GIFFrame();
frame.drawPixelMap = pixelList[i];
frame.dims = { width: imageInfo.size.width, height: imageInfo.size.height, top: 0, left: 0 }
if (i < delayTimes.length) {
frame.delay = delayTimes[i];
} else {
frame.delay = delayTimes[delayTimes.length - 1]
}
data.push(frame)
}
}
return data;
}
function taskPoolExecutePixelMapList(arrayBuffer: ArrayBuffer, callback: (data?: GIFFrame[], err?: BusinessError | string) => void) {
LogUtil.log("ceshi321 : arrayBuffer长度" + arrayBuffer.byteLength)
let task = new taskpool.Task(taskParseGif, arrayBuffer)
task.setTransferList([])
taskpool.execute(task).then((imageFrames: Object) => {
// LogUtil.log('ceshi321 : Succeeded in creating pixelmap Ui .' + imageFrames.getPixelBytesNumber())
callback(imageFrames as GIFFrame[],undefined)
}).catch((err: string) => {
LogUtil.log("ceshi321 : test occur error: " + err)
callback(undefined,err);
});
} }