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 {
private data: TestDataSource = new TestDataSource();
private setting: DiskStrategy = new NONE();
private scroller: Scroller = new Scroller()
build() {
Scroll() {
Column() {
Grid() {
Grid(this.scroller) {
LazyForEach(this.data, (item: Material, index) => {
GridItem() {
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: item.thumbnail,
placeholderSrc: $r('app.media.icon_loading'),
mainScaleType: ScaleType.CENTER_CROP,
placeholderScaleType: ScaleType.CENTER_CROP,
isCacheable: false,
// strategy: this.setting
if(index < 100) {
GridItem() {
Stack({ alignContent: Alignment.BottomEnd }) {
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: item.thumbnail,
placeholderSrc: $r('app.media.icon_loading'),
mainScaleType: ScaleType.CENTER_CROP,
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)
}, (item: string) => JSON.stringify(item))
}.width('45%').height(200)
}
}, (item: Material) => item.material_id)
}
.columnsTemplate('1fr 1fr')
.columnsGap(8)
.maxCount(8)
.rowsGap(10)
.width('100%')
.hitTestBehavior(HitTestMode.None)
.maxCount(10)
.cachedCount(5)
.cachedCount(3)
}.margin({ top: 5 })
}
}

View File

@ -12,12 +12,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Hypium } from '@ohos/hypium'
import { DiskLruCache, ImageKnifeGlobal, ImageKnife, DiskCacheEntry } from '@ohos/imageknife'
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
import { AbilityConstant, common, UIAbility, Want } from '@kit.AbilityKit';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import { DiskLruCache, DiskCacheEntry } from '@ohos/imageknife'
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { GlobalContext } from '../testability/GlobalContext'
const BASE_COUNT: number = 2000;
@ -26,6 +25,7 @@ export default function DiskLruCacheTest() {
describe('DiskLruCacheTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
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.
// 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.
})
it('testSetCahe', 0, () => {
let context: Object | undefined = ImageKnifeGlobal.getInstance().getHapContext();
if (context != undefined) {
let disLruCache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime();
disLruCache.set('test', "Hello World Simple Example.");
disLruCache.set('testABC', "Hello World ABC");
disLruCache.set('testDE', "Hello World Simple DE");
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
.assertTrue()
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testABC') as ArrayBufferLike)) == "Hello World ABC")
.assertTrue()
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testDE') as ArrayBufferLike)) == "Hello World Simple DE")
.assertTrue()
let str: string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
for (let index = 0; index < 100; index++) {
str += index;
disLruCache.set('test' + index, str);
}
expect(disLruCache.getSize() <= 1024).assertTrue()
endTime(startTime, 'testSetCahe');
disLruCache.cleanCacheData();
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let disLruCache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime();
disLruCache.set('test', "Hello World Simple Example.");
disLruCache.set('testABC', "Hello World ABC");
disLruCache.set('testDE', "Hello World Simple DE");
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
.assertTrue()
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testABC') as ArrayBufferLike)) == "Hello World ABC")
.assertTrue()
expect(String.fromCharCode(...new Uint8Array(disLruCache.get('testDE') as ArrayBufferLike)) == "Hello World Simple DE")
.assertTrue()
let str: string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
for (let index = 0; index < 100; index++) {
str += index;
disLruCache.set('test' + index, str);
}
expect(disLruCache.getSize() <= 1024).assertTrue()
endTime(startTime, 'testSetCahe');
disLruCache.cleanCacheData();
})
it('testGetCacheAsync', 1, () => {
let context: common.UIAbilityContext = ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext;
if (context != undefined) {
let data = context.filesDir
let cache: DiskLruCache = DiskLruCache.create(context);
let startTime = new Date().getTime();
let path = data + '/testFile.txt';
let file = fs.openSync(path, 0o102);
fs.writeSync(file.fd, "hello, world!");
let length = fs.statSync(path).size;
let dataArr = new ArrayBuffer(length);
fs.readSync(file.fd, dataArr);
cache.set('testFile', dataArr);
expect(cache.get('testFile')?.byteLength == 13).assertTrue()
endTime(startTime, 'testGetCacheAsync');
cache.cleanCacheData();
}
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let filesDir: object | undefined = GlobalContext.getInstance().getObject("filesDir");
let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime();
let path = filesDir + '/testFile.txt';
let file = fs.openSync(path, 0o102);
fs.writeSync(file.fd, "hello, world!");
let length = fs.statSync(path).size;
let dataArr = new ArrayBuffer(length);
fs.readSync(file.fd, dataArr);
cache.set('testFile', dataArr);
expect(cache.get('testFile')?.byteLength == 13).assertTrue()
endTime(startTime, 'testGetCacheAsync');
cache.cleanCacheData();
})
it('testDeleteCacheDataByKey', 2, () => {
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.");
cache.set('testABC', "Hello World ABC");
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)))
.assertEqual("Hello World Simple Example.");
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike)))
.assertEqual("Hello World ABC");
cache.deleteCacheDataByKey('test');
cache.deleteCacheDataByKey('testABC');
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike))).assertEqual('');
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike))).assertEqual('');
endTime(startTime, 'testDeleteCacheDataByKey');
cache.cleanCacheData();
}
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime();
cache.set('test', "Hello World Simple Example.");
cache.set('testABC', "Hello World ABC");
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)))
.assertEqual("Hello World Simple Example.");
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike)))
.assertEqual("Hello World ABC");
cache.deleteCacheDataByKey('test');
cache.deleteCacheDataByKey('testABC');
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike))).assertEqual('');
expect(String.fromCharCode(...new Uint8Array(cache.get('testABC') as ArrayBufferLike))).assertEqual('');
endTime(startTime, 'testDeleteCacheDataByKey');
cache.cleanCacheData();
})
it('testGetPath', 3, async () => {
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.");
let path: string = ''
await cache.getFileToPathAsync('test').then((data) => {
path = data
})
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
.assertTrue()
expect(cache.getFileToPath('test') == path).assertTrue()
expect(cache.getPath() + cache.getCacheMap().getFirstKey() == path).assertTrue()
endTime(startTime, 'testGetPath');
cache.cleanCacheData();
}
it('testGetPath', 3, () => {
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
let startTime = new Date().getTime();
cache.set('test', "Hello World Simple Example.");
let path: string = cache.getFileToPath('test');
expect(String.fromCharCode(...new Uint8Array(cache.get('test') as ArrayBufferLike)) == "Hello World Simple Example.")
.assertTrue()
expect(cache.getFileToPath('test') == path).assertTrue()
expect(cache.getPath() + cache.getCacheMap().getFirstKey() == path).assertTrue()
endTime(startTime, 'testGetPath');
cache.cleanCacheData();
})
it('testGetCacheMap', 6, () => {
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
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;
if (context != undefined) {
let cache: DiskLruCache = DiskLruCache.create(context);
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('testGetSize', 7, () => {
let context: object | undefined = GlobalContext.getInstance().getObject("hapContext");
let cache: DiskLruCache = DiskLruCache.create(context as common.UIAbilityContext, 1024);
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('testGetSize', 7, async () => {
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 () => {
it('testDiskCacheEntry', 8, () => {
let startTime = new Date().getTime();
let dentry = new DiskCacheEntry('test', 30 * 1024 * 1024)
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 Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base'
import {GlobalContext } from './GlobalContext'
export default class TestAbility extends UIAbility {
onCreate(want: Want, param: AbilityConstant.LaunchParam) {
@ -33,6 +34,8 @@ export default class TestAbility extends UIAbility {
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
// 初始化xts的ImageKnife
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() {

View File

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

View File

@ -24,7 +24,6 @@ export class ParseImageUtil implements IParseImage<PixelMap> {
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) {
let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一文件转为pixelMap 然后变换 给Image组件
@ -52,41 +51,5 @@ export class ParseImageUtil implements IParseImage<PixelMap> {
onErrorFunction(err);
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();
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);
});
}