!55 ArkTs语法整改

Merge pull request !55 from 周黎生/master
This commit is contained in:
openharmony_ci 2023-09-26 09:02:03 +00:00 committed by Gitee
commit 660e4d0052
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
134 changed files with 2834 additions and 2860 deletions

View File

@ -1,3 +1,17 @@
## 2.1.0
- ArkTs语法整改:
globalThis.ImageKnife方式已经不可使用
提供了ImageKnifeGlobal对象单例全局可访问
访问ImageKnife对象需要使用ImageKnifeGlobal.getInstance().getImageKnife()
- 裁剪组件暴露PixelMapCrop组件和配置类Options, 配置类Options不再需要声明PixelMapCrop.Options中的PixelMapCrop命名空间
- 适配DevEco Studio 版本4.0(4.0.3.512), SDK: API10 (4.0.10.9)
## 2.0.5-rc.0 ## 2.0.5-rc.0
- 修复若干问题: - 修复若干问题:

View File

@ -37,7 +37,7 @@ ohpm install @ohos/imageknife
"author": "", "author": "",
"license": "", "license": "",
"dependencies": { "dependencies": {
"@ohos/imageknife": "^2.0.2" "@ohos/imageknife": "^2.0.6"
} }
} }
``` ```
@ -53,8 +53,9 @@ export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) { onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', (err, data) => { windowStage.loadContent('pages/Index', (err, data) => {
}); });
//初始化全局ImageKnife // 初始化全局ImageKnife
globalThis.ImageKnife = ImageKnife.with(this.context); ImageKnife.with(this.context);
// 后续访问ImageKnife请通过:ImageKnifeGlobal.getInstance().getImageKnife()方式
} }
} }
``` ```
@ -109,13 +110,13 @@ GIF图片即可。
```extendtypescript ```extendtypescript
import router from '@ohos.router' import router from '@ohos.router'
import { ImageKnifeComponent, ImageKnifeOption, } from '@ohos/imageknife' import { ImageKnifeComponent, ImageKnifeOption,ImageKnife } from '@ohos/imageknife'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
@Entry @Entry
@Component @Component
struct IndexFunctionDemo { struct IndexFunctionDemo {
private globalGifWorker: any = undefined private globalGifWorker?:worker.ThreadWorker = undefined;
@State imageKnifeOption1: ImageKnifeOption = { @State imageKnifeOption1: ImageKnifeOption = {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
@ -174,9 +175,15 @@ struct IndexFunctionDemo {
} }
aboutToAppear() { aboutToAppear() {
this.globalGifWorker = new worker.ThreadWorker('entry/ets/workers/GifLoadWorker.ts') this.globalGifWorker = new worker.ThreadWorker('entry/ets/workers/GifLoadWorker.ts', {
type: 'classic',
name: 'ImageKnifeParseGIF'
})
// gif解析在子线程,请在页面构建后创建worker,注入imageknife // gif解析在子线程,请在页面构建后创建worker,注入imageknife
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear() { aboutToDisappear() {
@ -322,17 +329,20 @@ svg返回的都是PixelMapgif返回GIFFrame数组我们返回了true。
当进行加载网络图片时,可能需要展示网络下载百分比动画。但是默认的动画又不能满足需求,这个时候我们就需要自定义网络下载百分比效果。代码如下: 当进行加载网络图片时,可能需要展示网络下载百分比动画。但是默认的动画又不能满足需求,这个时候我们就需要自定义网络下载百分比效果。代码如下:
```typescript ```typescript
import AbilityStage from '@ohos.application.AbilityStage' import UIAbility from '@ohos.app.ability.UIAbility';
import { ImageKnife, ImageKnifeDrawFactory } from '@ohos/imageknife' import window from '@ohos.window';
import { ImageKnifeGlobal,ImageKnife,ImageKnifeDrawFactory,LogUtil } from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import abilityAccessCtrl,{Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility {
export default class MyAbilityStage extends AbilityStage { onWindowStageCreate(windowStage: window.WindowStage) {
onCreate() { //.. 删除不必要代码
globalThis.ImageKnife = ImageKnife.with(this.context); windowStage.loadContent('pages/index', (err, data) => {
// 全局配置网络加载进度条 });
globalThis.ImageKnife.setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5)) // 初始化ImageKnifeGlobal和ImageKnife
} ImageKnife.with(this.context);
// 全局配置网络加载进度条 使用ImageKnifeGlobal.getInstance().getImageKnife()访问ImageKnife
ImageKnifeGlobal.getInstance().getImageKnife().setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
}
} }
``` ```
@ -363,7 +373,7 @@ export default class MyAbilityStage extends AbilityStage {
了解了RequestOption的参数内容后我们可以参考ImageKnifeComponent组件代码进行分析。 了解了RequestOption的参数内容后我们可以参考ImageKnifeComponent组件代码进行分析。
**从`imageKnifeExecute()`函数入口首先我们需要构建一个RequestOption对象`let request = new RequestOption()`, **从`imageKnifeExecute()`函数入口首先我们需要构建一个RequestOption对象`let request = new RequestOption()`,
接下来就是按需配置request对象的内容最后使用 `globalThis.ImageKnife.call(request)`发送request执行任务即可。** 接下来就是按需配置request对象的内容最后使用 `ImageKnifeGlobal.getInstance().getImageKnife()?.call(request)`发送request执行任务即可。**
是不是很简单,而其实最重要的内容是就是: **按需配置request对象的内容** 为了更好理解,我举例说明一下: 是不是很简单,而其实最重要的内容是就是: **按需配置request对象的内容** 为了更好理解,我举例说明一下:
@ -374,7 +384,7 @@ let request = new RequestOption();
// (必传) // (必传)
request.load("图片url") request.load("图片url")
// (可选 整个request监听回调) // (可选 整个request监听回调)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
// data 是ImageKnifeData对象 // data 是ImageKnifeData对象
if(data.isPixelMap()){ if(data.isPixelMap()){
// 这样就获取到了目标PixelMap // 这样就获取到了目标PixelMap
@ -383,14 +393,18 @@ request.load("图片url")
return false; return false;
}) })
let compSize = { let compSize:Size = {
width: this.currentWidth, width: this.currentWidth,
height:this.currentHeight height:this.currentHeight
} }
// (必传)这里setImageViewSize函数必传组件大小因为涉及到图片变换效果都需要适配图像源和组件大小 // (必传)这里setImageViewSize函数必传组件大小因为涉及到图片变换效果都需要适配图像源和组件大小
request.setImageViewSize(compSize) request.setImageViewSize(compSize)
// 最后使用ImageKnife的call函数调用request即可 // 最后使用ImageKnife的call函数调用request即可
globalThis.ImageKnife.call(request) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife();
if(imageKnife != undefined){
imageKnife.call(request)
}
``` ```
**其他场景,可以按需加载** **其他场景,可以按需加载**

View File

@ -1,14 +1,21 @@
{ {
"app": { "app": {
"compileSdkVersion": 9,
"compatibleSdkVersion": 9,
"products": [ "products": [
{ {
"name": "default", "name": "default",
"signingConfig": "default" "signingConfig": "default",
"compileSdkVersion": 10,
"compatibleSdkVersion": 10
} }
], ],
"signingConfigs": [] "buildModeSet":[
{
"name":"debug"
},
{
"name":"release"
}
]
}, },
"modules": [ "modules": [
{ {

View File

@ -19,7 +19,7 @@ export class CustomEngineKeyImpl implements EngineKeyInterface {
addOtherInfo: string = "Version=1.0.0;" addOtherInfo: string = "Version=1.0.0;"
constructor() { constructor() {
this.redefineUrl = this.urlNeedClearToken.bind(this); this.redefineUrl = this.urlNeedClearToken;
} }
// request只读 // request只读
generateMemoryCacheKey(loadSrc: string, size: string, transformed: string, dontAnimate: boolean): string { generateMemoryCacheKey(loadSrc: string, size: string, transformed: string, dontAnimate: boolean): string {
@ -36,7 +36,7 @@ export class CustomEngineKeyImpl implements EngineKeyInterface {
// 需求场景: 请求图片可能 请求中存在token需要清除 可以把输入的url清除token后作为key的一部分这样token发生变化也能命中缓存。 // 需求场景: 请求图片可能 请求中存在token需要清除 可以把输入的url清除token后作为key的一部分这样token发生变化也能命中缓存。
urlNeedClearToken(url: string): string { urlNeedClearToken = (url: string)=>{
if (this.isHttpRequest(url)) { if (this.isHttpRequest(url)) {
return this.clearToken(url) return this.clearToken(url)
} else { } else {

View File

@ -15,7 +15,7 @@
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
import window from '@ohos.window'; import window from '@ohos.window';
import { ImageKnife,ImageKnifeDrawFactory,LogUtil } from '@ohos/imageknife' import { ImageKnifeGlobal,ImageKnife,ImageKnifeDrawFactory,LogUtil } from '@ohos/imageknife'
import { CustomEngineKeyImpl } from './CustomEngineKeyImpl' import { CustomEngineKeyImpl } from './CustomEngineKeyImpl'
import abilityAccessCtrl,{Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl,{Permissions} from '@ohos.abilityAccessCtrl';
@ -45,11 +45,11 @@ export default class EntryAbility extends UIAbility {
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
}); });
globalThis.ImageKnife = ImageKnife.with(this.context); ImageKnife.with(this.context);
// 全局配置网络加载进度条 // 全局配置网络加载进度条
globalThis.ImageKnife.setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5)) ImageKnifeGlobal.getInstance().getImageKnife().setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
// 全局配置缓存key // 全局配置缓存key
globalThis.ImageKnife.setEngineKeyImpl(new CustomEngineKeyImpl()) ImageKnifeGlobal.getInstance().getImageKnife().setEngineKeyImpl(new CustomEngineKeyImpl())
//开启ImageKnife所有级别日志开关 //开启ImageKnife所有级别日志开关
LogUtil.mLogLevel = LogUtil.ALL LogUtil.mLogLevel = LogUtil.ALL
} }

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { ImageKnifeComponent, ImageKnifeOption,NONE } from '@ohos/imageknife' import { ImageKnifeComponent, ImageKnifeOption,NONE,DiskStrategy } from '@ohos/imageknife'
@Entry @Entry
@Component @Component
@ -39,13 +39,14 @@ struct OptionTestPage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("加载") Button("加载")
.onClick(() => { .onClick(() => {
let setting:DiskStrategy = new NONE();
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: 'https://img-blog.csdn.net/20140514114029140', loadSrc: 'https://img-blog.csdn.net/20140514114029140',
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
onlyRetrieveFromCache: false, onlyRetrieveFromCache: false,
isCacheable: false, isCacheable: false,
strategy: new NONE() strategy: setting
} }
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300)
@ -55,13 +56,14 @@ struct OptionTestPage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("加载") Button("加载")
.onClick(() => { .onClick(() => {
let setting2:DiskStrategy = new NONE();
this.imageKnifeOption2 = { this.imageKnifeOption2 = {
loadSrc: 'https://img-blog.csdn.net/20140514114029140', loadSrc: 'https://img-blog.csdn.net/20140514114029140',
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
onlyRetrieveFromCache: true, onlyRetrieveFromCache: true,
isCacheable: true, isCacheable: true,
strategy: new NONE() strategy: setting2
} }
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption2 }).width(300).height(300) ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption2 }).width(300).height(300)

View File

@ -22,7 +22,7 @@ struct BasicTestFeatureAbilityPage {
watchPathChange() { watchPathChange() {
console.log("watchPathChange") console.log("watchPathChange")
} }
urls=[ urls:string[]=[
"http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
"http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg", "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
"http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg", "http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
@ -45,10 +45,10 @@ struct BasicTestFeatureAbilityPage {
"http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg", "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
] ]
@State options:Array<ImageKnifeOption> = [] @State options:Array<ImageKnifeOption> = new Array
aboutToAppear(){ aboutToAppear(){
this.options = this.urls.map((url)=>{ this.options = this.urls.map<ImageKnifeOption>((url:string)=>{
return { return {
loadSrc:url loadSrc:url
} }
@ -60,11 +60,11 @@ struct BasicTestFeatureAbilityPage {
Stack({ alignContent: Alignment.TopStart }) { Stack({ alignContent: Alignment.TopStart }) {
Column() { Column() {
List({ space: 20, initialIndex: 0 }) { List({ space: 20, initialIndex: 0 }) {
ForEach(this.options, (item) => { ForEach(this.options, (item:ImageKnifeOption) => {
ListItem() { ListItem() {
ImageKnifeComponent({imageKnifeOption:item}).width(300).height(300) ImageKnifeComponent({imageKnifeOption:item}).width(300).height(300)
} }
}, item => item.loadSrc) }, (item:ImageKnifeOption )=> item.loadSrc as string)
} }
.listDirection(Axis.Vertical) // 排列方向 .listDirection(Axis.Vertical) // 排列方向
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线 .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线

View File

@ -13,9 +13,10 @@
* limitations under the License. * limitations under the License.
*/ */
import { FileUtils } from '@ohos/imageknife' import { FileUtils, ImageKnifeGlobal} from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct basicTestFileIOPage { struct basicTestFileIOPage {
@ -25,7 +26,7 @@ struct basicTestFileIOPage {
@State imageHint: string = '' @State imageHint: string = ''
@State imageFile: string = '文字提醒' @State imageFile: string = '文字提醒'
@State imageRes: Resource = $r('app.media.pngSample') @State imageRes: Resource = $r('app.media.pngSample')
@State imagePixelMap: PixelMap = undefined @State imagePixelMap?: PixelMap = undefined
@State normalPixelMap: boolean = false; @State normalPixelMap: boolean = false;
@State normalResource: boolean = false; @State normalResource: boolean = false;
@ -41,7 +42,7 @@ struct basicTestFileIOPage {
.margin({ top: 10 }) .margin({ top: 10 })
.onClick(() => { .onClick(() => {
let data = globalThis.ImageKnife.getImageKnifeContext().filesDir; let data:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
console.log('ImageKnife filesPath = ' + data) console.log('ImageKnife filesPath = ' + data)
this.filePath = data this.filePath = data
this.appFilePath = data; this.appFilePath = data;
@ -51,7 +52,7 @@ struct basicTestFileIOPage {
.margin({ top: 10 }) .margin({ top: 10 })
.onClick(() => { .onClick(() => {
let data = globalThis.ImageKnife.getImageKnifeContext().cacheDir; let data:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).cacheDir as string;
console.log('ImageKnife cachesPath = ' + data) console.log('ImageKnife cachesPath = ' + data)
this.filePath = data this.filePath = data
this.appFilePath = data; this.appFilePath = data;
@ -79,8 +80,8 @@ struct basicTestFileIOPage {
this.appFilePath = 'appFilePath未取到值,请按顺序从上往下,从左往右依次测试' this.appFilePath = 'appFilePath未取到值,请按顺序从上往下,从左往右依次测试'
return return
} }
globalThis.ImageKnife.getImageKnifeContext().resourceManager ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMedia($r('app.media.gifSample').id) .getMediaContent($r('app.media.gifSample').id)
.then(data => { .then(data => {
console.log('result.getMedia') console.log('result.getMedia')
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength)
@ -89,8 +90,8 @@ struct basicTestFileIOPage {
this.imageFile = 'file://' + this.appFilePath + '/Folder1/jpgSample.gif' this.imageFile = 'file://' + this.appFilePath + '/Folder1/jpgSample.gif'
console.log('Folder1 imaeFile =' + this.imageFile) console.log('Folder1 imaeFile =' + this.imageFile)
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err as BusinessError));
}) })
}) })
Button('copy:Folder1至Folder2 验证copyFileSync') Button('copy:Folder1至Folder2 验证copyFileSync')

View File

@ -18,11 +18,13 @@ import { FileTypeUtil } from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import { Base64 } from '@ohos/imageknife' import { Base64 } from '@ohos/imageknife'
import { ParseImageUtil } from '@ohos/imageknife' import { ParseImageUtil } from '@ohos/imageknife'
import { ImageKnifeGlobal } from '@ohos/imageknife'
import { BusinessError } from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct BasicTestMediaImage { struct BasicTestMediaImage {
@State imagePixelMap: PixelMap = undefined; @State imagePixelMap?: PixelMap = undefined;
build() { build() {
Scroll() { Scroll() {
@ -30,76 +32,81 @@ struct BasicTestMediaImage {
Flex({ direction: FlexDirection.Row }) { Flex({ direction: FlexDirection.Row }) {
Button('本地资源jpg') Button('本地资源jpg')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.jpgSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.jpgSample').id)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil(); let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => { parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
this.imagePixelMap = pxielmap; this.imagePixelMap = pxielmap;
}, (err) => { }, (err:BusinessError|string|undefined) => {
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({ left: 15 }).backgroundColor(Color.Blue) }).margin({ left: 15 }).backgroundColor(Color.Blue)
Button('本地资源png') Button('本地资源png')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.pngSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.pngSample').id)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil(); let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => { parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
this.imagePixelMap = pxielmap; this.imagePixelMap = pxielmap;
}, (err) => { },(err:BusinessError|string|undefined) => {
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({ left: 15 }).backgroundColor(Color.Blue) }).margin({ left: 15 }).backgroundColor(Color.Blue)
Button('本地资源bmp') Button('本地资源bmp')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.bmpSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.bmpSample').id)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil(); let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => { parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
this.imagePixelMap = pxielmap; this.imagePixelMap = pxielmap;
}, (err) => { }, (err:BusinessError|string|undefined) => {
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({ left: 15 }).backgroundColor(Color.Blue) }).margin({ left: 15 }).backgroundColor(Color.Blue)
Button('本地资源webp') Button('本地资源webp')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.jpgSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.jpgSample').id)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil(); let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => { parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
this.imagePixelMap = pxielmap; this.imagePixelMap = pxielmap;
}, (err) => { }, (err:BusinessError|string|undefined) => {
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({ left: 15 }).backgroundColor(Color.Blue) }).margin({ left: 15 }).backgroundColor(Color.Blue)
Button('本地资源gif') Button('本地资源gif')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.gifSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.gifSample').id)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil(); let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => { parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
this.imagePixelMap = pxielmap; this.imagePixelMap = pxielmap;
}, (err) => { }, (err:BusinessError|string|undefined) => {
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({ left: 15 }).backgroundColor(Color.Blue) }).margin({ left: 15 }).backgroundColor(Color.Blue)

View File

@ -17,7 +17,9 @@ import {FileUtils} from '@ohos/imageknife'
import {FileTypeUtil} from '@ohos/imageknife' import {FileTypeUtil} from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import {Base64} from '@ohos/imageknife' import {Base64} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import { BusinessError } from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct BasicTestResourceManagerPage { struct BasicTestResourceManagerPage {
@ -31,8 +33,9 @@ struct BasicTestResourceManagerPage {
Button('getMedia解析一张jpg图片') Button('getMedia解析一张jpg图片')
.margin({ top: 10 }) .margin({ top: 10 })
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.jpgSample') ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.id,) .getMediaContent($r('app.media.jpgSample')
.id)
.then(data => { .then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
@ -40,19 +43,20 @@ struct BasicTestResourceManagerPage {
let fileType = filetypeUtil.getFileType(arrayBuffer); let fileType = filetypeUtil.getFileType(arrayBuffer);
this.fileTypeStr = fileType; this.fileTypeStr = fileType;
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
}) })
Button('getMediaBase64解析一张png图片') Button('getMediaBase64解析一张png图片')
.margin({ top: 10 }) .margin({ top: 10 })
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMediaBase64($r('app.media.pngSample') ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContentBase64($r('app.media.pngSample')
.id) .id)
.then(data => { .then(data => {
console.log('ParseResClientBase64 - 本地加载资源 解析后数据data') console.log('ParseResClientBase64 - 本地加载资源 解析后数据data')
let matchReg = ';base64,'; let matchReg = ';base64,';
var firstIndex = data.indexOf(matchReg); let firstIndex = data.indexOf(matchReg);
data = data.substring(firstIndex + matchReg.length, data.length) data = data.substring(firstIndex + matchReg.length, data.length)
console.log('ParseResClientBase64 - 本地加载资源 解析后数据剔除非必要数据后data= ' + data) console.log('ParseResClientBase64 - 本地加载资源 解析后数据剔除非必要数据后data= ' + data)
let arrayBuffer = Base64.getInstance() let arrayBuffer = Base64.getInstance()
@ -61,7 +65,7 @@ struct BasicTestResourceManagerPage {
let fileType = filetypeUtil.getFileType(arrayBuffer); let fileType = filetypeUtil.getFileType(arrayBuffer);
this.fileTypeStr = fileType; this.fileTypeStr = fileType;
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
}) })

View File

@ -15,12 +15,13 @@
import {ImageKnife} from '@ohos/imageknife' import {ImageKnife} from '@ohos/imageknife'
import {OnRenameListener} from '@ohos/imageknife' import {OnRenameListener} from '@ohos/imageknife'
import {OnCompressListener} from '@ohos/imageknife' import {OnCompressListener} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
@Entry @Entry
@Component @Component
struct CompressPage { struct CompressPage {
@State mRPixelMap: PixelMap = undefined; @State mRPixelMap?: PixelMap = undefined;
@State mFPixelMap: PixelMap = undefined; @State mFPixelMap?: PixelMap = undefined;
@State mResultText: string= "压缩回调结果" @State mResultText: string= "压缩回调结果"
@State mResultPath: string= "压缩路径:" @State mResultPath: string= "压缩路径:"
@State mAsyncPath: string= "" @State mAsyncPath: string= ""
@ -90,58 +91,62 @@ struct CompressPage {
}.width('100%').height('100%'); }.width('100%').height('100%');
} }
private compressAsyncRecource() { private compressAsyncRecource() {
var data = new Array<Resource>(); let data = new Array<Resource>();
data.push($r('app.media.jpgSample')) data.push($r('app.media.jpgSample'))
console.info("asasd start compress") let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
globalThis.ImageKnife if(imageKnife!=undefined) {
.compressBuilder() imageKnife
.load(data) .compressBuilder()
.ignoreBy(100) .load(data)
.get() .ignoreBy(100)
.then((path)=>{ .get()
this.mAsyncPathHint = path; .then((path: string) => {
this.mAsyncPath='file://' + path; this.mAsyncPathHint = path;
}) this.mAsyncPath = 'file://' + path;
; });
}
console.info("asasd start compress end") console.info("asasd start compress end")
} }
private cropressRecource() { private cropressRecource() {
var data = new Array<Resource>(); let data = new Array<Resource>();
data.push($r('app.media.jpgSample')) data.push($r('app.media.jpgSample'))
var rename: OnRenameListener = { let rename: OnRenameListener = {
reName() { reName() {
return "test_1.jpg"; return "test_1.jpg";
} }
} }
var that = this;
var listener: OnCompressListener = { let listener: OnCompressListener = {
start() { start:()=>{
that.mResultText = "start" this.mResultText = "start"
console.info("asasd start") console.info("asasd start")
}, },
onScuccess(p: PixelMap, path: string) { onSuccess:(p: PixelMap | null | undefined, path: string)=> {
let pack = undefined; if(p!=null && p!=undefined) {
pack = p; let pack = p;
that.mRPixelMap = pack; this.mRPixelMap = pack as PixelMap;
console.info("asasd success path:" + this.mRPixelMap) console.info("asasd success path:" + this.mRPixelMap)
that.mResultText = "success"; this.mResultText = "success";
that.mResultPath = path; this.mResultPath = path;
}
}, },
onError(s: string) { onError:(s: string)=>{
console.info("asasd onError:" + s) console.info("asasd onError:" + s)
that.mResultText = "fail"; this.mResultText = "fail";
} }
} }
console.info("asasd start compress") console.info("asasd start compress")
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
globalThis.ImageKnife if(imageKnife != undefined) {
.compressBuilder() (ImageKnifeGlobal.getInstance().getImageKnife())
.load(data) .compressBuilder()
.ignoreBy(100) .load(data)
.setRenameListener(rename) .ignoreBy(100)
.setCompressListener(listener) .setRenameListener(rename)
.launch(); .setCompressListener(listener)
.launch();
}
console.info("asasd start compress end") console.info("asasd start compress end")
} }
} }

View File

@ -17,16 +17,18 @@ import { CropImage } from '@ohos/imageknife'
import { CropOptions } from '@ohos/imageknife' import { CropOptions } from '@ohos/imageknife'
import { Crop } from '@ohos/imageknife' import { Crop } from '@ohos/imageknife'
import { RecourseProvider } from '@ohos/imageknife' import { RecourseProvider } from '@ohos/imageknife'
import { PixelMapCrop } from '@ohos/imageknife' import { PixelMapCrop,Options } from '@ohos/imageknife'
import { CropCallback } from '@ohos/imageknife' import { CropCallback } from '@ohos/imageknife'
import { FileUtils } from '@ohos/imageknife' import { FileUtils } from '@ohos/imageknife'
import { ImageKnifeGlobal } from '@ohos/imageknife'
import { BusinessError } from '@ohos.base'
import resourceManager from '@ohos.resourceManager';
import common from '@ohos.app.ability.common'
@Entry @Entry
@Component @Component
export struct CropImagePage2 { export struct CropImagePage2 {
@State options1: PixelMapCrop.Options = new PixelMapCrop.Options(); @State options1: Options = new Options();
@State cropTap: boolean = false; @State cropTap: boolean = false;
@State width1: number = 0; @State width1: number = 0;
@ -41,24 +43,24 @@ export struct CropImagePage2 {
Column() { Column() {
Button('点击解析图片') Button('点击解析图片')
.onClick(() => { .onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.bmpSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.then(data => { .getMediaContent($r('app.media.bmpSample').id)
.then((data:Uint8Array) => {
let arrayBuffer = FileUtils.getInstance().uint8ArrayToBuffer(data); let arrayBuffer = FileUtils.getInstance().uint8ArrayToBuffer(data);
let optionx = new PixelMapCrop.Options(); let optionx = new Options();
optionx.setWidth(800) optionx.setWidth(800)
.setHeight(800) .setHeight(800)
.setCropFunction((err, pixelmap, sx, sy) => { .setCropFunction((err:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number) => {
console.log('PMC setCropFunction callback') console.log('PMC setCropFunction callback')
if (err) { if (err) {
console.error('PMC crop err =' + err) console.error('PMC crop err =' + err)
} else { } else {
this.width1 = sx * px2vp(1); this.width1 = sx * px2vp(1);
this.height1 = sy * px2vp(1); this.height1 = sy * px2vp(1);
this.canvasContext.drawImage(pixelmap,0,0,this.width1,this.height1) if(pixelmap != null) {
this.canvasContext.drawImage(pixelmap, 0, 0, this.width1, this.height1)
}
} }
}) })
optionx.loadBuffer(arrayBuffer, () => { optionx.loadBuffer(arrayBuffer, () => {
this.options1 = optionx; this.options1 = optionx;
@ -87,10 +89,14 @@ export struct CropImagePage2 {
}) })
.scale({ x: this._scale, y: this._scale, z: 1.0 }) .scale({ x: this._scale, y: this._scale, z: 1.0 })
.gesture(GestureGroup(GestureMode.Parallel, .gesture(GestureGroup(GestureMode.Parallel,
RotationGesture({ fingers: 2 }).onActionUpdate(event => { RotationGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
this._rotate = event.angle; if(event != undefined) {
}), PinchGesture({ fingers: 2 }).onActionUpdate(event => { this._rotate = event.angle;
this._scale = event.scale; }
}), PinchGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
if(event != undefined) {
this._scale = event.scale;
}
}))) })))
} }
.backgroundColor(Color.Brown) .backgroundColor(Color.Brown)

View File

@ -14,7 +14,7 @@
*/ */
import mediaLibrary from '@ohos.multimedia.mediaLibrary'; import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import { ImageKnifeComponent, ImageKnifeOption, } from '@ohos/imageknife' import { ImageKnifeComponent, ImageKnifeOption, } from '@ohos/imageknife'
import ArkWorker from '@ohos.worker'
@Entry @Entry
@Component @Component
@ -26,7 +26,7 @@ struct DataShareUriLoadPage {
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed') errorholderSrc: $r('app.media.icon_failed')
}; };
private globalGifWorker: any = undefined
build() { build() {
Scroll() { Scroll() {
@ -42,7 +42,7 @@ struct DataShareUriLoadPage {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
// 创建文件获取选项此处参数为获取image类型的文件资源 // 创建文件获取选项此处参数为获取image类型的文件资源
let imagesFetchOp = { let imagesFetchOp:mediaLibrary.MediaFetchOptions = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
}; };

View File

@ -13,14 +13,18 @@
* limitations under the License. * limitations under the License.
*/ */
import {GIFParseImpl} from '@ohos/imageknife' import {GIFParseImpl} from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import {ImageKnifeGlobal} from '@ohos/imageknife'
import {ImageKnife} from '@ohos/imageknife'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct gifTestCasePage { struct gifTestCasePage {
@State pixels:PixelMap = undefined @State pixels?:PixelMap = undefined
private globalGifWorker = undefined; private globalGifWorker?:worker.ThreadWorker = undefined;
build() { build() {
Scroll() { Scroll() {
@ -28,7 +32,8 @@ struct gifTestCasePage {
Flex({direction:FlexDirection.Row}){ Flex({direction:FlexDirection.Row}){
Button("加载gif图片") Button("加载gif图片")
.onClick(()=>{ .onClick(()=>{
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.test').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.test').id)
.then(data => { .then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength)
let gifImpl = new GIFParseImpl(); let gifImpl = new GIFParseImpl();
@ -42,14 +47,15 @@ struct gifTestCasePage {
} }
},undefined,true) },undefined,true)
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({left:5}).backgroundColor(Color.Blue) }).margin({left:5}).backgroundColor(Color.Blue)
Button("加载gif图片自带worker") Button("加载gif图片自带worker")
.onClick(()=>{ .onClick(()=>{
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.gifSample_single_frame').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.gifSample_single_frame').id)
.then(data => { .then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length = ' + data.byteLength) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length = ' + data.byteLength)
let local_worker = new worker.ThreadWorker('entry/ets/workers/GifLoadWorker.ts', { let local_worker = new worker.ThreadWorker('entry/ets/workers/GifLoadWorker.ts', {
@ -67,14 +73,15 @@ struct gifTestCasePage {
} }
},local_worker) },local_worker)
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
}).margin({left:5}).backgroundColor(Color.Blue) }).margin({left:5}).backgroundColor(Color.Blue)
Button("加载gif图片全局配置worker") Button("加载gif图片全局配置worker")
.onClick(()=>{ .onClick(()=>{
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.test').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.test').id)
.then(data => { .then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length = ' + data.byteLength) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length = ' + data.byteLength)
@ -89,7 +96,7 @@ struct gifTestCasePage {
} }
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
@ -116,7 +123,10 @@ struct gifTestCasePage {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
(ImageKnifeGlobal.getInstance().getImageKnife())?.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -16,13 +16,15 @@ import router from '@system.router';
import { import {
ImageKnifeComponent, ImageKnifeComponent,
ImageKnifeOption, ImageKnifeOption,
ImageKnifeGlobal,
ImageKnife
} from '@ohos/imageknife' } from '@ohos/imageknife'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
@Entry @Entry
@Component @Component
struct IndexFunctionDemo { struct IndexFunctionDemo {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
@ -91,7 +93,10 @@ struct IndexFunctionDemo {
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
// gif解析在子线程,请在页面构建后创建worker,注入imageknife // gif解析在子线程,请在页面构建后创建worker,注入imageknife
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
imageKnife?.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -14,6 +14,7 @@
*/ */
import {ImageKnifeComponent, ScaleType} from '@ohos/imageknife' import {ImageKnifeComponent, ScaleType} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import {Material} from './model/Material' import {Material} from './model/Material'
import {TestDataSource} from './model/TestDataSource' import {TestDataSource} from './model/TestDataSource'
@ -32,10 +33,13 @@ struct ManyPhotoShowPage {
Button('设置磁盘存储为50M') Button('设置磁盘存储为50M')
.onClick(()=>{ .onClick(()=>{
let disk:DiskLruCache = globalThis.ImageKnife.getDiskMemoryCache(); if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
disk.setMaxSize(50*1024*1024) let disk: DiskLruCache | undefined = (ImageKnifeGlobal.getInstance().getImageKnife())?.getDiskMemoryCache();
Prompt.showToast({message:"设置成功"}) if(disk != undefined) {
disk.setMaxSize(50 * 1024 * 1024)
Prompt.showToast({ message: "设置成功" })
}
}
}) })
List({ space: 20, scroller: this.elementScroller }) { List({ space: 20, scroller: this.elementScroller }) {

View File

@ -12,14 +12,14 @@
* 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.
*/ */
export class BasicDataSource implements IDataSource { export class BasicDataSource<T> implements IDataSource {
private listeners: DataChangeListener[] = []; private listeners: DataChangeListener[] = [];
public totalCount(): number { public totalCount(): number {
return 0; return 0;
} }
public getData(index: number): any { public getData(index: number):T | undefined {
return undefined; return undefined;
} }

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
export class Material{ export class Material{
material_id: string; material_id: string ='';
thumbnail: string; thumbnail: string = '';
name: string; name: string ='';
} }

View File

@ -14,7 +14,7 @@
*/ */
import {BasicDataSource} from './BasicDataSource' import {BasicDataSource} from './BasicDataSource'
import { Material } from './Material'; import { Material } from './Material';
export class TestDataSource extends BasicDataSource { export class TestDataSource extends BasicDataSource<Material> {
private dataArray: Material[] = [ private dataArray: Material[] = [
{name:"测试CBC",thumbnail:"https://xxtool-release.zone1.meitudata.com/xxtool-pre/material/R9aT7lpEEVxawo4.jpeg!thumb-w321-webp75",material_id:"5060118818"}, {name:"测试CBC",thumbnail:"https://xxtool-release.zone1.meitudata.com/xxtool-pre/material/R9aT7lpEEVxawo4.jpeg!thumb-w321-webp75",material_id:"5060118818"},
{name:"通用天空1像素测试",thumbnail:"https://xxtool-release.zone1.meitudata.com/xxtool-pre/material/1V6c63lKLGPlKVo.png!thumb-w321-webp75",material_id:"506009997"}, {name:"通用天空1像素测试",thumbnail:"https://xxtool-release.zone1.meitudata.com/xxtool-pre/material/1V6c63lKLGPlKVo.png!thumb-w321-webp75",material_id:"506009997"},
@ -574,7 +574,7 @@ export class TestDataSource extends BasicDataSource {
return this.dataArray.length; return this.dataArray.length;
} }
public getData(index: number): any { public getData(index: number): Material | undefined {
return this.dataArray[index]; return this.dataArray[index];
} }

View File

@ -15,18 +15,19 @@
import router from '@system.router'; import router from '@system.router';
import { Pngj } from '@ohos/imageknife' import { Pngj } from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import { FileUtils } from '@ohos/imageknife' import { FileUtils,ImageKnifeGlobal } from '@ohos/imageknife'
import featureability from '@ohos.ability.featureAbility' import featureability from '@ohos.ability.featureAbility'
import ArkWorker from '@ohos.worker' import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
import { BusinessError } from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct PngjTestCasePage { struct PngjTestCasePage {
pngSource1: ArrayBuffer = undefined; pngSource1?: ArrayBuffer = undefined;
pngSource2: ArrayBuffer = undefined; pngSource2?: ArrayBuffer = undefined;
pngSource3: ArrayBuffer = undefined; pngSource3?: ArrayBuffer = undefined;
pngSource4: ArrayBuffer = undefined; pngSource4?: ArrayBuffer = undefined;
pngdecodeRun1: boolean = false; pngdecodeRun1: boolean = false;
pngdecodeRun2: boolean = false; pngdecodeRun2: boolean = false;
pngdecodeRun3: boolean = false; pngdecodeRun3: boolean = false;
@ -52,29 +53,29 @@ struct PngjTestCasePage {
Button(this.hint7).fontSize(30) Button(this.hint7).fontSize(30)
.onClick(() => { .onClick(() => {
this.rootFolder = globalThis.ImageKnife.getImageKnifeContext().filesDir; this.rootFolder = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
globalThis.ImageKnife.getImageKnifeContext() ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
.resourceManager .resourceManager as resourceManager.ResourceManager)
.getMedia($r('app.media.pngSample').id) .getMediaContent($r('app.media.pngSample').id)
.then(data => { .then(data => {
this.pngSource1 = FileUtils.getInstance().uint8ArrayToBuffer(data); this.pngSource1 = FileUtils.getInstance().uint8ArrayToBuffer(data);
this.hint7 = '获取buffer成功可以测试' this.hint7 = '获取buffer成功可以测试'
}) })
.catch(err => { .catch( (err:BusinessError) => {
console.log('点击获取Png图片buffer err=' + err) console.log('点击获取Png图片buffer err=' + err)
}) })
}) })
Button('测试readPng') Button('测试readPng')
.onClick(() => { .onClick(() => {
if (this.pngSource1) { if (this.pngSource1!=undefined) {
if (!this.pngdecodeRun1) { if (!this.pngdecodeRun1) {
this.pngdecodeRun1 = true; this.pngdecodeRun1 = true;
let pngj = new Pngj(); let pngj = new Pngj();
pngj.readPngImageInfo(this.pngSource1, (sender, value) => { pngj.readPngImageInfo(this.pngSource1,{pngCallback: (sender, value) => {
this.hint1 = JSON.stringify(value); this.hint1 = JSON.stringify(value);
this.pngdecodeRun1 = false; this.pngdecodeRun1 = false;
}) }})
} else { } else {
this.hint7 = '已经在执行了,请稍等' this.hint7 = '已经在执行了,请稍等'
@ -91,22 +92,26 @@ struct PngjTestCasePage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button(this.hint8).fontSize(30) Button(this.hint8).fontSize(30)
.onClick(() => { .onClick(() => {
this.rootFolder = globalThis.ImageKnife.getImageKnifeContext().filesDir;
globalThis.ImageKnife.getImageKnifeContext()
.resourceManager
.getMedia($r('app.media.pngSample').id) this.rootFolder = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
.resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.pngSample').id)
.then(data => { .then(data => {
this.pngSource2 = FileUtils.getInstance().uint8ArrayToBuffer(data); this.pngSource2 = FileUtils.getInstance().uint8ArrayToBuffer(data);
this.hint8 = '获取buffer成功可以测试' this.hint8 = '获取buffer成功可以测试'
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('点击获取Png图片buffer err=' + err) console.log('点击获取Png图片buffer err=' + err)
}) })
}) })
Button('readPngAsync') Button('readPngAsync')
.onClick(() => { .onClick(() => {
if (this.pngSource2) { if (this.pngSource2!=undefined) {
if (!this.pngdecodeRun2) { if (!this.pngdecodeRun2) {
this.pngdecodeRun2 = true; this.pngdecodeRun2 = true;
let pngj = new Pngj(); let pngj = new Pngj();
@ -114,12 +119,12 @@ struct PngjTestCasePage {
type: 'classic', type: 'classic',
name: 'readPngImageAsync' name: 'readPngImageAsync'
}) })
pngj.readPngImageAsync(png_worker, this.pngSource1, (sender, value) => { pngj.readPngImageAsync(png_worker, this.pngSource2!, {pngCallback: (sender:ArrayBuffer, value:Record<string,Object>) => {
this.pngSource1 = sender this.pngSource1 = sender
this.hint2 = 'img with=' + value.width + ' img height=' + value.height this.hint2 = 'img with=' + value.width + ' img height=' + value.height
+ ' img depth=' + value.depth + ' img ctype=' + value.ctype + ' img depth=' + value.depth + ' img ctype=' + value.ctype
this.pngdecodeRun2 = false; this.pngdecodeRun2 = false;
}) }})
} else { } else {
this.hint8 = '已经在执行了,请稍等' this.hint8 = '已经在执行了,请稍等'
@ -136,22 +141,22 @@ struct PngjTestCasePage {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button(this.hint9).fontSize(30) Button(this.hint9).fontSize(30)
.onClick(() => { .onClick(() => {
this.rootFolder = globalThis.ImageKnife.getImageKnifeContext().filesDir; this.rootFolder = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
globalThis.ImageKnife.getImageKnifeContext() ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
.resourceManager .resourceManager as resourceManager.ResourceManager)
.getMedia($r('app.media.pngSample').id) .getMediaContent($r('app.media.pngSample').id)
.then(data => { .then(data => {
this.pngSource3 = FileUtils.getInstance().uint8ArrayToBuffer(data); this.pngSource3 = FileUtils.getInstance().uint8ArrayToBuffer(data);
this.hint9 = '获取buffer成功可以测试' this.hint9 = '获取buffer成功可以测试'
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('点击获取Png图片buffer err=' + err) console.log('点击获取Png图片buffer err=' + err)
}) })
}) })
Button('测试writePngWithString') Button('测试writePngWithString')
.onClick(() => { .onClick(() => {
if (this.pngSource3) { if (this.pngSource3 != undefined) {
if (!this.pngdecodeRun3) { if (!this.pngdecodeRun3) {
this.pngdecodeRun3 = true; this.pngdecodeRun3 = true;
let pngj = new Pngj(); let pngj = new Pngj();
@ -159,7 +164,7 @@ struct PngjTestCasePage {
type: 'classic', type: 'classic',
name: 'writePngWithStringAsync' name: 'writePngWithStringAsync'
}) })
pngj.writePngWithStringAsync(png_worker, 'hello world', this.pngSource3, (sender, value) => { pngj.writePngWithStringAsync(png_worker, 'hello world', this.pngSource3, {pngCallback: (sender:ArrayBuffer, value:ArrayBuffer) => {
this.pngSource3 = sender this.pngSource3 = sender
FileUtils.getInstance().createFileProcess( FileUtils.getInstance().createFileProcess(
this.rootFolder + '/pngj', this.rootFolder + '/pngj',
@ -168,7 +173,7 @@ struct PngjTestCasePage {
let png1 = new Uint8Array(value) let png1 = new Uint8Array(value)
this.hint3 = 'png写入后长度' + png1.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng.png' + '保存后使用2进制查看数据是否新增' this.hint3 = 'png写入后长度' + png1.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng.png' + '保存后使用2进制查看数据是否新增'
this.pngdecodeRun3 = false; this.pngdecodeRun3 = false;
}) }})
} else { } else {
this.hint9 = '已经在执行了,请稍等' this.hint9 = '已经在执行了,请稍等'
} }
@ -186,21 +191,21 @@ struct PngjTestCasePage {
Button(this.hint10).fontSize(30) Button(this.hint10).fontSize(30)
.onClick(() => { .onClick(() => {
this.rootFolder = globalThis.ImageKnife.getImageKnifeContext().filesDir; this.rootFolder = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
globalThis.ImageKnife.getImageKnifeContext() ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
.resourceManager .resourceManager as resourceManager.ResourceManager)
.getMedia($r('app.media.pngSample').id) .getMediaContent($r('app.media.pngSample').id)
.then(data => { .then(data => {
this.pngSource4 = FileUtils.getInstance().uint8ArrayToBuffer(data); this.pngSource4 = FileUtils.getInstance().uint8ArrayToBuffer(data);
this.hint10 = '获取buffer成功可以测试' this.hint10 = '获取buffer成功可以测试'
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('点击获取Png图片buffer err=' + err) console.log('点击获取Png图片buffer err=' + err)
}) })
}) })
Button('writePng') Button('writePng')
.onClick(()=>{ .onClick(()=>{
if (this.pngSource4) { if (this.pngSource4 != undefined) {
if (!this.pngdecodeRun4) { if (!this.pngdecodeRun4) {
this.pngdecodeRun4 = true; this.pngdecodeRun4 = true;
let pngj = new Pngj(); let pngj = new Pngj();
@ -208,7 +213,7 @@ struct PngjTestCasePage {
type: 'classic', type: 'classic',
name: 'writePngAsync' name: 'writePngAsync'
}) })
pngj.writePngAsync(png_worker, this.pngSource4, (sender, value) => { pngj.writePngAsync(png_worker, this.pngSource4,{pngCallback: (sender:ArrayBuffer, value:ArrayBuffer) => {
this.pngSource4 = sender this.pngSource4 = sender
FileUtils.getInstance().createFileProcess( FileUtils.getInstance().createFileProcess(
this.rootFolder + '/pngj', this.rootFolder + '/pngj',
@ -217,7 +222,7 @@ struct PngjTestCasePage {
let png2 = new Uint8Array(value) let png2 = new Uint8Array(value)
this.hint4 = 'png2未写入长度' + png2.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng2.png' + '保存后使用2进制查看数据是否新增' this.hint4 = 'png2未写入长度' + png2.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng2.png' + '保存后使用2进制查看数据是否新增'
this.pngdecodeRun4 = false; this.pngdecodeRun4 = false;
}) }})
} else { } else {
this.hint10 = '已经在执行了,请稍等' this.hint10 = '已经在执行了,请稍等'
} }

View File

@ -15,7 +15,7 @@
import {LruCache} from '@ohos/imageknife' import {LruCache} from '@ohos/imageknife'
function getRandomInt(min, max) { function getRandomInt(min:number, max:number):number {
min = Math.ceil(min); min = Math.ceil(min);
max = Math.floor(max); max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值 return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值

View File

@ -13,13 +13,16 @@
* limitations under the License. * limitations under the License.
*/ */
import {SVGParseImpl} from '@ohos/imageknife' import {SVGParseImpl} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager';
import {BusinessError} from '@ohos.base'
import common from '@ohos.app.ability.common';
@Entry @Entry
@Component @Component
struct svgTestCasePage { struct svgTestCasePage {
@State svgSamplePixelMap:PixelMap = undefined @State svgSamplePixelMap?:PixelMap = undefined
@State svgIconPixelMap:PixelMap = undefined @State svgIconPixelMap?:PixelMap = undefined
build() { build() {
Scroll() { Scroll() {
@ -28,15 +31,16 @@ struct svgTestCasePage {
Button("加载SVG图片") Button("加载SVG图片")
.onClick(()=>{ .onClick(()=>{
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.svgSample').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.then(data => { .getMediaContent($r('app.media.svgSample').id)
.then((data:Uint8Array) => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
let svgImpl = new SVGParseImpl(); let svgImpl = new SVGParseImpl();
svgImpl.parseSvg(data.buffer).then((pixelmap)=>{ svgImpl.parseSvg(data.buffer).then((pixelmap)=>{
this.svgSamplePixelMap = pixelmap; this.svgSamplePixelMap = pixelmap;
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })
@ -57,7 +61,8 @@ struct svgTestCasePage {
Button("加载SVG图片") Button("加载SVG图片")
.onClick(()=>{ .onClick(()=>{
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.iconsvg').id) ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMediaContent($r('app.media.iconsvg').id)
.then(data => { .then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data) console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
let svgImpl = new SVGParseImpl(); let svgImpl = new SVGParseImpl();
@ -65,7 +70,7 @@ struct svgTestCasePage {
this.svgIconPixelMap = pixelmap; this.svgIconPixelMap = pixelmap;
}) })
}) })
.catch(err => { .catch((err:BusinessError) => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err)); console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
}) })

View File

@ -12,19 +12,20 @@
* 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 router from '@system.router';
import { import {
ImageKnifeComponent, ImageKnifeComponent,
ImageKnifeOption, ImageKnifeOption,
ImageKnifeGlobal,
ImageKnife,
ImageKnifeDrawFactory, ImageKnifeDrawFactory,
ScaleType ScaleType
} from '@ohos/imageknife' } from '@ohos/imageknife'
import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
@Entry @Entry
@Component @Component
struct tempUrlTestPage { struct tempUrlTestPage {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.icon'), loadSrc: $r('app.media.icon'),
@ -89,8 +90,11 @@ struct tempUrlTestPage {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
// gif解析在子线程,请在页面构建后创建worker,注入imageknife let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) if(imageKnife != undefined) {
// gif解析在子线程,请在页面构建后创建worker,注入imageknife
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -13,18 +13,20 @@
* limitations under the License. * limitations under the License.
*/ */
import {RequestOption} from '@ohos/imageknife' import {RequestOption} from '@ohos/imageknife'
import {ImageKnifeData} from '@ohos/imageknife'
import {AllCacheInfo,IAllCacheInfoCallback} from '@ohos/imageknife' import {AllCacheInfo,IAllCacheInfoCallback} from '@ohos/imageknife'
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {TransformType} from '@ohos/imageknife' import {TransformType} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import {BusinessError} from '@ohos.base'
@Entry @Entry
@Component @Component
struct TestAllCacheInfoPage { struct TestAllCacheInfoPage {
@State nativePixelMap: PixelMap = undefined; @State nativePixelMap?: PixelMap = undefined;
@State networkPixelMap: PixelMap = undefined; @State networkPixelMap?: PixelMap = undefined;
allCacheInfoCallback1 =(allCacheInfo)=>{ allCacheInfoCallback1:IAllCacheInfoCallback ={callback:(allCacheInfo:AllCacheInfo)=>{
let info = allCacheInfo as AllCacheInfo; let info = allCacheInfo as AllCacheInfo;
console.log("AllCacheInfoCallback imageknifecomponent1 memory ="+JSON.stringify(info.memoryCacheInfo)) console.log("AllCacheInfoCallback imageknifecomponent1 memory ="+JSON.stringify(info.memoryCacheInfo))
console.log("AllCacheInfoCallback imageknifecomponent1 resource ="+JSON.stringify(info.resourceCacheInfo)) console.log("AllCacheInfoCallback imageknifecomponent1 resource ="+JSON.stringify(info.resourceCacheInfo))
@ -32,8 +34,8 @@ struct TestAllCacheInfoPage {
this.cacheinfo3 = "memory="+JSON.stringify(info.memoryCacheInfo)+ this.cacheinfo3 = "memory="+JSON.stringify(info.memoryCacheInfo)+
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+ "\n resource ="+JSON.stringify(info.resourceCacheInfo)+
"\n data ="+JSON.stringify(info.dataCacheInfo) "\n data ="+JSON.stringify(info.dataCacheInfo)
} }}
allCacheInfoCallback2 =(allCacheInfo)=>{ allCacheInfoCallback2:IAllCacheInfoCallback ={callback:(allCacheInfo:AllCacheInfo)=>{
let info = allCacheInfo as AllCacheInfo; let info = allCacheInfo as AllCacheInfo;
console.log("AllCacheInfoCallback ImageKnifeComponent memory ="+JSON.stringify(info.memoryCacheInfo)) console.log("AllCacheInfoCallback ImageKnifeComponent memory ="+JSON.stringify(info.memoryCacheInfo))
console.log("AllCacheInfoCallback ImageKnifeComponent resource ="+JSON.stringify(info.resourceCacheInfo)) console.log("AllCacheInfoCallback ImageKnifeComponent resource ="+JSON.stringify(info.resourceCacheInfo))
@ -41,7 +43,7 @@ struct TestAllCacheInfoPage {
this.cacheinfo4 = "memory="+JSON.stringify(info.memoryCacheInfo)+ this.cacheinfo4 = "memory="+JSON.stringify(info.memoryCacheInfo)+
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+ "\n resource ="+JSON.stringify(info.resourceCacheInfo)+
"\n data ="+JSON.stringify(info.dataCacheInfo) "\n data ="+JSON.stringify(info.dataCacheInfo)
} }}
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.pngSample'), loadSrc: $r('app.media.pngSample'),
@ -164,12 +166,11 @@ struct TestAllCacheInfoPage {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load($r('app.media.pngSample')) imageKnifeOption.load($r('app.media.pngSample'))
.setImageViewSize({width:300,height:300}) .setImageViewSize({width:300,height:300})
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let pack = undefined; let pack = data.drawPixelMap?.imagePixelMap as PixelMap;;
pack = data.drawPixelMap.imagePixelMap as PixelMap;;
this.nativePixelMap = pack; this.nativePixelMap = pack;
return false; return false;
}).addAllCacheInfoCallback((allCacheInfo)=>{ }}).addAllCacheInfoCallback({callback:(allCacheInfo:AllCacheInfo)=>{
let info = allCacheInfo as AllCacheInfo; let info = allCacheInfo as AllCacheInfo;
console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo)) console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo))
console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo)) console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo))
@ -177,20 +178,19 @@ struct TestAllCacheInfoPage {
this.cacheinfo1 = "memory="+JSON.stringify(info.memoryCacheInfo)+ this.cacheinfo1 = "memory="+JSON.stringify(info.memoryCacheInfo)+
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+ "\n resource ="+JSON.stringify(info.resourceCacheInfo)+
"\n data ="+JSON.stringify(info.dataCacheInfo) "\n data ="+JSON.stringify(info.dataCacheInfo)
}) }})
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
private testAllCacheInfoNetwork() { private testAllCacheInfoNetwork() {
let ImageKnifeOption = new RequestOption(); let ImageKnifeOption = new RequestOption();
ImageKnifeOption.load("https://hbimg.huabanimg.com/0ef60041445edcfd6b38d20e19024b2cd9281dcc3525a4-Vy8fYO_fw658/format/webp") ImageKnifeOption.load("https://hbimg.huabanimg.com/0ef60041445edcfd6b38d20e19024b2cd9281dcc3525a4-Vy8fYO_fw658/format/webp")
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let pack = undefined; let pack = data.drawPixelMap?.imagePixelMap as PixelMap;
pack = data.drawPixelMap.imagePixelMap as PixelMap;
this.networkPixelMap = pack; this.networkPixelMap = pack;
console.log("imageknife2 图片2 赋值!") console.log("imageknife2 图片2 赋值!")
return false; return false;
}).addAllCacheInfoCallback((allCacheInfo)=>{ }}).addAllCacheInfoCallback({callback:(allCacheInfo:AllCacheInfo)=>{
let info = allCacheInfo as AllCacheInfo; let info = allCacheInfo as AllCacheInfo;
console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo)) console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo))
console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo)) console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo))
@ -198,12 +198,12 @@ struct TestAllCacheInfoPage {
this.cacheinfo2 = "memory="+JSON.stringify(info.memoryCacheInfo)+ this.cacheinfo2 = "memory="+JSON.stringify(info.memoryCacheInfo)+
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+ "\n resource ="+JSON.stringify(info.resourceCacheInfo)+
"\n data ="+JSON.stringify(info.dataCacheInfo) "\n data ="+JSON.stringify(info.dataCacheInfo)
}) }})
.setImageViewSize({width:300,height:300}) .setImageViewSize({width:300,height:300})
.rotateImage(180) .rotateImage(180)
ImageKnife.call(ImageKnifeOption); ImageKnife?.call(ImageKnifeOption);
} }
} }
var ImageKnife = globalThis.ImageKnife let ImageKnife = (ImageKnifeGlobal.getInstance().getImageKnife())

View File

@ -14,13 +14,14 @@
*/ */
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import {ImageKnife} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker' import worker from '@ohos.worker'
@Entry @Entry
@Component @Component
struct TestGifDontAnimatePage { struct TestGifDontAnimatePage {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
@ -90,7 +91,10 @@ struct TestGifDontAnimatePage {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife : ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife!= undefined) {
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -12,7 +12,7 @@
* 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 { ImageKnife, ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknife' import { ImageKnife,ImageKnifeGlobal, ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknife'
import worker, { MessageEvents } from '@ohos.worker' import worker, { MessageEvents } from '@ohos.worker'
import Prompt from '@system.prompt' import Prompt from '@system.prompt'
@ -23,8 +23,8 @@ struct TestGifLoadWithWorkerPage {
@State options: ImageKnifeOption = { @State options: ImageKnifeOption = {
loadSrc: $r('app.media.icon') loadSrc: $r('app.media.icon')
} }
private my_worker: worker.ThreadWorker; private my_worker?: worker.ThreadWorker = undefined;
private my_gif_worker: worker.ThreadWorker; private my_gif_worker?: worker.ThreadWorker = undefined;
/** /**
* 界面进入时回调 * 界面进入时回调
@ -86,7 +86,7 @@ struct TestGifLoadWithWorkerPage {
this.my_gif_worker.onmessage = (e: MessageEvents) => { this.my_gif_worker.onmessage = (e: MessageEvents) => {
console.log("my_gif_worker.onmessage: " + e.data) console.log("my_gif_worker.onmessage: " + e.data)
} }
globalThis.ImageKnife.setGifWorker(this.my_gif_worker) (ImageKnifeGlobal.getInstance().getImageKnife())?.setGifWorker(this.my_gif_worker)
//子线程加载gif,不阻塞toast的消失 //子线程加载gif,不阻塞toast的消失
this.options = { this.options = {
@ -100,9 +100,9 @@ struct TestGifLoadWithWorkerPage {
Button('加载gif') Button('加载gif')
.margin({ top: 16 }) .margin({ top: 16 })
.onClick(() => { .onClick(() => {
console.log("ImageKnifeComponent button 加载gif onClick()")
globalThis.ImageKnife.setGifWorker(undefined) (ImageKnifeGlobal.getInstance().getImageKnife()).setGifWorker(undefined)
//主线程加载gif,阻塞toast的消失 //主线程加载gif,阻塞toast的消失
this.options = { this.options = {

View File

@ -14,6 +14,8 @@
*/ */
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import {ImageKnife} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker' import worker from '@ohos.worker'
@ -21,7 +23,7 @@ import worker from '@ohos.worker'
@Component @Component
struct TestImageKnifeOptionChangedPage { struct TestImageKnifeOptionChangedPage {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
@ -190,7 +192,10 @@ struct TestImageKnifeOptionChangedPage {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -14,9 +14,11 @@
*/ */
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {BaseTransform} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import {GrayscaleTransformation} from '@ohos/imageknife' import {GrayscaleTransformation} from '@ohos/imageknife'
import {SketchFilterTransformation} from '@ohos/imageknife' import {SketchFilterTransformation} from '@ohos/imageknife'
import image from '@ohos.multimedia.image'
@Entry @Entry
@Component @Component
@ -38,6 +40,7 @@ struct TestImageKnifeOptionChangedPage2 {
Flex({direction:FlexDirection.Row}){ Flex({direction:FlexDirection.Row}){
Button("网络jpg") Button("网络jpg")
.onClick(()=>{ .onClick(()=>{
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB", loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
@ -45,7 +48,7 @@ struct TestImageKnifeOptionChangedPage2 {
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier:0.1, thumbSizeMultiplier:0.1,
transformation:new RotateImageTransformation(180) transformation:rotateTrans
}; };
}).margin({left:5}).backgroundColor(Color.Blue) }).margin({left:5}).backgroundColor(Color.Blue)
Button("png") Button("png")

View File

@ -14,16 +14,20 @@
*/ */
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {ImageKnifeGlobal} from '@ohos/imageknife'
import {ImageKnife} from '@ohos/imageknife'
import {ScaleType} from '@ohos/imageknife' import {ScaleType} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife' import {RotateImageTransformation} from '@ohos/imageknife'
import {GrayscaleTransformation} from '@ohos/imageknife' import {GrayscaleTransformation} from '@ohos/imageknife'
import {SketchFilterTransformation} from '@ohos/imageknife' import {SketchFilterTransformation} from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker' import worker from '@ohos.worker'
import {BaseTransform} from '@ohos/imageknife'
import image from '@ohos.multimedia.image'
@Entry @Entry
@Component @Component
struct TestImageKnifeOptionChangedPage3 { struct TestImageKnifeOptionChangedPage3 {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
@ -41,13 +45,14 @@ struct TestImageKnifeOptionChangedPage3 {
Flex({direction:FlexDirection.Row}){ Flex({direction:FlexDirection.Row}){
Button("本地jpg") Button("本地jpg")
.onClick(()=>{ .onClick(()=>{
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
mainScaleType: ScaleType.FIT_CENTER, mainScaleType: ScaleType.FIT_CENTER,
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier:0.1, thumbSizeMultiplier:0.1,
transformation:new RotateImageTransformation(180), transformation:rotateTrans,
}; };
animateTo({ animateTo({
duration: 500, duration: 500,
@ -65,13 +70,15 @@ struct TestImageKnifeOptionChangedPage3 {
}).margin({left:5}).backgroundColor(Color.Blue) }).margin({left:5}).backgroundColor(Color.Blue)
Button("本地png") Button("本地png")
.onClick(()=>{ .onClick(()=>{
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: $r('app.media.pngSample'), loadSrc: $r('app.media.pngSample'),
mainScaleType: ScaleType.FIT_CENTER, mainScaleType: ScaleType.FIT_CENTER,
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier:0.1, thumbSizeMultiplier:0.1,
transformation:new RotateImageTransformation(180), transformation:rotateTrans,
}; };
animateTo({ animateTo({
duration: 500, duration: 500,
@ -141,13 +148,14 @@ struct TestImageKnifeOptionChangedPage3 {
Flex({direction:FlexDirection.Row}){ Flex({direction:FlexDirection.Row}){
Button("网络jpg") Button("网络jpg")
.onClick(()=>{ .onClick(()=>{
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB", loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
displayProgress:true, displayProgress:true,
thumbSizeMultiplier:0.1, thumbSizeMultiplier:0.1,
transformation:new RotateImageTransformation(180) transformation:rotateTrans
}; };
}).margin({left:5}).backgroundColor(Color.Blue) }).margin({left:5}).backgroundColor(Color.Blue)
Button("网络png") Button("网络png")
@ -203,7 +211,10 @@ struct TestImageKnifeOptionChangedPage3 {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -21,23 +21,27 @@ import {
SketchFilterTransformation, SketchFilterTransformation,
ScaleTypeHelper, ScaleTypeHelper,
IDrawLifeCycle, IDrawLifeCycle,
ScaleType ScaleType,
ImageKnifeGlobal,
BaseTransform
} from '@ohos/imageknife' } from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
import image from '@ohos.multimedia.image';
@Entry @Entry
@Component @Component
struct TestImageKnifeOptionChangedPage4 { struct TestImageKnifeOptionChangedPage4 {
private globalGifWorker:any = undefined private globalGifWorker?: worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier: 0.1, thumbSizeMultiplier: 0.1,
drawLifeCycle:this.createViewLifeCycle() drawLifeCycle: this.createViewLifeCycle()
}; };
private mTimerId: number = 0 private mTimerId: number = 0
@ -47,15 +51,16 @@ struct TestImageKnifeOptionChangedPage4 {
Flex({ direction: FlexDirection.Row }) { Flex({ direction: FlexDirection.Row }) {
Button("网络jpg") Button("网络jpg")
.onClick(() => { .onClick(() => {
let rotateTrans: BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
this.imageKnifeOption1 = { this.imageKnifeOption1 = {
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB", loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier: 0.1, thumbSizeMultiplier: 0.1,
transformation: new RotateImageTransformation(180), transformation: rotateTrans,
drawLifeCycle:this.createViewLifeCycle() drawLifeCycle: this.createViewLifeCycle()
}; };
}).margin({ left: 5 }).backgroundColor(Color.Blue) }).margin({ left: 5 }).backgroundColor(Color.Blue)
Button("网络png") Button("网络png")
@ -65,13 +70,14 @@ struct TestImageKnifeOptionChangedPage4 {
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier: 0.1, thumbSizeMultiplier: 0.1,
transformations: [new RotateImageTransformation(180)], transformations: [new RotateImageTransformation(180)],
drawLifeCycle:this.createViewLifeCycle() drawLifeCycle: this.createViewLifeCycle()
}; };
}).margin({ left: 5 }).backgroundColor(Color.Blue) }).margin({ left: 5 }).backgroundColor(Color.Blue)
}.margin({ top: 15 }) }.margin({ top: 15 })
Flex({ direction: FlexDirection.Row }) { Flex({ direction: FlexDirection.Row }) {
Button("网络bmp") Button("网络bmp")
.onClick(() => { .onClick(() => {
@ -80,10 +86,10 @@ struct TestImageKnifeOptionChangedPage4 {
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier: 0.1, thumbSizeMultiplier: 0.1,
transformations: [new GrayscaleTransformation()], transformations: [new GrayscaleTransformation()],
drawLifeCycle:this.createViewLifeCycle() drawLifeCycle: this.createViewLifeCycle()
}; };
}).margin({ left: 5 }).backgroundColor(Color.Blue) }).margin({ left: 5 }).backgroundColor(Color.Blue)
Button("网络webp") Button("网络webp")
@ -93,10 +99,10 @@ struct TestImageKnifeOptionChangedPage4 {
placeholderSrc: $r('app.media.icon_loading'), placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'), errorholderSrc: $r('app.media.icon_failed'),
thumbSizeMultiplier: 0.1, thumbSizeMultiplier: 0.1,
transformations: [new SketchFilterTransformation()], transformations: [new SketchFilterTransformation()],
drawLifeCycle:this.createViewLifeCycle() drawLifeCycle: this.createViewLifeCycle()
}; };
}).margin({ left: 5 }).backgroundColor(Color.Blue) }).margin({ left: 5 }).backgroundColor(Color.Blue)
}.margin({ top: 15 }) }.margin({ top: 15 })
@ -118,42 +124,52 @@ struct TestImageKnifeOptionChangedPage4 {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) ImageKnifeGlobal.getInstance().getImageKnife()?.setGifWorker(this.globalGifWorker)
} }
aboutToDisappear(){
if(this.globalGifWorker){ aboutToDisappear() {
if (this.globalGifWorker) {
this.globalGifWorker.terminate(); this.globalGifWorker.terminate();
} }
} }
drawMainAnimate(index, context, scaleType, imagePixelMap, widthPixel, heightPixel, compWidth, compHeight) { drawMainAnimate_index: number = 0;
console.log('drawMainAnimate index = '+index) drawMainAnimate_context?: CanvasRenderingContext2D = undefined;
drawMainAnimate_scaleType: ScaleType = ScaleType.FIT_CENTER;
drawMainAnimate_imagePixelMap?: PixelMap = undefined;
drawMainAnimate_widthPixel: number = 0;
drawMainAnimate_heightPixel: number = 0;
drawMainAnimate_compWidth: number = 0;
drawMainAnimate_compHeight: number = 0;
drawMainAnimate = () => {
console.log('drawMainAnimate index = ' + this.drawMainAnimate_index)
let clipScale = (index / 30.0) let clipScale = (this.drawMainAnimate_index / 30.0)
context.save() this.drawMainAnimate_context?.save()
context.beginPath(); this.drawMainAnimate_context?.beginPath();
let path2d = new Path2D() let path2d = new Path2D()
let maxRadius = Math.sqrt(compWidth / 2 * compWidth / 2 + compHeight / 2 * compHeight / 2) let maxRadius = Math.sqrt(this.drawMainAnimate_compWidth / 2 * this.drawMainAnimate_compWidth / 2 + this.drawMainAnimate_compHeight / 2 * this.drawMainAnimate_compHeight / 2)
path2d.arc(compWidth / 2, compHeight / 2, maxRadius * clipScale, 0, Math.PI * 2) path2d.arc(this.drawMainAnimate_compWidth / 2, this.drawMainAnimate_compHeight / 2, maxRadius * clipScale, 0, Math.PI * 2)
context.clip(path2d) this.drawMainAnimate_context?.clip(path2d)
context.save() this.drawMainAnimate_context?.save()
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, imagePixelMap, px2vp(widthPixel), px2vp(heightPixel), compWidth, compHeight,0,0) ScaleTypeHelper.drawImageWithScaleType(this.drawMainAnimate_context!, this.drawMainAnimate_scaleType, this.drawMainAnimate_imagePixelMap, px2vp(this.drawMainAnimate_widthPixel), px2vp(this.drawMainAnimate_heightPixel), this.drawMainAnimate_compWidth, this.drawMainAnimate_compHeight, 0, 0)
context.restore(); this.drawMainAnimate_context?.restore();
context.restore(); this.drawMainAnimate_context?.restore();
if(index<30){ if (this.drawMainAnimate_index < 30) {
index++ this.drawMainAnimate_index++
let nextFunc = this.drawMainAnimate.bind(this,index, context, scaleType, imagePixelMap, widthPixel, heightPixel, compWidth, compHeight) let nextFunc = this.drawMainAnimate
// @ts-ignore
this.mTimerId = setTimeout(nextFunc, 1000/30.0) this.mTimerId = setTimeout(nextFunc, 1000 / 30.0)
}else{ } else {
// 不做处理 // 不做处理
} }
} }
private stopAnimate(){
if(this.mTimerId > 0){ private stopAnimate() {
if (this.mTimerId > 0) {
clearTimeout(this.mTimerId) clearTimeout(this.mTimerId)
this.mTimerId = 0 this.mTimerId = 0
}else{ } else {
} }
} }
@ -162,16 +178,16 @@ struct TestImageKnifeOptionChangedPage4 {
let viewLifeCycle: IDrawLifeCycle = { let viewLifeCycle: IDrawLifeCycle = {
// 展示占位图 // 展示占位图
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.stopAnimate() this.stopAnimate()
return false; return false;
}, },
// 展示加载进度 // 展示加载进度
displayProgress: (context: CanvasRenderingContext2D, progress: number, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayProgress: (context: CanvasRenderingContext2D, progress: number, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.stopAnimate() this.stopAnimate()
context.save(); context.save();
context.clearRect(0,0,compWidth,compHeight) context.clearRect(0, 0, compWidth, compHeight)
let pi = Math.PI * 2 / 100; //pi 讲圆的周长划分为100份 let pi = Math.PI * 2 / 100; //pi 讲圆的周长划分为100份
let rate = progress - 25; let rate = progress - 25;
let diameter = compWidth > compHeight ? compHeight : compWidth let diameter = compWidth > compHeight ? compHeight : compWidth
@ -212,7 +228,7 @@ struct TestImageKnifeOptionChangedPage4 {
}, },
// 展示缩略图 // 展示缩略图
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.stopAnimate() this.stopAnimate()
return false; return false;
}, },
@ -221,14 +237,24 @@ struct TestImageKnifeOptionChangedPage4 {
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
this.stopAnimate() this.stopAnimate()
if (data.isPixelMap()) { if (data.isPixelMap()) {
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER
console.log('imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType) console.log('imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType)
let func = this.drawMainAnimate.bind(this,0, context, scaleType, data.drawPixelMap.imagePixelMap, imageInfo.size.width, imageInfo.size.height, compWidth, compHeight)
// @ts-ignore this.drawMainAnimate_index = 0;
this.mTimerId = setTimeout(func, 1000/30.0) this.drawMainAnimate_context = context;
this.drawMainAnimate_scaleType = scaleType
this.drawMainAnimate_imagePixelMap = data.drawPixelMap?.imagePixelMap
this.drawMainAnimate_widthPixel = imageInfo.size.width
this.drawMainAnimate_heightPixel = imageInfo.size.height
this.drawMainAnimate_compWidth = compWidth
this.drawMainAnimate_compHeight = compHeight
let func = this.drawMainAnimate
this.mTimerId = setTimeout(func, 1000 / 30.0)
console.log('TestImageKnifeOptionChangedPage4 drawMainSource end!') console.log('TestImageKnifeOptionChangedPage4 drawMainSource end!')
}) })
@ -239,14 +265,14 @@ struct TestImageKnifeOptionChangedPage4 {
// 展示重试图层 // 展示重试图层
displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.stopAnimate() this.stopAnimate()
return false; return false;
}, },
// 展示失败占位图 // 展示失败占位图
displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.stopAnimate() this.stopAnimate()
return false; return false;
} }

View File

@ -16,7 +16,9 @@ import {
GrayscaleTransformation, GrayscaleTransformation,
ImageKnifeComponent, ImageKnifeComponent,
ImageKnifeData, ImageKnifeData,
ImageKnifeGlobal,
ImageKnifeOption, ImageKnifeOption,
ImageKnife,
RotateImageTransformation, RotateImageTransformation,
SketchFilterTransformation, SketchFilterTransformation,
ScaleTypeHelper, ScaleTypeHelper,
@ -24,12 +26,11 @@ import {
ScaleType, ScaleType,
ImageKnifeDrawFactory ImageKnifeDrawFactory
} from '@ohos/imageknife' } from '@ohos/imageknife'
import ArkWorker from '@ohos.worker'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
@Entry @Entry
@Component @Component
struct TestImageKnifeOptionChangedPage5 { struct TestImageKnifeOptionChangedPage5 {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
@ -100,7 +101,10 @@ struct TestImageKnifeOptionChangedPage5 {
type: 'classic', type: 'classic',
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
if(imageKnife != undefined) {
imageKnife.setGifWorker(this.globalGifWorker)
}
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){
@ -109,7 +113,7 @@ struct TestImageKnifeOptionChangedPage5 {
} }
private choiceViewLifeCycle(type:DrawType): IDrawLifeCycle { private choiceViewLifeCycle(type:DrawType): IDrawLifeCycle {
let viewLifeCycle = undefined; let viewLifeCycle:IDrawLifeCycle|undefined = undefined;
switch(type){ switch(type){
case DrawType.Oval: case DrawType.Oval:
viewLifeCycle = ImageKnifeDrawFactory.createOvalLifeCycle(5,"#ff00ff") viewLifeCycle = ImageKnifeDrawFactory.createOvalLifeCycle(5,"#ff00ff")
@ -122,7 +126,7 @@ struct TestImageKnifeOptionChangedPage5 {
viewLifeCycle = { viewLifeCycle = {
// 展示占位图 // 展示占位图
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示加载进度 // 展示加载进度
@ -131,20 +135,20 @@ struct TestImageKnifeOptionChangedPage5 {
}, },
// 展示缩略图 // 展示缩略图
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示主图 // 展示主图
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
if (data.isPixelMap()) { if (data.isPixelMap()) {
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER
console.log('imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType) console.log('imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType)
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0)
context.restore(); context.restore();
console.log('TestImageKnifeOptionChangedPage4 drawMainSource end!') console.log('TestImageKnifeOptionChangedPage4 drawMainSource end!')
}) })

View File

@ -13,15 +13,17 @@
* limitations under the License. * limitations under the License.
*/ */
import {ImageKnifeComponent} from '@ohos/imageknife' import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeData} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife' import {ImageKnifeOption} from '@ohos/imageknife'
import {RequestOption} from '@ohos/imageknife' import {RequestOption} from '@ohos/imageknife'
import ArkWorker from '@ohos.worker' import {ImageKnifeGlobal } from '@ohos/imageknife'
import worker from '@ohos.worker' import worker from '@ohos.worker'
import { BusinessError } from '@ohos.base'
@Entry @Entry
@Component @Component
struct TestPreloadPage { struct TestPreloadPage {
private globalGifWorker:any = undefined private globalGifWorker?:worker.ThreadWorker = undefined
@State imageKnifeOption1: ImageKnifeOption = @State imageKnifeOption1: ImageKnifeOption =
{ {
loadSrc: $r('app.media.jpgSample'), loadSrc: $r('app.media.jpgSample'),
@ -82,15 +84,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.gifSample')) request.load($r('app.media.gifSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载本地资源gif 出现错误! err=' + err) console.log('预加载本地资源gif 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源gif成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源gif成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -116,15 +118,15 @@ struct TestPreloadPage {
request.load($r('app.media.gifSample')) request.load($r('app.media.gifSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.dontAnimate() .dontAnimate()
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err ) {
console.log('预加载本地资源gif静态 出现错误! err=' + err) console.log('预加载本地资源gif静态 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源gif静态成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源gif静态成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -151,15 +153,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658') request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源gif 出现错误! err=' + err) console.log('预加载网络资源gif 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -183,15 +185,15 @@ struct TestPreloadPage {
request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658') request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.dontAnimate() .dontAnimate()
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源gif静态 出现错误! err=' + err) console.log('预加载网络资源gif静态 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源gif静态成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源gif静态成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -222,15 +224,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.svgSample')) request.load($r('app.media.svgSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err ) {
console.log('预加载本地资源svg 出现错误! err=' + err) console.log('预加载本地资源svg 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源svg成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源svg成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -261,15 +263,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('http://124.222.187.78/download/test.svg') request.load('http://124.222.187.78/download/test.svg')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源gif 出现错误! err=' + err) console.log('预加载网络资源gif 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -302,15 +304,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.jpgSample')) request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载本地资源webp 出现错误! err=' + err) console.log('预加载本地资源webp 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源webp成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源webp成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -341,15 +343,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp') request.load('https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源webp 出现错误! err=' + err) console.log('预加载网络资源webp 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源webp成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源webp成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -380,15 +382,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.bmpSample')) request.load($r('app.media.bmpSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载本地资源bmp 出现错误! err=' + err) console.log('预加载本地资源bmp 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源bmp成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源bmp成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -419,15 +421,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('https://img-blog.csdn.net/20140514114029140') request.load('https://img-blog.csdn.net/20140514114029140')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源bmp 出现错误! err=' + err) console.log('预加载网络资源bmp 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -458,15 +460,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.pngSample')) request.load($r('app.media.pngSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载本地资源png 出现错误! err=' + err) console.log('预加载本地资源png 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源png成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源png成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -497,15 +499,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('https://img-blog.csdnimg.cn/20191215043500229.png') request.load('https://img-blog.csdnimg.cn/20191215043500229.png')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源bmp 出现错误! err=' + err) console.log('预加载网络资源bmp 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -536,15 +538,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load($r('app.media.jpgSample')) request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载本地资源jpg 出现错误! err=' + err) console.log('预加载本地资源jpg 出现错误! err=' + err)
} else { } else {
console.log('预加载本地资源jpg成功! imageKnifedata=' + JSON.stringify(data)) console.log('预加载本地资源jpg成功! imageKnifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -575,15 +577,15 @@ struct TestPreloadPage {
let request = new RequestOption(); let request = new RequestOption();
request.load('https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB') request.load('https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB')
.setImageViewSize({ width: 300, height: 300 }) .setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
if (err && err.length > 0) { if (err) {
console.log('预加载网络资源jpg 出现错误! err=' + err) console.log('预加载网络资源jpg 出现错误! err=' + err)
} else { } else {
console.log('预加载网络资源jpg成功! imageknifedata=' + JSON.stringify(data)) console.log('预加载网络资源jpg成功! imageknifedata=' + JSON.stringify(data))
} }
return false; return false;
}) }})
globalThis.ImageKnife.preload(request); ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
}) })
.margin({ left: 15 }) .margin({ left: 15 })
.backgroundColor(Color.Grey) .backgroundColor(Color.Grey)
@ -620,7 +622,7 @@ struct TestPreloadPage {
name: 'ImageKnifeParseGIF' name: 'ImageKnifeParseGIF'
}) })
// gif解析在子线程,请在页面构建后创建worker,注入imageknife // gif解析在子线程,请在页面构建后创建worker,注入imageknife
globalThis.ImageKnife.setGifWorker(this.globalGifWorker) ImageKnifeGlobal.getInstance().getImageKnife()?.setGifWorker(this.globalGifWorker)
} }
aboutToDisappear(){ aboutToDisappear(){
if(this.globalGifWorker){ if(this.globalGifWorker){

View File

@ -12,8 +12,8 @@
* 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 { ImageKnifeComponent } from '@ohos/imageknife/src/main/ets/components/imageknife/ImageKnifeComponent' import { ImageKnifeComponent } from '@ohos/imageknife'
import { ImageKnifeOption } from '@ohos/imageknife/src/main/ets/components/imageknife/ImageKnifeOption' import { ImageKnifeOption } from '@ohos/imageknife'
@Entry @Entry
@Component @Component

View File

@ -12,7 +12,7 @@
* 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 { RequestOption } from '@ohos/imageknife' import { RequestOption,ImageKnifeGlobal} from '@ohos/imageknife'
import { CropCircleTransformation } from '@ohos/imageknife' import { CropCircleTransformation } from '@ohos/imageknife'
import { RoundedCornersTransformation } from '@ohos/imageknife' import { RoundedCornersTransformation } from '@ohos/imageknife'
import { import {
@ -32,8 +32,8 @@ import { BlurTransformation } from '@ohos/imageknife'
import { PixelationFilterTransformation } from '@ohos/imageknife' import { PixelationFilterTransformation } from '@ohos/imageknife'
import { MaskTransformation } from '@ohos/imageknife' import { MaskTransformation } from '@ohos/imageknife'
import { SwirlFilterTransformation } from '@ohos/imageknife' import { SwirlFilterTransformation } from '@ohos/imageknife'
import { BusinessError } from '@ohos.base'
import {ImageKnifeData} from '@ohos/imageknife'
/** /**
* PixelMap transform 示例 * PixelMap transform 示例
*/ */
@ -45,28 +45,28 @@ let mUrl = $r('app.media.pngSample');
@Component @Component
struct TransformPixelMapPage { struct TransformPixelMapPage {
@State url: string = ""; @State url: string = "";
@State mCropPixelMap: PixelMap = undefined; @State mCropPixelMap?: PixelMap = undefined;
@State mRoundPixelMap: PixelMap = undefined; @State mRoundPixelMap?: PixelMap = undefined;
@State mCirclePixelMap: PixelMap = undefined; @State mCirclePixelMap?: PixelMap = undefined;
@State mCircleBorderPixelMap: PixelMap = undefined; @State mCircleBorderPixelMap?: PixelMap = undefined;
@State mRotatePixelMap: PixelMap = undefined; @State mRotatePixelMap?: PixelMap = undefined;
@State mSquarePixelMap: PixelMap = undefined; @State mSquarePixelMap?: PixelMap = undefined;
@State mClipTopPixelMap: PixelMap = undefined; @State mClipTopPixelMap?: PixelMap = undefined;
@State mClipCenterPixelMap: PixelMap = undefined; @State mClipCenterPixelMap?: PixelMap = undefined;
@State mClipBottomPixelMap: PixelMap = undefined; @State mClipBottomPixelMap?: PixelMap = undefined;
@State mGrayscalePixelMap: PixelMap = undefined; @State mGrayscalePixelMap?: PixelMap = undefined;
@State mBrightnessPixelMap: PixelMap = undefined; @State mBrightnessPixelMap?: PixelMap = undefined;
@State mContrastPixelMap: PixelMap = undefined; @State mContrastPixelMap?: PixelMap = undefined;
@State mInvertPixelMap: PixelMap = undefined; @State mInvertPixelMap?: PixelMap = undefined;
@State mSepiaPixelMap: PixelMap = undefined; @State mSepiaPixelMap?: PixelMap = undefined;
@State mSketchPixelMap: PixelMap = undefined; @State mSketchPixelMap?: PixelMap = undefined;
@State mBlurPixelMap: PixelMap = undefined; @State mBlurPixelMap?: PixelMap = undefined;
@State mPixelPixelMap: PixelMap = undefined; @State mPixelPixelMap?: PixelMap = undefined;
@State mSwirlPixelMap: PixelMap = undefined; @State mSwirlPixelMap?: PixelMap = undefined;
@State mMaskPixelMap: PixelMap = undefined; @State mMaskPixelMap?: PixelMap = undefined;
@State mKuwaharaPixelMap: PixelMap = undefined; @State mKuwaharaPixelMap?: PixelMap = undefined;
@State mToonPixelMap: PixelMap = undefined; @State mToonPixelMap?: PixelMap = undefined;
@State mVignettePixelMap: PixelMap = undefined; @State mVignettePixelMap?: PixelMap = undefined;
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
@ -545,67 +545,49 @@ struct TransformPixelMapPage {
* centerCrop * centerCrop
*/ */
centerCrop() { centerCrop() {
var imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load($r('app.media.jpgSample')) imageKnifeOption.load($r('app.media.jpgSample'))
// imageKnifeOption.load(mUrl) // imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined; this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mCropPixelMap = result;
setTimeout(() => {
let result2 = undefined;
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
this.mCropPixelMap = result2;
}, 100)
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(100), height: vp2px(100) }) .setImageViewSize({ width: vp2px(100), height: vp2px(100) })
.skipMemoryCache(true) .skipMemoryCache(true)
.centerCrop(); .centerCrop();
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
* centerInside * centerInside
*/ */
centerInside() { centerInside() {
var imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load($r('app.media.Back')) imageKnifeOption.load($r('app.media.Back'))
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined; this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mCropPixelMap = result;
setTimeout(() => {
let result2 = undefined;
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
this.mCropPixelMap = result2;
}, 100)
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(100), height: vp2px(100) }) .setImageViewSize({ width: vp2px(100), height: vp2px(100) })
.skipMemoryCache(true) .skipMemoryCache(true)
.centerInside(); .centerInside();
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
* centerInside * centerInside
*/ */
fitCenter() { fitCenter() {
var imageKnifeOption = new RequestOption() let imageKnifeOption = new RequestOption()
imageKnifeOption.load($r('app.media.Back')) imageKnifeOption.load($r('app.media.Back'))
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined; this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mCropPixelMap = result;
setTimeout(() => {
let result2 = undefined;
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
this.mCropPixelMap = result2;
}, 100)
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(100), height: vp2px(100) }) .setImageViewSize({ width: vp2px(100), height: vp2px(100) })
.skipMemoryCache(true) .skipMemoryCache(true)
.fitCenter(); .fitCenter();
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
* 圆角设置 * 圆角设置
@ -613,18 +595,12 @@ struct TransformPixelMapPage {
roundedCornersTransformation(top_left: number, roundedCornersTransformation(top_left: number,
bottom_left: number, top_right: number, bottom_right: number) { bottom_left: number, top_right: number, bottom_right: number) {
var imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined; this.mRoundPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mRoundPixelMap = result;
setTimeout(() => {
let result2 = undefined;
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
this.mRoundPixelMap = result2;
}, 100)
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(100), height: vp2px(100) }) .setImageViewSize({ width: vp2px(100), height: vp2px(100) })
.skipMemoryCache(true) .skipMemoryCache(true)
.roundedCorners({ .roundedCorners({
@ -633,7 +609,7 @@ struct TransformPixelMapPage {
bottom_left: bottom_left, bottom_left: bottom_left,
bottom_right: bottom_right bottom_right: bottom_right
}) })
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -642,16 +618,16 @@ struct TransformPixelMapPage {
circleTransformation() { circleTransformation() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mCirclePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mCirclePixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.cropCircle() .cropCircle()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -659,20 +635,20 @@ struct TransformPixelMapPage {
*/ */
circleBorderTransformation(border: number) { circleBorderTransformation(border: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var circleTransformation = new CropCircleWithBorderTransformation(border, let circleTransformation = new CropCircleWithBorderTransformation(border,
{ r_color: 255, g_color: 204, b_color: 204 }); { r_color: 255, g_color: 204, b_color: 204 });
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mCircleBorderPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mCircleBorderPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.cropCircleWithBorder(border, .cropCircleWithBorder(border,
{ r_color: 255, g_color: 204, b_color: 204 }) { r_color: 255, g_color: 204, b_color: 204 })
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -680,18 +656,18 @@ struct TransformPixelMapPage {
*/ */
transformRotate(angled: number) { transformRotate(angled: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new RotateImageTransformation(angled); let transformation = new RotateImageTransformation(angled);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mRotatePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mRotatePixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.rotateImage(angled) .rotateImage(angled)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -699,18 +675,18 @@ struct TransformPixelMapPage {
*/ */
transformSquare() { transformSquare() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new CropSquareTransformation(); let transformation = new CropSquareTransformation();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mSquarePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mSquarePixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.cropSquare() .cropSquare()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -718,26 +694,26 @@ struct TransformPixelMapPage {
*/ */
clipPixelMap(width: number, height: number, cropType: CropType) { clipPixelMap(width: number, height: number, cropType: CropType) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new CropTransformation(width, height, cropType); let transformation = new CropTransformation(width, height, cropType);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined; let result:PixelMap|undefined = undefined;
if (cropType == CropType.TOP) { if (cropType == CropType.TOP) {
result = data.drawPixelMap.imagePixelMap as PixelMap; result = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mClipTopPixelMap = result; this.mClipTopPixelMap = result;
} else if (cropType == CropType.CENTER) { } else if (cropType == CropType.CENTER) {
result = data.drawPixelMap.imagePixelMap as PixelMap; result = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mClipCenterPixelMap = result; this.mClipCenterPixelMap = result;
} else if (cropType == CropType.BOTTOM) { } else if (cropType == CropType.BOTTOM) {
result = data.drawPixelMap.imagePixelMap as PixelMap; result = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mClipBottomPixelMap = result; this.mClipBottomPixelMap = result;
} }
return false; return false;
}) }})
.setImageViewSize({ width: width, height: height }) .setImageViewSize({ width: width, height: height })
.skipMemoryCache(true) .skipMemoryCache(true)
.crop(width, height, cropType) .crop(width, height, cropType)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -746,19 +722,19 @@ struct TransformPixelMapPage {
*/ */
grayscalePixelMap() { grayscalePixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new GrayscaleTransformation(); let transformation = new GrayscaleTransformation();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mGrayscalePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mGrayscalePixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.grayscale() .grayscale()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -767,19 +743,19 @@ struct TransformPixelMapPage {
*/ */
brightnessPixelMap(brightness: number) { brightnessPixelMap(brightness: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new BrightnessFilterTransformation(brightness); let transformation = new BrightnessFilterTransformation(brightness);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mBrightnessPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mBrightnessPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.brightnessFilter(brightness) .brightnessFilter(brightness)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -788,19 +764,19 @@ struct TransformPixelMapPage {
*/ */
contrastPixelMap(contrast: number) { contrastPixelMap(contrast: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new ContrastFilterTransformation(contrast); let transformation = new ContrastFilterTransformation(contrast);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mContrastPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mContrastPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.contrastFilter(contrast) .contrastFilter(contrast)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -809,19 +785,19 @@ struct TransformPixelMapPage {
*/ */
invertPixelMap() { invertPixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new InvertFilterTransformation(); let transformation = new InvertFilterTransformation();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mInvertPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mInvertPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.invertFilter() .invertFilter()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -830,19 +806,19 @@ struct TransformPixelMapPage {
*/ */
sepiaPixelMap() { sepiaPixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new SepiaFilterTransformation(); let transformation = new SepiaFilterTransformation();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mSepiaPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mSepiaPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.sepiaFilter() .sepiaFilter()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -851,19 +827,19 @@ struct TransformPixelMapPage {
*/ */
sketchPixelMap() { sketchPixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new SketchFilterTransformation(); let transformation = new SketchFilterTransformation();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mSketchPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mSketchPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.sketchFilter() .sketchFilter()
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -872,19 +848,19 @@ struct TransformPixelMapPage {
*/ */
blurHandlePixelMap(radius: number) { blurHandlePixelMap(radius: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new BlurTransformation(radius); let transformation = new BlurTransformation(radius);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mBlurPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mBlurPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.blur(radius) .blur(radius)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -892,19 +868,19 @@ struct TransformPixelMapPage {
*/ */
pixelHandlePixelMap(pixel: number) { pixelHandlePixelMap(pixel: number) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new PixelationFilterTransformation(pixel); let transformation = new PixelationFilterTransformation(pixel);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mPixelPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mPixelPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.pixelationFilter(pixel) .pixelationFilter(pixel)
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -913,20 +889,20 @@ struct TransformPixelMapPage {
*/ */
swirlHandlePixelMap() { swirlHandlePixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new SwirlFilterTransformation(80); let transformation = new SwirlFilterTransformation(80);
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mSwirlPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mSwirlPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.swirlFilter(80) .swirlFilter(80)
// .diskCacheStrategy(new NONE()) // .diskCacheStrategy(new NONE())
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
/** /**
@ -934,20 +910,20 @@ struct TransformPixelMapPage {
*/ */
maskHandlePixelMap(maskResource: Resource) { maskHandlePixelMap(maskResource: Resource) {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
var transformation = new MaskTransformation(maskResource); let transformation = new MaskTransformation(maskResource);
// imageKnifeOption.load($r('app.media.photo6')) // imageKnifeOption.load($r('app.media.photo6'))
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mMaskPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mMaskPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.mask(maskResource) .mask(maskResource)
// .diskCacheStrategy(new NONE()) // .diskCacheStrategy(new NONE())
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -957,18 +933,18 @@ struct TransformPixelMapPage {
kuwaharaHandlePixelMap() { kuwaharaHandlePixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mKuwaharaPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mKuwaharaPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.kuwaharaFilter(20.0) .kuwaharaFilter(20.0)
// .diskCacheStrategy(new NONE()) // .diskCacheStrategy(new NONE())
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -978,18 +954,18 @@ struct TransformPixelMapPage {
toonHandlePixelMap() { toonHandlePixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mToonPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mToonPixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.toonFilter(0.2, 50.0); .toonFilter(0.2, 50.0);
// .diskCacheStrategy(new NONE()) // .diskCacheStrategy(new NONE())
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
@ -999,20 +975,20 @@ struct TransformPixelMapPage {
vignetteHandlePixelMap() { vignetteHandlePixelMap() {
let imageKnifeOption = new RequestOption(); let imageKnifeOption = new RequestOption();
imageKnifeOption.load(mUrl) imageKnifeOption.load(mUrl)
.addListener((err, data) => { .addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
let result = undefined;
result = data.drawPixelMap.imagePixelMap as PixelMap; this.mVignettePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.mVignettePixelMap = result;
return false; return false;
}) }})
.setImageViewSize({ width: vp2px(200), height: vp2px(200) }) .setImageViewSize({ width: vp2px(200), height: vp2px(200) })
.skipMemoryCache(true) .skipMemoryCache(true)
.enableGPU() .enableGPU()
.vignetteFilter([0.5, 0.5], [0.0, 0.0, 0.0], [0.3, 0.5]) .vignetteFilter([0.5, 0.5], [0.0, 0.0, 0.0], [0.3, 0.5])
// .diskCacheStrategy(new NONE()) // .diskCacheStrategy(new NONE())
ImageKnife.call(imageKnifeOption); ImageKnife?.call(imageKnifeOption);
} }
} }
var ImageKnife = globalThis.ImageKnife let ImageKnife = ImageKnifeGlobal.getInstance().getImageKnife();

View File

@ -19,25 +19,25 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
export default function abilityTest() { export default function abilityTest() {
describe('ActsAbilityTest', function () { describe('ActsAbilityTest', function () {
// 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(function () { beforeAll( ()=> {
// 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.
}) })
beforeEach(function () { beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('assertContain',0, function () { it('assertContain',0, ()=> {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
let a = 'abc' let a = 'abc'

View File

@ -14,41 +14,41 @@
*/ */
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import {ImageKnife,ImageKnifeDrawFactory} from '@ohos/imageknife' import {ImageKnife,ImageKnifeDrawFactory,ImageKnifeGlobal} from '@ohos/imageknife'
export default function ImageKnifeTest() { export default function ImageKnifeTest() {
describe('ImageKnifeTest', function () { describe('ImageKnifeTest', function () {
// 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(function () { beforeAll( ()=> {
// 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.
}) })
beforeEach(function () { beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('TestGlobalImageKnife',0, function () { it('TestGlobalImageKnife',0, ()=> {
globalThis.ImageKnife = ImageKnife.with(globalThis.TestAbilityContext) let global:ImageKnifeGlobal = ImageKnife.with(ImageKnifeGlobal.getInstance().getHapContext())
expect(globalThis.ImageKnife).not().assertUndefined() expect(global.getImageKnife()).not().assertUndefined()
}) })
it('TestGlobalDefaultLifeCycle',1, function () { it('TestGlobalDefaultLifeCycle',1, ()=> {
globalThis.ImageKnife = ImageKnife.with(globalThis.TestAbilityContext) ImageKnife.with(ImageKnifeGlobal.getInstance().getHapContext())
globalThis.ImageKnife.setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5)) (ImageKnifeGlobal.getInstance().getImageKnife()).setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
let globalLifeCycle = globalThis.ImageKnife.getDefaultLifeCycle(); let globalLifeCycle = (ImageKnifeGlobal.getInstance().getImageKnife()).getDefaultLifeCycle();
expect(globalLifeCycle).not().assertUndefined() expect(globalLifeCycle).not().assertUndefined()
}) })

View File

@ -17,27 +17,27 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
import {LogUtil} from '@ohos/imageknife' import {LogUtil} from '@ohos/imageknife'
export default function LogUtilTest() { export default function LogUtilTest() {
describe('LogUtilTest', function () { describe('LogUtilTest', ()=> {
// 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(function () { beforeAll( ()=> {
// 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.
}) })
beforeEach(function () { beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('TestLogUtilLevel',0, function () { it('TestLogUtilLevel',0, ()=> {
console.log("tag:LogUtil LogUtil.mLogLevel="+LogUtil.mLogLevel); console.log("tag:LogUtil LogUtil.mLogLevel="+LogUtil.mLogLevel);
LogUtil.mLogLevel = LogUtil.OFF; LogUtil.mLogLevel = LogUtil.OFF;

View File

@ -17,35 +17,35 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
import {LruCache} from '@ohos/imageknife' // DiskLruCache用例由DiskLruCache三方库提供 import {LruCache} from '@ohos/imageknife' // DiskLruCache用例由DiskLruCache三方库提供
export default function lruCacheTest() { export default function lruCacheTest() {
describe('lruCacheTest', function () { describe('lruCacheTest', ()=> {
// 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(function () { beforeAll( ()=> {
// 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.
}) })
beforeEach(function () { beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('testLruCacheSize',0, function () { it('testLruCacheSize',0, ()=> {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(100); let memoryCache = new LruCache<string, string>(100);
expect(memoryCache.size).assertEqual(0); expect(memoryCache.size).assertEqual(0);
expect(memoryCache.maxsize).assertEqual(100) expect(memoryCache.maxsize).assertEqual(100)
}) })
it('testLruCachePut',1, function () { it('testLruCachePut',1, ()=> {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(5); let memoryCache = new LruCache<string, string>(5);
memoryCache.put("1","1"); memoryCache.put("1","1");
memoryCache.put("2","2"); memoryCache.put("2","2");
memoryCache.put("3","3"); memoryCache.put("3","3");
@ -57,9 +57,9 @@ export default function lruCacheTest() {
let result = memoryCache.get("1") let result = memoryCache.get("1")
expect(result).assertEqual(undefined) expect(result).assertEqual(undefined)
}) })
it('testLruCacheGet',2, function () { it('testLruCacheGet',2, ()=> {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(5); let memoryCache = new LruCache<string, string>(5);
memoryCache.put("1","1"); memoryCache.put("1","1");
memoryCache.put("2","2"); memoryCache.put("2","2");
memoryCache.put("3","3"); memoryCache.put("3","3");
@ -71,9 +71,9 @@ export default function lruCacheTest() {
let result = memoryCache.get("2") let result = memoryCache.get("2")
expect(result).assertEqual("2") expect(result).assertEqual("2")
}) })
it('testLruCacheAlgorithm',3, function () { it('testLruCacheAlgorithm',3, ()=> {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(5); let memoryCache = new LruCache<string, string>(5);
memoryCache.put("1","1"); memoryCache.put("1","1");
memoryCache.put("2","2"); memoryCache.put("2","2");
memoryCache.put("3","3"); memoryCache.put("3","3");
@ -82,17 +82,24 @@ export default function lruCacheTest() {
memoryCache.get("1"); memoryCache.get("1");
memoryCache.get("2"); memoryCache.get("2");
let count:number = 1
memoryCache.foreachLruCache(function (value, key, index) { let callback =(key:string,value:string)=>{
if(index == 0){ if(count == 5){
expect(key).assertEqual("2") expect(key).assertEqual("2")
expect(value).assertEqual("2") expect(value).assertEqual("2")
}
console.log('dodo count='+count+' key='+key+' value='+value)
count++;
} }
memoryCache.foreachLruCache( (value:string, key:string, map:Map<string,string>)=> {
callback(key,value)
})
expect(memoryCache.size).assertEqual(5)
}) })
}) it('testLruCacheRemove',4, ()=> {
it('testLruCacheRemove',4, function () {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(5); let memoryCache = new LruCache<string, string>(5);
memoryCache.put("1","1"); memoryCache.put("1","1");
memoryCache.put("2","2"); memoryCache.put("2","2");
memoryCache.put("3","3"); memoryCache.put("3","3");
@ -104,16 +111,23 @@ export default function lruCacheTest() {
memoryCache.remove("2"); memoryCache.remove("2");
memoryCache.foreachLruCache(function (value, key, index) { let count:number = 1
if(index == 0){ let callback =(key:string,value:string)=>{
expect(key).assertEqual("1") if(count == 4){
expect(value).assertEqual("1") expect(key).assertEqual("1")
expect(value).assertEqual("1")
}
console.log('dodo count='+count+' key='+key+' value='+value)
count++;
} }
memoryCache.foreachLruCache( (value:string, key:string, map:Map<string,string>)=> {
callback(key,value)
})
expect(memoryCache.size).assertEqual(4)
}) })
}) it('testLruCacheResize',5, ()=> {
it('testLruCacheResize',5, function () {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let memoryCache = new LruCache<string, any>(5); let memoryCache = new LruCache<string, string>(5);
memoryCache.put("1","1"); memoryCache.put("1","1");
memoryCache.put("2","2"); memoryCache.put("2","2");
memoryCache.put("3","3"); memoryCache.put("3","3");

View File

@ -18,43 +18,43 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
import {RequestOption} from '@ohos/imageknife' import {RequestOption} from '@ohos/imageknife'
export default function RequestOptionTest() { export default function RequestOptionTest() {
describe('RequestOptionTest', function () { describe('RequestOptionTest', ()=> {
// 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(function () { beforeAll( ()=> {
// 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.
}) })
beforeEach(function () { beforeEach( ()=> {
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach( ()=> {
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll( ()=> {
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('TestRequestOption',0, function () { it('TestRequestOption',0, ()=> {
let option = new RequestOption(); let option = new RequestOption();
expect(option.requestListeners.length == 0).assertTrue() expect(option.requestListeners.length == 0).assertTrue()
}) })
it('TestConfigLoadSrc',1, function () { it('TestConfigLoadSrc',1, ()=> {
let option = new RequestOption(); let option = new RequestOption();
expect(option.loadSrc).assertEqual(undefined) expect(option.loadSrc).assertEqual('')
option.loadSrc = $r('app.media.icon') option.loadSrc = $r('app.media.icon')
expect(JSON.stringify(option.loadSrc)).assertEqual(JSON.stringify($r('app.media.icon'))) expect(JSON.stringify(option.loadSrc)).assertEqual(JSON.stringify($r('app.media.icon')))
}) })
it('TestConfigViewSize',2, function () { it('TestConfigViewSize',2, ()=> {
let option = new RequestOption(); let option = new RequestOption();
option.loadSrc = $r('app.media.icon') option.loadSrc = $r('app.media.icon')
option.setImageViewSize({width:100,height:100}) option.setImageViewSize({width:100,height:100})
expect(JSON.stringify(option.size)).assertEqual(JSON.stringify({width:100,height:100})) expect(JSON.stringify(option.size)).assertEqual(JSON.stringify({width:100,height:100}))
}) })
it('TestNormalConfigInfo',3, function () { it('TestNormalConfigInfo',3, ()=>{
let option = new RequestOption(); let option = new RequestOption();
expect(option.strategy.getName()).assertEqual('AUTOMATIC') expect(option.strategy.getName()).assertEqual('AUTOMATIC')

View File

@ -39,46 +39,46 @@ import {
} from '@ohos/imageknife' } from '@ohos/imageknife'
export default function Transform() { export default function Transform() {
describe('Transform', function () { describe('Transform', ()=>{
// 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(function () { beforeAll(()=>{
// 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.
}) })
beforeEach(function () { beforeEach(()=>{
// Presets an action, which is performed before each unit test case starts. // Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function. // This API supports only one parameter: preset action function.
}) })
afterEach(function () { afterEach(()=>{
// Presets a clear action, which is performed after each unit test case ends. // Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**. // The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
afterAll(function () { afterAll(()=>{
// Presets a clear action, which is performed after all test cases of the test suite end. // Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function. // This API supports only one parameter: clear action function.
}) })
it('TestBlurTransformation', 0, function () { it('TestBlurTransformation', 0, ()=>{
let blur = new BlurTransformation(15); let blur = new BlurTransformation(15);
expect(blur.getName()).assertEqual('BlurTransformation _mRadius:15') expect(blur.getName()).assertEqual('BlurTransformation _mRadius:15')
}) })
it('TestBrightnessFilterTransformation', 1, function () { it('TestBrightnessFilterTransformation', 1, ()=>{
let bright = new BrightnessFilterTransformation(20); let bright = new BrightnessFilterTransformation(20);
expect(bright.getName()).assertEqual("BrightnessFilterTransformation:20") expect(bright.getName()).assertEqual("BrightnessFilterTransformation:20")
}) })
it('TestContrastFilterTransformation', 2, function () { it('TestContrastFilterTransformation', 2, ()=>{
let constrast = new ContrastFilterTransformation(30); let constrast = new ContrastFilterTransformation(30);
expect(constrast.getName()).assertEqual("ContrastFilterTransformation:30") expect(constrast.getName()).assertEqual("ContrastFilterTransformation:30")
}) })
it('TestCropCircleTransformation', 3, function () { it('TestCropCircleTransformation', 3, ()=>{
let cropCircle = new CropCircleTransformation(); let cropCircle = new CropCircleTransformation();
expect(cropCircle.getName()).assertContain("CropCircleTransformation") expect(cropCircle.getName()).assertContain("CropCircleTransformation")
expect(cropCircle.getName()).assertContain(";mCenterX:") expect(cropCircle.getName()).assertContain(";mCenterX:")
expect(cropCircle.getName()).assertContain(";mCenterY:") expect(cropCircle.getName()).assertContain(";mCenterY:")
expect(cropCircle.getName()).assertContain(";mRadius:") expect(cropCircle.getName()).assertContain(";mRadius:")
}) })
it('TestCropCircleWithBorderTransformation', 4, function () { it('TestCropCircleWithBorderTransformation', 4, ()=>{
let CropCircleWithBorder = new CropCircleWithBorderTransformation(10,{r_color:100,g_color:100,b_color:100 }); let CropCircleWithBorder = new CropCircleWithBorderTransformation(10,{r_color:100,g_color:100,b_color:100 });
expect(CropCircleWithBorder.getName()).assertContain("CropCircleTransformation") expect(CropCircleWithBorder.getName()).assertContain("CropCircleTransformation")
expect(CropCircleWithBorder.getName()).assertContain(";mCenterX:") expect(CropCircleWithBorder.getName()).assertContain(";mCenterX:")
@ -89,63 +89,63 @@ export default function Transform() {
expect(CropCircleWithBorder.getName()).assertContain(";mGColor:") expect(CropCircleWithBorder.getName()).assertContain(";mGColor:")
expect(CropCircleWithBorder.getName()).assertContain(";mBColor:") expect(CropCircleWithBorder.getName()).assertContain(";mBColor:")
}) })
it('TestCropSquareTransformation', 5, function () { it('TestCropSquareTransformation', 5, ()=>{
let CropSquare = new CropSquareTransformation(); let CropSquare = new CropSquareTransformation();
expect(CropSquare.getName()).assertContain("CropSquareTransformation") expect(CropSquare.getName()).assertContain("CropSquareTransformation")
}) })
it('TestCropTransformation', 6, function () { it('TestCropTransformation', 6, ()=>{
let crop = new CropTransformation(10,10,CropType.CENTER); let crop = new CropTransformation(10,10,CropType.CENTER);
expect(crop.getName()).assertContain("CropCircleTransformation"+ ";mWidth:10" + ";mHeight:10" + ";mCropType:1" ) expect(crop.getName()).assertContain("CropCircleTransformation"+ ";mWidth:10" + ";mHeight:10" + ";mCropType:1" )
}) })
it('TestGrayscaleTransformation', 7, function () { it('TestGrayscaleTransformation', 7, ()=>{
let grayscale = new GrayscaleTransformation(); let grayscale = new GrayscaleTransformation();
expect(grayscale.getName()).assertContain("GrayscaleTransformation" ) expect(grayscale.getName()).assertContain("GrayscaleTransformation" )
}) })
it('TestInvertFilterTransformation', 8, function () { it('TestInvertFilterTransformation', 8, ()=>{
let invert = new InvertFilterTransformation(); let invert = new InvertFilterTransformation();
expect(invert.getName()).assertContain("InvertFilterTransformation" ) expect(invert.getName()).assertContain("InvertFilterTransformation" )
}) })
it('TestPixelationFilterTransformation', 9, function () { it('TestPixelationFilterTransformation', 9, ()=>{
let pixelation = new PixelationFilterTransformation(); let pixelation = new PixelationFilterTransformation();
expect(pixelation.getName()).assertContain("PixelationFilterTransformation" ) expect(pixelation.getName()).assertContain("PixelationFilterTransformation" )
}) })
it('TestRotateImageTransformation', 10, function () { it('TestRotateImageTransformation', 10, ()=>{
let rotateImage = new RotateImageTransformation(180); let rotateImage = new RotateImageTransformation(180);
expect(rotateImage.getName()).assertContain("RotateImageTransformation" + ";degreesToRotate:180") expect(rotateImage.getName()).assertContain("RotateImageTransformation" + ";degreesToRotate:180")
}) })
it('TestRoundedCornersTransformation', 11, function () { it('TestRoundedCornersTransformation', 11, ()=>{
let roundConer = new RoundedCornersTransformation({top_left:5,bottom_left:5,top_right:5,bottom_right:5}); let roundConer = new RoundedCornersTransformation({top_left:5,bottom_left:5,top_right:5,bottom_right:5});
expect(roundConer.getName()).assertContain("RoundedCornersTransformation" + ";mTop_left:" + 5 expect(roundConer.getName()).assertContain("RoundedCornersTransformation" + ";mTop_left:" + 5
+ ";mTop_right:" + 5 + ";mTop_right:" + 5
+ ";mBottom_left:" + 5 + ";mBottom_left:" + 5
+ ";mBottom_right:" + 5) + ";mBottom_right:" + 5)
}) })
it('TestSepiaFilterTransformation', 12, function () { it('TestSepiaFilterTransformation', 12, ()=>{
let speia = new SepiaFilterTransformation(); let speia = new SepiaFilterTransformation();
expect(speia.getName()).assertContain("SepiaFilterTransformation") expect(speia.getName()).assertContain("SepiaFilterTransformation")
}) })
it('TestSketchFilterTransformation', 13, function () { it('TestSketchFilterTransformation', 13, ()=>{
let Sketch = new SketchFilterTransformation(); let Sketch = new SketchFilterTransformation();
expect(Sketch.getName()).assertContain("SketchFilterTransformation") expect(Sketch.getName()).assertContain("SketchFilterTransformation")
}) })
it('TestMaskTransformation', 14, function () { it('TestMaskTransformation', 14, ()=>{
let mask = new MaskTransformation($r('app.media.icon')); let mask = new MaskTransformation($r('app.media.icon'));
expect(mask.getName()).assertContain("MaskTransformation") expect(mask.getName()).assertContain("MaskTransformation")
}) })
it('TestSwirlFilterTransformation', 15, function () { it('TestSwirlFilterTransformation', 15, ()=>{
let swirl = new SwirlFilterTransformation(10,180,[10,10]); let swirl = new SwirlFilterTransformation(10,180,[10,10]);
expect(swirl.getName()).assertContain("SwirlFilterTransformation") expect(swirl.getName()).assertContain("SwirlFilterTransformation")
}) })
it('TestKuwaharaFilterTransform', 16, function () { it('TestKuwaharaFilterTransform', 16, ()=>{
let kuwahara = new KuwaharaFilterTransform(10); let kuwahara = new KuwaharaFilterTransform(10);
expect(kuwahara.getName()).assertContain("KuwaharaFilterTransform _mRadius:10") expect(kuwahara.getName()).assertContain("KuwaharaFilterTransform _mRadius:10")
}) })
it('TestToonFilterTransform', 17, function () { it('TestToonFilterTransform', 17, ()=>{
let toon = new ToonFilterTransform(10); let toon = new ToonFilterTransform(10);
expect(toon.getName()).assertContain("ToonFilterTransform threshold:") expect(toon.getName()).assertContain("ToonFilterTransform threshold:")
expect(toon.getName()).assertContain(";quantizationLevels:") expect(toon.getName()).assertContain(";quantizationLevels:")
}) })
it('TestVignetteFilterTransform', 18, function () { it('TestVignetteFilterTransform', 18, ()=>{
let vignette = new VignetteFilterTransform([0.5, 0.5],[0.0, 0.0, 0.0],[0.3, 0.75]); let vignette = new VignetteFilterTransform([0.5, 0.5],[0.0, 0.0, 0.0],[0.3, 0.75]);
expect(vignette.getName()).assertContain("VignetteFilterTransform centerPoint:") expect(vignette.getName()).assertContain("VignetteFilterTransform centerPoint:")
expect(vignette.getName()).assertContain(";vignetteColor:") expect(vignette.getName()).assertContain(";vignetteColor:")

View File

@ -18,7 +18,7 @@ import hilog from '@ohos.hilog';
import { Hypium } from '@ohos/hypium'; import { Hypium } from '@ohos/hypium';
import testsuite from '../test/List.test'; import testsuite from '../test/List.test';
import window from '@ohos.window'; import window from '@ohos.window';
import {ImageKnife,ImageKnifeDrawFactory,ImageKnifeGlobal} from '@ohos/imageknife'
export default class TestAbility extends UIAbility { export default class TestAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate'); hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
@ -30,7 +30,8 @@ export default class TestAbility extends UIAbility {
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!'); hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!');
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
globalThis.TestAbilityContext = this.context.createModuleContext("entry_test") // 初始化xts的ImageKnife
ImageKnife.with(this.context.createModuleContext("entry_test"));
} }
onDestroy() { onDestroy() {

View File

@ -18,110 +18,111 @@
* cache * cache
*/ */
export * from './src/main/ets/components/cache/FileUtils' export { FileUtils } from './src/main/ets/components/cache/FileUtils'
export * from './src/main/ets/components/cache/Base64' export { Base64 } from './src/main/ets/components/cache/Base64'
export * from './src/main/ets/components/cache/LruCache' export { LruCache } from './src/main/ets/components/cache/LruCache'
export * from './src/main/ets/components/cache/diskstrategy/enum/ALL' export { DiskStrategy } from './src/main/ets/components/cache/diskstrategy/DiskStrategy'
export * from './src/main/ets/components/cache/diskstrategy/enum/AUTOMATIC' export { ALL } from './src/main/ets/components/cache/diskstrategy/enum/ALL'
export * from './src/main/ets/components/cache/diskstrategy/enum/DATA' export { AUTOMATIC } from './src/main/ets/components/cache/diskstrategy/enum/AUTOMATIC'
export * from './src/main/ets/components/cache/diskstrategy/enum/NONE' export { DATA } from './src/main/ets/components/cache/diskstrategy/enum/DATA'
export * from './src/main/ets/components/cache/diskstrategy/enum/RESOURCE' export { NONE } from './src/main/ets/components/cache/diskstrategy/enum/NONE'
export type {EngineKeyInterface} from './src/main/ets/components/cache/key/EngineKeyInterface' export { RESOURCE } from './src/main/ets/components/cache/diskstrategy/enum/RESOURCE'
export * from './src/main/ets/components/cache/key/EngineKeyFactories' export { EngineKeyInterface } from './src/main/ets/components/cache/key/EngineKeyInterface'
export { EngineKeyFactories } from './src/main/ets/components/cache/key/EngineKeyFactories'
/** /**
* compress * compress
*/ */
export * from './src/main/ets/components/imageknife/compress/CompressBuilder' export { CompressBuilder } from './src/main/ets/components/imageknife/compress/CompressBuilder'
export type {OnCompressListener} from './src/main/ets/components/imageknife/compress/listener/OnCompressListener' export { OnCompressListener } from './src/main/ets/components/imageknife/compress/listener/OnCompressListener'
export type {OnRenameListener} from './src/main/ets/components/imageknife/compress/listener/OnRenameListener' export { OnRenameListener } from './src/main/ets/components/imageknife/compress/listener/OnRenameListener'
export type {CompressDataListener} from './src/main/ets/components/imageknife/compress/listener/CompressDataListener' export { CompressDataListener } from './src/main/ets/components/imageknife/compress/listener/CompressDataListener'
export * from './src/main/ets/components/imageknife/compress/listener/CompressionPredicate' export { CompressionPredicate } from './src/main/ets/components/imageknife/compress/listener/CompressionPredicate'
export * from './src/main/ets/components/imageknife/compress/provider/CompressAdapter' export { CompressAdapter } from './src/main/ets/components/imageknife/compress/provider/CompressAdapter'
export * from './src/main/ets/components/imageknife/compress/provider/CompressProvider' export { CompressProvider } from './src/main/ets/components/imageknife/compress/provider/CompressProvider'
export * from './src/main/ets/components/imageknife/compress/provider/DataStringPathProvider' export { DataStringPathProvider } from './src/main/ets/components/imageknife/compress/provider/DataStringPathProvider'
export * from './src/main/ets/components/imageknife/compress/provider/RecourseProvider' export { RecourseProvider } from './src/main/ets/components/imageknife/compress/provider/RecourseProvider'
/** /**
* crop * crop
*/ */
export * from './src/main/ets/components/imageknife/crop/Crop'
export * from './src/main/ets/components/imageknife/crop/CropImage' export { CropImage } from './src/main/ets/components/imageknife/crop/CropImage'
export * from './src/main/ets/components/imageknife/crop/CropOptions' export { CropOptions } from './src/main/ets/components/imageknife/crop/CropOptions'
export {default as PixelMapCrop} from './src/main/ets/components/imageknife/crop/PixelMapCrop' export { PixelMapCrop,Options } from './src/main/ets/components/imageknife/crop/PixelMapCrop'
export * from './src/main/ets/components/imageknife/crop/CropCallback' export { CropCallback } from './src/main/ets/components/imageknife/crop/CropCallback'
/** /**
* transform * transform
*/ */
export type {BaseTransform} from './src/main/ets/components/imageknife/transform/BaseTransform' export { BaseTransform } from './src/main/ets/components/imageknife/transform/BaseTransform'
export * from './src/main/ets/components/imageknife/transform/BlurTransformation' export { BlurTransformation } from './src/main/ets/components/imageknife/transform/BlurTransformation'
export * from './src/main/ets/components/imageknife/transform/BrightnessFilterTransformation' export { BrightnessFilterTransformation } from './src/main/ets/components/imageknife/transform/BrightnessFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/ContrastFilterTransformation' export { ContrastFilterTransformation } from './src/main/ets/components/imageknife/transform/ContrastFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/CropCircleTransformation' export { CropCircleTransformation } from './src/main/ets/components/imageknife/transform/CropCircleTransformation'
export * from './src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation' export { CropCircleWithBorderTransformation,rgbColor } from './src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation'
export * from './src/main/ets/components/imageknife/transform/CropSquareTransformation' export { CropSquareTransformation } from './src/main/ets/components/imageknife/transform/CropSquareTransformation'
export * from './src/main/ets/components/imageknife/transform/CropTransformation' export { CropTransformation,CropType } from './src/main/ets/components/imageknife/transform/CropTransformation'
export * from './src/main/ets/components/imageknife/transform/GrayscaleTransformation' export { GrayscaleTransformation } from './src/main/ets/components/imageknife/transform/GrayscaleTransformation'
export * from './src/main/ets/components/imageknife/transform/InvertFilterTransformation' export { InvertFilterTransformation } from './src/main/ets/components/imageknife/transform/InvertFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/PixelationFilterTransformation' export { PixelationFilterTransformation } from './src/main/ets/components/imageknife/transform/PixelationFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/RotateImageTransformation' export { RotateImageTransformation } from './src/main/ets/components/imageknife/transform/RotateImageTransformation'
export * from './src/main/ets/components/imageknife/transform/RoundedCornersTransformation' export { RoundedCornersTransformation,RoundCorner } from './src/main/ets/components/imageknife/transform/RoundedCornersTransformation'
export * from './src/main/ets/components/imageknife/transform/SepiaFilterTransformation' export { SepiaFilterTransformation } from './src/main/ets/components/imageknife/transform/SepiaFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/SketchFilterTransformation' export { SketchFilterTransformation } from './src/main/ets/components/imageknife/transform/SketchFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/MaskTransformation' export { MaskTransformation } from './src/main/ets/components/imageknife/transform/MaskTransformation'
export * from './src/main/ets/components/imageknife/transform/SwirlFilterTransformation' export { SwirlFilterTransformation } from './src/main/ets/components/imageknife/transform/SwirlFilterTransformation'
export * from './src/main/ets/components/imageknife/transform/KuwaharaFilterTransform' export { KuwaharaFilterTransform } from './src/main/ets/components/imageknife/transform/KuwaharaFilterTransform'
export * from './src/main/ets/components/imageknife/transform/ToonFilterTransform' export { ToonFilterTransform } from './src/main/ets/components/imageknife/transform/ToonFilterTransform'
export * from './src/main/ets/components/imageknife/transform/VignetteFilterTransform' export { VignetteFilterTransform } from './src/main/ets/components/imageknife/transform/VignetteFilterTransform'
export * from './src/main/ets/components/imageknife/transform/TransformUtils' export { TransformUtils } from './src/main/ets/components/imageknife/transform/TransformUtils'
export * from './src/main/ets/components/imageknife/transform/TransformType' export { TransformType } from './src/main/ets/components/imageknife/transform/TransformType'
export * from './src/main/ets/components/imageknife/transform/pixelmap/CenterCrop' export { CenterCrop } from './src/main/ets/components/imageknife/transform/pixelmap/CenterCrop'
export * from './src/main/ets/components/imageknife/transform/pixelmap/CenterInside' export { CenterInside } from './src/main/ets/components/imageknife/transform/pixelmap/CenterInside'
export * from './src/main/ets/components/imageknife/transform/pixelmap/FitCenter' export { FitCenter } from './src/main/ets/components/imageknife/transform/pixelmap/FitCenter'
/** /**
* pngj * pngj
*/ */
export * from './src/main/ets/components/imageknife/pngj/Pngj' export { Pngj } from './src/main/ets/components/imageknife/pngj/Pngj'
export {handler} from './PngWork' export {handler} from './PngWork'
export * from './src/main/ets/components/3rd_party/upng/UPNG' export { UPNG } from './src/main/ets/components/3rd_party/upng/UPNG'
/** /**
* ImageKnife * ImageKnife
*/ */
export * from './src/main/ets/components/imageknife/ImageKnife' export { ImageKnife } from './src/main/ets/components/imageknife/ImageKnife'
export * from './src/main/ets/components/imageknife/RequestOption' export { ImageKnifeGlobal } from './src/main/ets/components/imageknife/ImageKnifeGlobal'
export * from './src/main/ets/components/imageknife/ImageKnifeComponent' export {RequestOption,Size} from './src/main/ets/components/imageknife/RequestOption'
export * from './src/main/ets/components/imageknife/ImageKnifeDrawFactory' export { ImageKnifeComponent, ScaleType, ScaleTypeHelper } from './src/main/ets/components/imageknife/ImageKnifeComponent'
export * from './src/main/ets/components/imageknife/ImageKnifeOption' export { ImageKnifeDrawFactory } from './src/main/ets/components/imageknife/ImageKnifeDrawFactory'
export * from './src/main/ets/components/imageknife/ImageKnifeData' export {ImageKnifeOption,CropCircleWithBorder,Crop,GifOptions,TransformOptions} from './src/main/ets/components/imageknife/ImageKnifeOption'
export type {IAllCacheInfoCallback} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback' export { ImageKnifeData } from './src/main/ets/components/imageknife/ImageKnifeData'
export type {AllCacheInfo} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback' export {IAllCacheInfoCallback,AllCacheInfo,ResourceCacheInfo,MemoryCacheInfo,DataCacheInfo} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback'
export type {IParseImage} from './src/main/ets/components/imageknife/interface/IParseImage' export {IParseImage} from './src/main/ets/components/imageknife/interface/IParseImage'
export type {IDataFetch} from './src/main/ets/components/imageknife/networkmanage/IDataFetch' export {IDataFetch} from './src/main/ets/components/imageknife/networkmanage/IDataFetch'
export type {ICache} from './src/main/ets/components/imageknife/requestmanage/ICache' export {ICache} from './src/main/ets/components/imageknife/requestmanage/ICache'
export * from './src/main/ets/components/imageknife/utils/FileTypeUtil' export { FileTypeUtil } from './src/main/ets/components/imageknife/utils/FileTypeUtil'
export * from './src/main/ets/components/imageknife/utils/ParseImageUtil' export { ParseImageUtil } from './src/main/ets/components/imageknife/utils/ParseImageUtil'
/** /**
* svg parse * svg parse
*/ */
export * from './src/main/ets/components/imageknife/utils/svg/SVGParseImpl' export { SVGParseImpl } from './src/main/ets/components/imageknife/utils/svg/SVGParseImpl'
/** /**
* gif parse * gif parse
*/ */
export * from './src/main/ets/components/imageknife/utils/gif/GIFParseImpl' export { GIFParseImpl } from './src/main/ets/components/imageknife/utils/gif/GIFParseImpl'
export * from './src/main/ets/components/imageknife/utils/gif/GIFFrame' export { GIFFrame } from './src/main/ets/components/imageknife/utils/gif/GIFFrame'
// 能力增强worker 解析GIF数据 // 能力增强worker 解析GIF数据
export {gifHandler} from './GifWorker' export { gifHandler } from './GifWorker'
// 自定义组件新增 // 自定义组件新增
// 自定义组件绘制生命周期 // 自定义组件绘制生命周期
export type {IDrawLifeCycle} from './src/main/ets/components/imageknife/interface/IDrawLifeCycle' export { IDrawLifeCycle } from './src/main/ets/components/imageknife/interface/IDrawLifeCycle'
// 日志管理 // 日志管理
export * from './src/main/ets/components/imageknife/utils/LogUtil' export { LogUtil } from './src/main/ets/components/imageknife/utils/LogUtil'

View File

@ -14,7 +14,7 @@
"main": "index.ets", "main": "index.ets",
"repository": "https://gitee.com/openharmony-tpc/ImageKnife", "repository": "https://gitee.com/openharmony-tpc/ImageKnife",
"type": "module", "type": "module",
"version": "2.0.5-rc.0", "version": "2.1.0",
"dependencies": { "dependencies": {
"@ohos/disklrucache": "^2.0.0", "@ohos/disklrucache": "^2.0.0",
"@ohos/svg": "^2.0.0", "@ohos/svg": "^2.0.0",

View File

@ -18,24 +18,24 @@ export class Base64 {
private static sInstance: Base64; private static sInstance: Base64;
public static getInstance(): Base64{ public static getInstance(): Base64{
if (!this.sInstance) { if (!Base64.sInstance) {
this.sInstance = new Base64(); Base64.sInstance = new Base64();
} }
return this.sInstance; return Base64.sInstance;
} }
private constructor() { private constructor() {
console.log("Base64 - constructor init!") console.log("Base64 - constructor init!")
for (var index = 0; index < this.chars.length; index++) { for (let index = 0; index < this.chars.length; index++) {
this.lookup[this.chars.charCodeAt(index)] = index; this.lookup[this.chars.charCodeAt(index)] = index;
} }
} }
encode(arraybuffer: ArrayBuffer): string { encode(arraybuffer: ArrayBuffer): string {
let bytes = new Uint8Array(arraybuffer), let bytes = new Uint8Array(arraybuffer),
i,
len = bytes.length, len = bytes.length,
base64 = ''; base64 = '';
let i:number = 0
for (i = 0; i < len; i += 3) { for (i = 0; i < len; i += 3) {
base64 += this.chars[bytes[i] >> 2]; base64 += this.chars[bytes[i] >> 2];
base64 += this.chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += this.chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
@ -53,12 +53,12 @@ export class Base64 {
decode(base64: string): ArrayBuffer{ decode(base64: string): ArrayBuffer{
let bufferLength = base64.length * 0.75, let bufferLength = base64.length * 0.75,
len = base64.length, len = base64.length,
i, p = 0;
p = 0, let i:number = 0;
encoded1, let encoded1:number = 0;
encoded2, let encoded2:number = 0;
encoded3, let encoded3:number = 0;
encoded4; let encoded4:number = 0;
if (base64[base64.length - 1] === '=') { if (base64[base64.length - 1] === '=') {
bufferLength--; bufferLength--;

View File

@ -38,7 +38,7 @@ export class CustomMap <K, V> {
if (key == null || value == null) { if (key == null || value == null) {
throw new Error('key or value is invalid,checking the parameter'); throw new Error('key or value is invalid,checking the parameter');
} }
var pre = this.map.get(key) let pre = this.map.get(key)
if (this.hasKey(key)) { if (this.hasKey(key)) {
this.map.delete(key) this.map.delete(key)
} }
@ -70,7 +70,7 @@ export class CustomMap <K, V> {
return this.map.size; return this.map.size;
} }
// 遍历Map,执行处理函数. 回调函数 function(key,value,index){..} // 遍历Map,执行处理函数. 回调函数 function(key,value,index){..}
each(fn) { each(fn: (value: V, key: K, map: Map<K, V>) => void) {
this.map.forEach(fn) this.map.forEach(fn)
} }
// 清除键值对 // 清除键值对

View File

@ -1,72 +0,0 @@
/*
* Copyright (C) 2021 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 fs from '@ohos.file.fs';
export class FileReader {
// 文件大小
fileLength: number = 0
// 读取的长度
length: number = 0
// 读写stream
stream: any = null
// 缓存buf
buf: ArrayBuffer = new ArrayBuffer(1)
constructor(path: string) {
if (!path || Object.keys(path).length == 0) {
return
}
try {
this.stream = fs.createStreamSync(path, 'r+');
var stat = fs.statSync(path)
this.fileLength = stat.size
} catch (e) {
}
}
/**
* 循环读取文件数据
*/
readLine(): string{
var line = ''
while (this.length <= this.fileLength) {
this.stream.readSync(this.buf, { position: this.length })
this.length++
var temp = String.fromCharCode.apply(null, new Uint8Array(this.buf));
line = line + temp
if (temp == '\n' || temp == '\r') {
return line
}
}
return line
}
/**
* 判断文件是否结束
*/
isEnd() {
return this.fileLength <= 0 || this.length == this.fileLength
}
/**
* 关闭stream
*/
close() {
this.stream.closeSync()
}
}

View File

@ -14,20 +14,20 @@
*/ */
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base'
export class FileUtils { export class FileUtils {
base64Str: string = '' base64Str: string = ''
private static sInstance: FileUtils; private static sInstance: FileUtils;
public static getInstance(): FileUtils { public static getInstance(): FileUtils {
if (!this.sInstance) { if (!FileUtils.sInstance) {
this.sInstance = new FileUtils(); FileUtils.sInstance = new FileUtils();
} }
return this.sInstance; return FileUtils.sInstance;
} }
private constructor() { private constructor() {
console.error("FileUtils - FileUtils constructor") console.log("FileUtils - FileUtils constructor")
} }
/** /**
@ -50,7 +50,7 @@ export class FileUtils {
fs.unlinkSync(path); fs.unlinkSync(path);
} }
} catch (err) { } catch (err) {
console.log("FileUtils deleteFile Method has error, err msg=" + err.message + " err code=" + err.code); console.log("FileUtils deleteFile Method has error, err msg=" + (err as BusinessError).message + " err code=" + (err as BusinessError).code);
} }
} }
/** /**
@ -63,11 +63,11 @@ export class FileUtils {
if (fileExist) { if (fileExist) {
fs.unlink(path).then(()=>{ fs.unlink(path).then(()=>{
resolve(); resolve();
}).catch(err=>{ }).catch( (err:BusinessError)=>{
reject(err) reject(err)
}) })
} }
}).catch(err=>{ }).catch((err:BusinessError)=>{
reject(err); reject(err);
}) })
}) })
@ -89,7 +89,7 @@ export class FileUtils {
* 异步删除文件目录 必须保证文件夹里面没有文件 * 异步删除文件目录 必须保证文件夹里面没有文件
* @param path 待删除目录的绝对路径 * @param path 待删除目录的绝对路径
*/ */
deleteFolderAsync(path: string, deleteComplete, deleteError) { deleteFolderAsync(path: string, deleteComplete:(value: void) => void | PromiseLike<void>, deleteError:(reason: Object) => PromiseLike<never>) {
if (this.existFolder(path)) { if (this.existFolder(path)) {
fs.rmdir(path) fs.rmdir(path)
.then(deleteComplete).catch(deleteError); .then(deleteComplete).catch(deleteError);
@ -209,10 +209,10 @@ export class FileUtils {
// 关闭文件 // 关闭文件
fs.closeSync(file); fs.closeSync(file);
resolve(buf); resolve(buf);
}).catch(err=>{ }).catch((err:BusinessError)=>{
reject(err); reject(err);
}) })
}).catch(err=>{ }).catch((err:BusinessError)=>{
reject(err); reject(err);
}) })
@ -235,7 +235,9 @@ export class FileUtils {
let ss = fs.createStreamSync(path, "r+"); let ss = fs.createStreamSync(path, "r+");
ss.readSync(buf) ss.readSync(buf)
ss.closeSync(); ss.closeSync();
return String.fromCharCode.apply(null, new Uint8Array(buf)) let u8:Uint8Array = new Uint8Array(buf);
let array:Array<number> = Array.from(u8)
return String.fromCharCode(...array)
} catch (e) { } catch (e) {
console.log("FileUtils - readFilePic " + e) console.log("FileUtils - readFilePic " + e)
return "" return ""
@ -307,33 +309,18 @@ export class FileUtils {
* string 转 Uint8Array * string 转 Uint8Array
* @param str 输入String * @param str 输入String
*/ */
stringToUint8Array(str): Uint8Array { stringToUint8Array(str:string): Uint8Array {
var arr = []; let arr:Array<number> = new Array<number>();
for (var i = 0, j = str.length; i < j; ++i) { for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i)); arr.push(str.charCodeAt(i));
} }
var tmpUint8Array = new Uint8Array(arr); let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array return tmpUint8Array
} }
/**
* int 转 byte[]
* @param n 输入int
*/
intTobytes2(n) {
var bytes = [];
for (var i = 0; i < 2; i++) {
bytes[i] = n >> (8 - i * 8);
}
return bytes;
}
uint8ArrayToBuffer(array: Uint8Array): ArrayBuffer { uint8ArrayToBuffer(array: Uint8Array): ArrayBuffer {
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset) return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
} }
} }
export interface AsyncCallback<T> {
(err: string, data: T): void;
}

View File

@ -30,7 +30,7 @@ export class LruCache <K, V> {
if (key == null || value == null) { if (key == null || value == null) {
throw new Error('key or value is invalid '); throw new Error('key or value is invalid ');
} }
var pre = this.map.get(key) let pre = this.map.get(key)
if (pre == null) { if (pre == null) {
this.size++ this.size++
} }
@ -43,7 +43,7 @@ export class LruCache <K, V> {
if (key == null) { if (key == null) {
throw new Error('key is null,checking the parameter'); throw new Error('key is null,checking the parameter');
} }
var preValue = this.map.get(key) let preValue = this.map.get(key)
if (this.map.remove(key)) { if (this.map.remove(key)) {
this.size-- this.size--
} }
@ -51,11 +51,11 @@ export class LruCache <K, V> {
} }
// 获取键为key的value // 获取键为key的value
get(key: K): V { get(key: K): V|undefined {
if (key == null) { if (key == null) {
throw new Error('key is null,checking the parameter'); throw new Error('key is null,checking the parameter');
} }
var preValue = this.map.get(key) let preValue = this.map.get(key)
if (preValue != null) { if (preValue != null) {
this.entryRemoved(key, preValue, preValue) this.entryRemoved(key, preValue, preValue)
} }
@ -69,7 +69,7 @@ export class LruCache <K, V> {
* preValue 对应key键的旧value值 * preValue 对应key键的旧value值
* value 对应key键的新value值 * value 对应key键的新value值
*/ */
entryRemoved(key: K, preValue: V, value: V) { entryRemoved(key: K, preValue: V | undefined, value: V | undefined) {
if (preValue != null) { if (preValue != null) {
this.map.remove(key) this.map.remove(key)
} }
@ -89,7 +89,7 @@ export class LruCache <K, V> {
if (this.size <= tempsize || this.map.isEmpty()) { if (this.size <= tempsize || this.map.isEmpty()) {
break break
} }
var delkey = this.map.getFirstKey() let delkey = this.map.getFirstKey()
this.map.remove(delkey) this.map.remove(delkey)
this.size-- this.size--
} }
@ -126,13 +126,13 @@ export class LruCache <K, V> {
} }
this.map.each(function (value, key, index) { this.map.each( (value, key, index) => {
printResult +='LruCache:key=' + key + 'value= ' + value; printResult +='LruCache:key=' + key + 'value= ' + value;
}) })
return printResult; return printResult;
} }
foreachLruCache(fn){ foreachLruCache(fn:(value: V, key: K, map: Map<K, V>) => void){
this.map.each(fn); this.map.each(fn);
} }

View File

@ -1,392 +0,0 @@
/*
* Copyright (C) 2021 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.
*/
export class Md5 {
// One time hashing functions
public static hashStr(str: string, raw?: false): string
public static hashStr(str: string, raw: true): Int32Array
public static hashStr(str: string, raw: boolean = false) {
return this.onePassHasher
.start()
.appendStr(str)
.end(raw);
}
public static hashAsciiStr(str: string, raw?: false): string
public static hashAsciiStr(str: string, raw: true): Int32Array
public static hashAsciiStr(str: string, raw: boolean = false) {
return this.onePassHasher
.start()
.appendAsciiStr(str)
.end(raw);
}
// Private Static Variables
private static stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]);
private static buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
private static hexChars = '0123456789abcdef';
private static hexOut: string[] = [];
// Permanent instance is to use for one-call hashing
private static onePassHasher = new Md5();
private static _hex(x: any): string {
const hc = Md5.hexChars;
const ho = Md5.hexOut;
let n;
let offset;
let j;
let i;
for (i = 0; i < 4; i += 1) {
offset = i * 8;
n = x[i];
for (j = 0; j < 8; j += 2) {
ho[offset + 1 + j] = hc.charAt(n & 0x0F);
n >>>= 4;
ho[offset + 0 + j] = hc.charAt(n & 0x0F);
n >>>= 4;
}
}
return ho.join('');
}
private static _md5cycle(x: Int32Array | Uint32Array, k: Int32Array | Uint32Array) {
let a = x[0];
let b = x[1];
let c = x[2];
let d = x[3];
// ff()
a += (b & c | ~b & d) + k[0] - 680876936 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[1] - 389564586 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[2] + 606105819 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[4] - 176418897 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[7] - 45705983 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[10] - 42063 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[13] - 40341101 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
b = (b << 22 | b >>> 10) + c | 0;
// gg()
a += (b & d | c & ~d) + k[1] - 165796510 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[11] + 643717713 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[0] - 373897302 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[5] - 701558691 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[10] + 38016083 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[15] - 660478335 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[4] - 405537848 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[9] + 568446438 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[3] - 187363961 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[2] - 51403784 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
b = (b << 20 | b >>> 12) + c | 0;
// hh()
a += (b ^ c ^ d) + k[5] - 378558 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[14] - 35309556 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[7] - 155497632 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[13] + 681279174 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[0] - 358537222 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[3] - 722521979 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[6] + 76029189 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[9] - 640364487 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[12] - 421815835 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[15] + 530742520 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[2] - 995338651 | 0;
b = (b << 23 | b >>> 9) + c | 0;
// ii()
a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
b = (b << 21 | b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
b = (b << 21 | b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
b = (b << 21 | b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
b = (b << 21 | b >>> 11) + c | 0;
x[0] = a + x[0] | 0;
x[1] = b + x[1] | 0;
x[2] = c + x[2] | 0;
x[3] = d + x[3] | 0;
}
private _dataLength: number;
private _bufferLength: number;
private _state: Int32Array = new Int32Array(4);
private _buffer: ArrayBuffer = new ArrayBuffer(68);
private _buffer8: Uint8Array;
private _buffer32: Uint32Array;
constructor() {
this._buffer8 = new Uint8Array(this._buffer, 0, 68);
this._buffer32 = new Uint32Array(this._buffer, 0, 17);
this.start();
}
public start() {
this._dataLength = 0;
this._bufferLength = 0;
this._state.set(Md5.stateIdentity);
return this;
}
// Char to code point to to array conversion:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
// #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown
public appendStr(str: string) {
const buf8 = this._buffer8;
const buf32 = this._buffer32;
let bufLen = this._bufferLength;
let code;
let i;
for (i = 0; i < str.length; i += 1) {
code = str.charCodeAt(i);
if (code < 128) {
buf8[bufLen++] = code;
} else if (code < 0x800) {
buf8[bufLen++] = (code >>> 6) + 0xC0;
buf8[bufLen++] = code & 0x3F | 0x80;
} else if (code < 0xD800 || code > 0xDBFF) {
buf8[bufLen++] = (code >>> 12) + 0xE0;
buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80;
buf8[bufLen++] = (code & 0x3F) | 0x80;
} else {
code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000;
if (code > 0x10FFFF) {
throw new Error('Unicode standard supports code points up to U+10FFFF');
}
buf8[bufLen++] = (code >>> 18) + 0xF0;
buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80;
buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80;
buf8[bufLen++] = (code & 0x3F) | 0x80;
}
if (bufLen >= 64) {
this._dataLength += 64;
Md5._md5cycle(this._state, buf32);
bufLen -= 64;
buf32[0] = buf32[16];
}
}
this._bufferLength = bufLen;
return this;
}
public appendAsciiStr(str: string) {
const buf8 = this._buffer8;
const buf32 = this._buffer32;
let bufLen = this._bufferLength;
let i;
let j = 0;
for (;; ) {
i = Math.min(str.length - j, 64 - bufLen);
while (i--) {
buf8[bufLen++] = str.charCodeAt(j++);
}
if (bufLen < 64) {
break;
}
this._dataLength += 64;
Md5._md5cycle(this._state, buf32);
bufLen = 0;
}
this._bufferLength = bufLen;
return this;
}
public appendByteArray(input: Uint8Array) {
const buf8 = this._buffer8;
const buf32 = this._buffer32;
let bufLen = this._bufferLength;
let i;
let j = 0;
for (;; ) {
i = Math.min(input.length - j, 64 - bufLen);
while (i--) {
buf8[bufLen++] = input[j++];
}
if (bufLen < 64) {
break;
}
this._dataLength += 64;
Md5._md5cycle(this._state, buf32);
bufLen = 0;
}
this._bufferLength = bufLen;
return this;
}
public getState() {
const self = this;
const s = self._state;
return {
buffer: String.fromCharCode.apply(null, self._buffer8),
buflen: self._bufferLength,
length: self._dataLength,
state: [s[0], s[1], s[2], s[3]]
};
}
public setState(state: any) {
const buf = state.buffer;
const x = state.state;
const s = this._state;
let i;
this._dataLength = state.length;
this._bufferLength = state.buflen;
s[0] = x[0];
s[1] = x[1];
s[2] = x[2];
s[3] = x[3];
for (i = 0; i < buf.length; i += 1) {
this._buffer8[i] = buf.charCodeAt(i);
}
}
public end(raw: boolean = false) {
const bufLen = this._bufferLength;
const buf8 = this._buffer8;
const buf32 = this._buffer32;
const i = (bufLen >> 2) + 1;
let dataBitsLen;
this._dataLength += bufLen;
buf8[bufLen] = 0x80;
buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0;
buf32.set(Md5.buffer32Identity.subarray(i), i);
if (bufLen > 55) {
Md5._md5cycle(this._state, buf32);
buf32.set(Md5.buffer32Identity);
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
dataBitsLen = this._dataLength * 8;
if (dataBitsLen <= 0xFFFFFFFF) {
buf32[14] = dataBitsLen;
} else {
const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/);
if (matches === null) {
return;
}
const lo = parseInt(matches[2], 16);
const hi = parseInt(matches[1], 16) || 0;
buf32[14] = lo;
buf32[15] = hi;
}
Md5._md5cycle(this._state, buf32);
return raw ? this._state : Md5._hex(this._state);
}
}

View File

@ -26,24 +26,25 @@ import {RequestManager} from "../imageknife/requestmanage/RequestManager"
import {NONE} from "../cache/diskstrategy/enum/NONE" import {NONE} from "../cache/diskstrategy/enum/NONE"
import {FileTypeUtil} from '../imageknife/utils/FileTypeUtil' import {FileTypeUtil} from '../imageknife/utils/FileTypeUtil'
import {DownloadClient} from '../imageknife/networkmanage/DownloadClient' import {DownloadClient} from '../imageknife/networkmanage/DownloadClient'
import type {IDataFetch} from '../imageknife/networkmanage/IDataFetch' import {IDataFetch} from '../imageknife/networkmanage/IDataFetch'
import {ParseResClient} from '../imageknife/resourcemanage/ParseResClient' import {ParseResClient} from '../imageknife/resourcemanage/ParseResClient'
import type {IResourceFetch} from '../imageknife/resourcemanage/IResourceFetch' import {IResourceFetch} from '../imageknife/resourcemanage/IResourceFetch'
import {ImageKnifeData,ImageKnifeType} from '../imageknife/ImageKnifeData' import {ImageKnifeData,ImageKnifeType} from '../imageknife/ImageKnifeData'
import {FileUtils} from '../cache/FileUtils' import {ImageKnifeGlobal} from '../imageknife/ImageKnifeGlobal'
import {FileReader} from '../cache/FileReader'
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import {CompressBuilder} from "../imageknife/compress/CompressBuilder" import {CompressBuilder} from "../imageknife/compress/CompressBuilder"
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle' import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
import {LogUtil} from '../imageknife/utils/LogUtil' import {LogUtil} from '../imageknife/utils/LogUtil'
import worker from '@ohos.worker'
import common from '@ohos.app.ability.common'
export class ImageKnife { export class ImageKnife {
static readonly SEPARATOR: string = '/' static readonly SEPARATOR: string = '/'
private imageKnifeContext;
private memoryCache: LruCache<string, any>; private memoryCache: LruCache<string, ImageKnifeData>;
private diskMemoryCache: DiskLruCache; private diskMemoryCache: DiskLruCache;
private dataFetch: IDataFetch; private dataFetch: IDataFetch;
private resourceFetch: IResourceFetch; private resourceFetch: IResourceFetch<ArrayBuffer>;
private filesPath: string = ""; // data/data/包名/files目录 private filesPath: string = ""; // data/data/包名/files目录
@ -54,24 +55,25 @@ export class ImageKnife {
private diskCacheFolder: string = "ImageKnifeDiskCache" private diskCacheFolder: string = "ImageKnifeDiskCache"
private defaultListener: AsyncCallback<ImageKnifeData>; // 全局监听器 private defaultListener: AsyncCallback<ImageKnifeData> = {
callback:(err: string, data: ImageKnifeData)=>{return false}
}; // 全局监听器
// gifWorker // gifWorker
private gifWorker; private gifWorker: worker.ThreadWorker|undefined = undefined;
private defaultLifeCycle: IDrawLifeCycle; private defaultLifeCycle: IDrawLifeCycle|undefined = undefined;
// 开发者可配置全局缓存 // 开发者可配置全局缓存
private engineKeyImpl: EngineKeyInterface; private engineKeyImpl: EngineKeyInterface;
private constructor(imgCtx) { private constructor() {
this.imageKnifeContext = imgCtx;
// 构造方法传入size 为保存文件个数 // 构造方法传入size 为保存文件个数
this.memoryCache = new LruCache<string, any>(100); this.memoryCache = new LruCache<string, ImageKnifeData>(100);
// 创建disk缓存 传入的size 为多少比特 比如20KB 传入20*1024 // 创建disk缓存 传入的size 为多少比特 比如20KB 传入20*1024
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext); this.diskMemoryCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext());
// 创建网络下载能力 // 创建网络下载能力
this.dataFetch = new DownloadClient(); this.dataFetch = new DownloadClient();
@ -80,7 +82,7 @@ export class ImageKnife {
this.resourceFetch = new ParseResClient(); this.resourceFetch = new ParseResClient();
// 初始化本地 文件保存 // 初始化本地 文件保存
this.filesPath = this.imageKnifeContext.filesDir; this.filesPath = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
this.runningRequest = new Array(); this.runningRequest = new Array();
this.pendingRequest = new Array(); this.pendingRequest = new Array();
@ -91,15 +93,24 @@ export class ImageKnife {
this.engineKeyImpl = new EngineKeyFactories(); this.engineKeyImpl = new EngineKeyFactories();
} }
getMemoryCache(): LruCache<string, any>{ getMemoryCache(): LruCache<string, ImageKnifeData>{
return this.memoryCache; return this.memoryCache;
} }
public static with(context): ImageKnife{ public static with(context:Object): ImageKnifeGlobal{
if (!this.sInstance) { // 存入hapContext;
this.sInstance = new ImageKnife(context); let global:ImageKnifeGlobal = ImageKnifeGlobal.getInstance();
global.setHapContext(context)
// 初始化ImageKnife
if (!ImageKnife.sInstance) {
ImageKnife.sInstance = new ImageKnife();
} }
return this.sInstance;
// 存入ImageKnife
global.setImageKnife(ImageKnife.sInstance)
return global;
} }
getDiskMemoryCache(): DiskLruCache{ getDiskMemoryCache(): DiskLruCache{
@ -115,10 +126,10 @@ export class ImageKnife {
} }
getImageKnifeContext() { getImageKnifeContext() {
return this.imageKnifeContext; return ImageKnifeGlobal.getInstance().getHapContext();
} }
setMemoryCache(lrucache: LruCache<string, any>) { setMemoryCache(lrucache: LruCache<string, ImageKnifeData>) {
this.memoryCache = lrucache; this.memoryCache = lrucache;
} }
@ -126,7 +137,7 @@ export class ImageKnife {
return this.defaultListener; return this.defaultListener;
} }
setGifWorker(worker){ setGifWorker(worker:worker.ThreadWorker){
this.gifWorker = worker this.gifWorker = worker
} }
getGifWorker(){ getGifWorker(){
@ -158,10 +169,10 @@ export class ImageKnife {
// 替代原来的LruCache // 替代原来的LruCache
public replaceLruCache(size:number){ public replaceLruCache(size:number){
if(this.memoryCache.map.size() <= 0) { if(this.memoryCache.map.size() <= 0) {
this.memoryCache = new LruCache<string, any>(size); this.memoryCache = new LruCache<string, ImageKnifeData>(size);
}else{ }else{
let newLruCache = new LruCache<string, any>(size); let newLruCache = new LruCache<string, ImageKnifeData>(size);
this.memoryCache.foreachLruCache(function (value, key, map) { this.memoryCache.foreachLruCache( (value:ImageKnifeData, key:string, map:Object)=> {
newLruCache.put(key, value); newLruCache.put(key, value);
}) })
this.memoryCache = newLruCache; this.memoryCache = newLruCache;
@ -175,10 +186,10 @@ export class ImageKnife {
// 替代原来的DiskLruCache // 替代原来的DiskLruCache
public replaceDiskLruCache(size:number) { public replaceDiskLruCache(size:number) {
if (this.diskMemoryCache.getCacheMap().size() <= 0) { if (this.diskMemoryCache.getCacheMap().size() <= 0) {
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext, size); this.diskMemoryCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext(), size);
} else { } else {
let newDiskLruCache = DiskLruCache.create(this.imageKnifeContext, size); let newDiskLruCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext(), size);
this.diskMemoryCache.foreachDiskLruCache(function (value, key, map) { this.diskMemoryCache.foreachDiskLruCache( (value:string|ArrayBuffer, key:string, map:Object)=> {
newDiskLruCache.set(key, value); newDiskLruCache.set(key, value);
}) })
this.diskMemoryCache = newDiskLruCache; this.diskMemoryCache = newDiskLruCache;
@ -186,7 +197,7 @@ export class ImageKnife {
} }
// 预加载 resource资源一级缓存string资源实现二级缓存 // 预加载 resource资源一级缓存string资源实现二级缓存
preload(request: RequestOption) { preload(request: RequestOption):void {
// 每个request 公共信息补充 // 每个request 公共信息补充
request.setFilesPath(this.filesPath); request.setFilesPath(this.filesPath);
@ -194,7 +205,7 @@ export class ImageKnife {
} }
// 正常加载 // 正常加载
call(request: RequestOption) { call(request: RequestOption):void {
// 添加全局监听 // 添加全局监听
if(this.defaultListener) { if(this.defaultListener) {
request.addListener(this.defaultListener) request.addListener(this.defaultListener)
@ -220,10 +231,10 @@ export class ImageKnife {
} }
loadResources(request: RequestOption) { loadResources(request: RequestOption) {
let factories; let factories:EngineKeyInterface;
let cacheKey; let cacheKey:string;
let transferKey; let transferKey:string;
let dataKey; let dataKey:string;
if(this.engineKeyImpl){ if(this.engineKeyImpl){
factories = this.engineKeyImpl; factories = this.engineKeyImpl;
}else { }else {
@ -324,7 +335,7 @@ export class ImageKnife {
// 加载下一个key的请求 // 加载下一个key的请求
loadNextPending(request) { loadNextPending(request:RequestOption) {
// 首先寻找被移除key相同的request // 首先寻找被移除key相同的request
let index = -1; let index = -1;
for (let i = 0; i < this.pendingRequest.length; i++) { for (let i = 0; i < this.pendingRequest.length; i++) {
@ -415,7 +426,7 @@ export class ImageKnife {
return false; return false;
} }
parseSource(request: RequestOption) { parseSource(request: RequestOption):void {
if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') { if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, request.loadSrc as PixelMap) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, request.loadSrc as PixelMap)
request.loadComplete(imageKnifeData); request.loadComplete(imageKnifeData);

View File

@ -14,13 +14,14 @@
*/ */
import { ImageKnifeOption } from '../imageknife/ImageKnifeOption' import { ImageKnifeOption } from '../imageknife/ImageKnifeOption'
import { ImageKnifeGlobal } from '../imageknife/ImageKnifeGlobal'
import { TransformType } from '../imageknife/transform/TransformType' import { TransformType } from '../imageknife/transform/TransformType'
import { RequestOption } from '../imageknife/RequestOption' import { RequestOption, Size } from '../imageknife/RequestOption'
import { ImageKnifeData } from '../imageknife/ImageKnifeData' import { ImageKnifeData } from '../imageknife/ImageKnifeData'
import { GIFFrame } from '../imageknife/utils/gif/GIFFrame' import { GIFFrame } from '../imageknife/utils/gif/GIFFrame'
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle' import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
import { LogUtil } from '../imageknife/utils/LogUtil' import { LogUtil } from '../imageknife/utils/LogUtil'
import { BusinessError } from '@ohos.base'
@Component @Component
export struct ImageKnifeComponent { export struct ImageKnifeComponent {
@ -78,7 +79,8 @@ export struct ImageKnifeComponent {
} }
private canvasHasReady: boolean = false; private canvasHasReady: boolean = false;
private firstDrawFlag: boolean = false; private firstDrawFlag: boolean = false;
private onReadyNext: () => void = undefined private onReadyNext?: (data:ImageKnifeData|number|undefined) => void = undefined
private onReadyNextData:ImageKnifeData|number|undefined = undefined
build() { build() {
Canvas(this.context) Canvas(this.context)
@ -104,11 +106,12 @@ export struct ImageKnifeComponent {
this.canvasHasReady = true; this.canvasHasReady = true;
if (this.onReadyNext) { if (this.onReadyNext) {
LogUtil.log('ImageKnifeComponent onReadyNext is running!') LogUtil.log('ImageKnifeComponent onReadyNext is running!')
this.onReadyNext() this.onReadyNext(this.onReadyNextData)
this.onReadyNext = undefined; this.onReadyNext = undefined;
this.onReadyNextData = undefined
} }
}) })
.onClick((event: ClickEvent) => { .onClick((event?: ClickEvent) => {
// 需要将点击事件回传 // 需要将点击事件回传
if (this.imageKnifeOption.onClick) { if (this.imageKnifeOption.onClick) {
this.imageKnifeOption.onClick(event) this.imageKnifeOption.onClick(event)
@ -152,24 +155,26 @@ export struct ImageKnifeComponent {
* 待onReady执行的时候执行 * 待onReady执行的时候执行
* @param nextFunction 下一个方法 * @param nextFunction 下一个方法
*/ */
runNextFunction(nextFunction: () => void) { runNextFunction(nextFunction: (data:ImageKnifeData|number|undefined) => void,data:ImageKnifeData|number|undefined) {
if (!this.canvasHasReady) { if (!this.canvasHasReady) {
// canvas未初始化完成 // canvas未初始化完成
this.onReadyNext = nextFunction; this.onReadyNext = nextFunction;
this.onReadyNextData = data;
} else { } else {
nextFunction(); nextFunction(data);
} }
} }
configNecessary(request: RequestOption) { configNecessary(request: RequestOption) {
request.load(this.imageKnifeOption.loadSrc) request.load(this.imageKnifeOption.loadSrc)
.addListener((err, data) => { .addListener({ callback: (err:BusinessError|string, data:ImageKnifeData) => {
LogUtil.log('ImageKnifeComponent request.load callback') LogUtil.log('ImageKnifeComponent request.load callback')
this.runNextFunction(this.displayMainSource.bind(this, data)); this.runNextFunction(this.displayMainSource,data);
return false; return false;
}
}) })
let realSize = { let realSize:Size = {
width: this.currentWidth, width: this.currentWidth,
height: this.currentHeight height: this.currentHeight
} }
@ -196,23 +201,23 @@ export struct ImageKnifeComponent {
configDisplay(request: RequestOption) { configDisplay(request: RequestOption) {
if (this.imageKnifeOption.placeholderSrc) { if (this.imageKnifeOption.placeholderSrc) {
request.placeholder(this.imageKnifeOption.placeholderSrc, (data) => { request.placeholder(this.imageKnifeOption.placeholderSrc, {asyncSuccess:(data:ImageKnifeData) => {
LogUtil.log('ImageKnifeComponent request.placeholder callback') LogUtil.log('ImageKnifeComponent request.placeholder callback')
this.runNextFunction(this.displayPlaceholder.bind(this, data)) this.runNextFunction(this.displayPlaceholder,data)
}
}) })
} }
if (this.imageKnifeOption.thumbSizeMultiplier) { if (this.imageKnifeOption.thumbSizeMultiplier) {
request.thumbnail(this.imageKnifeOption.thumbSizeMultiplier, (data) => { request.thumbnail(this.imageKnifeOption.thumbSizeMultiplier, {asyncSuccess:(data:ImageKnifeData) => {
LogUtil.log('ImageKnifeComponent request.thumbnail callback') LogUtil.log('ImageKnifeComponent request.thumbnail callback')
this.runNextFunction(this.displayThumbSizeMultiplier.bind(this, data)) this.runNextFunction(this.displayThumbSizeMultiplier,data)
}, this.imageKnifeOption.thumbSizeDelay) }}, this.imageKnifeOption.thumbSizeDelay)
} }
if (this.imageKnifeOption.errorholderSrc) { if (this.imageKnifeOption.errorholderSrc) {
request.errorholder(this.imageKnifeOption.errorholderSrc, (data) => { request.errorholder(this.imageKnifeOption.errorholderSrc, {asyncSuccess:(data:ImageKnifeData) => {
LogUtil.log('ImageKnifeComponent request.errorholder callback') LogUtil.log('ImageKnifeComponent request.errorholder callback')
this.runNextFunction(this.displayErrorholder.bind(this, data)) this.runNextFunction(this.displayErrorholder,data)
}) }})
} }
if (this.imageKnifeOption.transform) { if (this.imageKnifeOption.transform) {
@ -230,19 +235,19 @@ export struct ImageKnifeComponent {
if (this.imageKnifeOption.displayProgress) { if (this.imageKnifeOption.displayProgress) {
request.addProgressListener((percentValue: number) => { request.addProgressListener({asyncSuccess:(percentValue: number) => {
// 如果进度条百分比 未展示大小,展示其动画 // 如果进度条百分比 未展示大小,展示其动画
LogUtil.log('ImageKnifeComponent request.addProgressListener callback') LogUtil.log('ImageKnifeComponent request.addProgressListener callback')
this.runNextFunction(this.displayProgress.bind(this, percentValue)) this.runNextFunction(this.displayProgress,percentValue)
}) }})
} }
if (this.imageKnifeOption.retryholderSrc) { if (this.imageKnifeOption.retryholderSrc) {
request.retryholder(this.imageKnifeOption.retryholderSrc, (data) => { request.retryholder(this.imageKnifeOption.retryholderSrc,{asyncSuccess: (data:ImageKnifeData) => {
LogUtil.log('ImageKnifeComponent request.retryholder callback') LogUtil.log('ImageKnifeComponent request.retryholder callback')
this.hasDisplayRetryholder = true this.hasDisplayRetryholder = true
this.runNextFunction(this.displayRetryholder.bind(this, data)) this.runNextFunction(this.displayRetryholder,data)
}) }})
} }
} }
@ -271,108 +276,140 @@ export struct ImageKnifeComponent {
this.configCacheStrategy(request); this.configCacheStrategy(request);
this.configDisplay(request); this.configDisplay(request);
this.configRenderGpu(request); this.configRenderGpu(request);
globalThis.ImageKnife.call(request); if(ImageKnifeGlobal.getInstance().getImageKnife()!=undefined) {
ImageKnifeGlobal.getInstance().getImageKnife()?.call(request);
}
} }
displayPlaceholder(data: ImageKnifeData) { displayPlaceholder = (data: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayPlaceholder', this.context, data, this.imageKnifeOption, if(data == undefined || typeof data == 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayPlaceholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayPlaceholder', this.context, data, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayPlaceholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayPlaceholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if(this.defaultLifeCycle.displayPlaceholder != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayPlaceholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
} }
displayProgress(percent: number) { displayProgress = (percent: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayProgress', this.context, percent, this.imageKnifeOption, if(typeof percent != 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayProgress', this.context, percent, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayProgress', this.context, percent, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayProgress', this.context, percent, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayProgress(this.context, percent, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if(this.defaultLifeCycle.displayProgress != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayProgress(this.context, percent, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
} }
displayThumbSizeMultiplier(data: ImageKnifeData) { displayThumbSizeMultiplier = (data: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption, if(data == undefined || typeof data == 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayThumbSizeMultiplier(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if(this.defaultLifeCycle.displayThumbSizeMultiplier != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayThumbSizeMultiplier(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
} }
displayMainSource(data: ImageKnifeData) { displayMainSource = (data: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayMainSource', this.context, data, this.imageKnifeOption, if(data == undefined || typeof data == 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayMainSource', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayMainSource', this.context, data, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayMainSource', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayMainSource(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if(this.defaultLifeCycle.displayMainSource != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayMainSource(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
} }
displayRetryholder(data: ImageKnifeData) { displayRetryholder = (data: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayRetryholder', this.context, data, this.imageKnifeOption, if(data == undefined || typeof data == 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayRetryholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayRetryholder', this.context, data, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayRetryholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayRetryholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if( this.defaultLifeCycle.displayRetryholder != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayRetryholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
} }
displayErrorholder(data: ImageKnifeData) { displayErrorholder = (data: ImageKnifeData|number|undefined)=> {
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayErrorholder', this.context, data, this.imageKnifeOption, if(data == undefined || typeof data == 'number'){
return
}
if (!this.drawLifeCycleHasConsumed( 'displayErrorholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },this.imageKnifeOption.drawLifeCycle)) {
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayErrorholder', this.context, data, this.imageKnifeOption, if (!this.drawLifeCycleHasConsumed( 'displayErrorholder', this.context, data, this.imageKnifeOption,
this.currentWidth, this.currentHeight, (gifTimeId) => { this.currentWidth, this.currentHeight, (gifTimeId) => {
this.setGifTimeId(gifTimeId) this.setGifTimeId(gifTimeId)
})) { },(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
this.defaultLifeCycle.displayErrorholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => { if(this.defaultLifeCycle.displayErrorholder != undefined) {
this.setGifTimeId(gifTimeId) this.defaultLifeCycle.displayErrorholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
}) this.setGifTimeId(gifTimeId)
})
}
} }
} }
@ -381,13 +418,13 @@ export struct ImageKnifeComponent {
drawPlaceholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { drawPlaceholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
LogUtil.log('ImageKnifeComponent default drawPlaceholder start!') LogUtil.log('ImageKnifeComponent default drawPlaceholder start!')
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height) LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height)
let scaleType = (typeof imageKnifeOption.placeholderScaleType == 'number') ? imageKnifeOption.placeholderScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.placeholderScaleType == 'number') ? imageKnifeOption.placeholderScaleType : ScaleType.FIT_CENTER
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0)
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawPlaceholder end!') LogUtil.log('ImageKnifeComponent default drawPlaceholder end!')
}) })
@ -436,13 +473,13 @@ export struct ImageKnifeComponent {
drawThumbSizeMultiplier(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { drawThumbSizeMultiplier(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
LogUtil.log('ImageKnifeComponent default drawThumbSizeMultiplier start!') LogUtil.log('ImageKnifeComponent default drawThumbSizeMultiplier start!')
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height) LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height)
let scaleType = (typeof imageKnifeOption.thumbSizeMultiplierScaleType == 'number') ? imageKnifeOption.thumbSizeMultiplierScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.thumbSizeMultiplierScaleType == 'number') ? imageKnifeOption.thumbSizeMultiplierScaleType : ScaleType.FIT_CENTER
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0)
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawThumbSizeMultiplier end!') LogUtil.log('ImageKnifeComponent default drawThumbSizeMultiplier end!')
}) })
@ -451,13 +488,13 @@ export struct ImageKnifeComponent {
drawMainSource(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { drawMainSource(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
LogUtil.log('ImageKnifeComponent default drawMainSource start!') LogUtil.log('ImageKnifeComponent default drawMainSource start!')
if (data.isPixelMap()) { if (data.isPixelMap()) {
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER
LogUtil.log('ImageKnifeComponent imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType) LogUtil.log('ImageKnifeComponent imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType)
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0)
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawMainSource end!') LogUtil.log('ImageKnifeComponent default drawMainSource end!')
}) })
@ -468,13 +505,13 @@ export struct ImageKnifeComponent {
drawRetryholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { drawRetryholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
LogUtil.log('ImageKnifeComponent default drawRetryholder start!') LogUtil.log('ImageKnifeComponent default drawRetryholder start!')
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
LogUtil.log('ImageKnifeComponent imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height) LogUtil.log('ImageKnifeComponent imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height)
let scaleType = (typeof imageKnifeOption.retryholderScaleType == 'number') ? imageKnifeOption.retryholderScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.retryholderScaleType == 'number') ? imageKnifeOption.retryholderScaleType : ScaleType.FIT_CENTER
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0)
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawRetryholder end!') LogUtil.log('ImageKnifeComponent default drawRetryholder end!')
}) })
@ -482,56 +519,56 @@ export struct ImageKnifeComponent {
drawErrorholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { drawErrorholder(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
LogUtil.log('ImageKnifeComponent default drawErrorholder start!') LogUtil.log('ImageKnifeComponent default drawErrorholder start!')
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height) LogUtil.log('ImageKnifeComponent imageinfo widht =' + imageInfo.size.width + ' height=' + imageInfo.size.height)
let scaleType = (typeof imageKnifeOption.errorholderSrcScaleType == 'number') ? imageKnifeOption.errorholderSrcScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.errorholderSrcScaleType == 'number') ? imageKnifeOption.errorholderSrcScaleType : ScaleType.FIT_CENTER
context.save(); context.save();
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0)
context.restore(); context.restore();
LogUtil.log('ImageKnifeComponent default drawErrorholder end!') LogUtil.log('ImageKnifeComponent default drawErrorholder end!')
}) })
} }
requestAddTransform(request: RequestOption) { requestAddTransform(request: RequestOption) {
if (TransformType.BlurTransformation == this.imageKnifeOption.transform.transformType) { if (TransformType.BlurTransformation == this.imageKnifeOption.transform?.transformType) {
request.blur(this.imageKnifeOption.transform.blur) request.blur(this.imageKnifeOption.transform?.blur)
} else if (TransformType.BrightnessFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.BrightnessFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.brightnessFilter(this.imageKnifeOption.transform.brightnessFilter) request.brightnessFilter(this.imageKnifeOption.transform?.brightnessFilter)
} else if (TransformType.ContrastFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.ContrastFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.contrastFilter(this.imageKnifeOption.transform.contrastFilter) request.contrastFilter(this.imageKnifeOption.transform?.contrastFilter)
} else if (TransformType.CropCircleTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CropCircleTransformation == this.imageKnifeOption.transform?.transformType) {
request.cropCircle() request.cropCircle()
} else if (TransformType.CropCircleWithBorderTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CropCircleWithBorderTransformation == this.imageKnifeOption.transform?.transformType) {
request.cropCircleWithBorder(this.imageKnifeOption.transform.cropCircleWithBorder.border, this.imageKnifeOption.transform.cropCircleWithBorder.obj) request.cropCircleWithBorder(this.imageKnifeOption.transform?.cropCircleWithBorder?.border, this.imageKnifeOption.transform?.cropCircleWithBorder?.obj)
} else if (TransformType.CropSquareTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CropSquareTransformation == this.imageKnifeOption.transform?.transformType) {
request.cropSquare() request.cropSquare()
} else if (TransformType.CropTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CropTransformation == this.imageKnifeOption.transform?.transformType) {
request.crop(this.imageKnifeOption.transform.crop.width, this.imageKnifeOption.transform.crop.height, this.imageKnifeOption.transform.crop.cropType) request.crop(this.imageKnifeOption.transform?.crop?.width, this.imageKnifeOption.transform?.crop?.height, this.imageKnifeOption.transform?.crop?.cropType)
} else if (TransformType.GrayscaleTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.GrayscaleTransformation == this.imageKnifeOption.transform?.transformType) {
request.grayscale() request.grayscale()
} else if (TransformType.InvertFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.InvertFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.invertFilter() request.invertFilter()
} else if (TransformType.MaskTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.MaskTransformation == this.imageKnifeOption.transform?.transformType) {
request.mask(this.imageKnifeOption.transform.mask) request.mask(this.imageKnifeOption.transform?.mask)
} else if (TransformType.PixelationFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.PixelationFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.pixelationFilter(this.imageKnifeOption.transform.pixelationFilter) request.pixelationFilter(this.imageKnifeOption.transform?.pixelationFilter)
} else if (TransformType.RotateImageTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.RotateImageTransformation == this.imageKnifeOption.transform?.transformType) {
request.rotateImage(this.imageKnifeOption.transform.rotateImage) request.rotateImage(this.imageKnifeOption.transform?.rotateImage)
} else if (TransformType.RoundedCornersTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.RoundedCornersTransformation == this.imageKnifeOption.transform?.transformType) {
request.roundedCorners(this.imageKnifeOption.transform.roundedCorners) request.roundedCorners(this.imageKnifeOption.transform?.roundedCorners)
} else if (TransformType.SepiaFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.SepiaFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.sepiaFilter() request.sepiaFilter()
} else if (TransformType.SketchFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.SketchFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.sketchFilter() request.sketchFilter()
} else if (TransformType.SwirlFilterTransformation == this.imageKnifeOption.transform.transformType) { } else if (TransformType.SwirlFilterTransformation == this.imageKnifeOption.transform?.transformType) {
request.swirlFilter(this.imageKnifeOption.transform.swirlFilter) request.swirlFilter(this.imageKnifeOption.transform?.swirlFilter)
} else if (TransformType.CenterCrop == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CenterCrop == this.imageKnifeOption.transform?.transformType) {
request.centerCrop() request.centerCrop()
} else if (TransformType.CenterInside == this.imageKnifeOption.transform.transformType) { } else if (TransformType.CenterInside == this.imageKnifeOption.transform?.transformType) {
request.centerInside() request.centerInside()
} else if (TransformType.FitCenter == this.imageKnifeOption.transform.transformType) { } else if (TransformType.FitCenter == this.imageKnifeOption.transform?.transformType) {
request.fitCenter() request.fitCenter()
} }
} }
@ -560,17 +597,17 @@ export struct ImageKnifeComponent {
this.gifTimerId = timeId; this.gifTimerId = timeId;
} }
private drawLifeCycleHasConsumed<K, T>(drawLifeCycle: IDrawLifeCycle, methodName: string, private drawLifeCycleHasConsumed<K, T>( methodName: string,
context: CanvasRenderingContext2D, data: K, imageKnifeOption: T, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void context: CanvasRenderingContext2D, data: K, imageKnifeOption: T, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void,drawLifeCycle?: IDrawLifeCycle
) { ):boolean {
if (drawLifeCycle && drawLifeCycle[methodName]) { if (drawLifeCycle && (drawLifeCycle as Record<string,Function>)[methodName]) {
return drawLifeCycle[methodName](context, data, imageKnifeOption, compWidth, compHeight, setGifTimeId) return (drawLifeCycle as Record<string,Function>)[methodName](context, data, imageKnifeOption, compWidth, compHeight, setGifTimeId)
} }
return false; return false;
} }
private drawGIFFrame(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) { private drawGIFFrame(context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) {
let frames = data.drawGIFFrame.imageGIFFrames as GIFFrame[] let frames = data.drawGIFFrame?.imageGIFFrames as GIFFrame[]
LogUtil.log('ImageKnifeComponent gifFrameLength =' + frames.length); LogUtil.log('ImageKnifeComponent gifFrameLength =' + frames.length);
if (imageKnifeOption.gif && (typeof (imageKnifeOption.gif.seekTo) == 'number') && imageKnifeOption.gif.seekTo >= 0) { if (imageKnifeOption.gif && (typeof (imageKnifeOption.gif.seekTo) == 'number') && imageKnifeOption.gif.seekTo >= 0) {
this.autoPlay = false; this.autoPlay = false;
@ -579,7 +616,14 @@ export struct ImageKnifeComponent {
} else { } else {
this.autoPlay = true this.autoPlay = true
context.clearRect(0, 0, compWidth, compHeight) context.clearRect(0, 0, compWidth, compHeight)
this.renderFrames.bind(this, frames, 0, context, compWidth, compHeight)()
this.renderFrames_frames = frames
this.renderFrames_index = 0
this.renderFrames_context = context
this.renderFrames_compWidth = compWidth
this.renderFrames_compHeight = compHeight
this.renderFrames()
} }
} }
@ -594,22 +638,30 @@ export struct ImageKnifeComponent {
* 绘制直接到第几帧方法由于gif非第一帧数据可能是不全的这里采用逐帧渲染的方式来绘制保证图像的完整性 * 绘制直接到第几帧方法由于gif非第一帧数据可能是不全的这里采用逐帧渲染的方式来绘制保证图像的完整性
*/ */
private drawSeekToFrame(frames: GIFFrame[], context: CanvasRenderingContext2D, compWidth: number, compHeight: number) { private drawSeekToFrame(frames: GIFFrame[], context: CanvasRenderingContext2D, compWidth: number, compHeight: number) {
for (let i = 0; i < this.imageKnifeOption.gif.seekTo; i++) { if(this.imageKnifeOption.gif != undefined && this.imageKnifeOption.gif.seekTo != undefined) {
this.drawFrame(frames, i, context, compWidth, compHeight); for (let i = 0; i < this.imageKnifeOption.gif.seekTo; i++) {
this.drawFrame(frames, i, context, compWidth, compHeight);
}
} }
} }
private renderFrames(frames: GIFFrame[], index: number, context: CanvasRenderingContext2D, compWidth: number, compHeight: number) { renderFrames_frames: GIFFrame[] | undefined = undefined
LogUtil.log('ImageKnifeComponent renderFrames frames length =' + frames.length) renderFrames_index: number = 0;
renderFrames_context: CanvasRenderingContext2D | undefined = undefined;
renderFrames_compWidth: number = 0;
renderFrames_compHeight: number = 0
renderFrames = ()=> {
LogUtil.log('ImageKnifeComponent renderFrames frames length =' + this.renderFrames_frames?.length)
let start = new Date().getTime(); let start = new Date().getTime();
if (index === 0) { if (this.renderFrames_index === 0) {
// 如果是第一帧,我们只从开始渲染前记录时间 // 如果是第一帧,我们只从开始渲染前记录时间
this.startGifLoopTime = start; this.startGifLoopTime = start;
} }
// draw Frame // draw Frame
this.drawFrame(frames, index, context, compWidth, compHeight); this.drawFrame(this.renderFrames_frames, this.renderFrames_index, this.renderFrames_context, this.renderFrames_compWidth, this.renderFrames_compHeight);
//如果gif动图只有一帧的情况下不进行后面代码的逐帧绘制循环 //如果gif动图只有一帧的情况下不进行后面代码的逐帧绘制循环
if (frames.length <= 1) { if (this.renderFrames_frames != undefined && this.renderFrames_frames.length <= 1) {
return return
} }
@ -620,9 +672,12 @@ export struct ImageKnifeComponent {
if (this.autoPlay) { if (this.autoPlay) {
// 理论上该帧在屏幕上保留的时间 // 理论上该帧在屏幕上保留的时间
let stayTime = frames[index].delay; let stayTime:number= 0
if(this.renderFrames_frames != undefined) {
stayTime = this.renderFrames_frames[this.renderFrames_index].delay;
}
if (this.imageKnifeOption.gif && this.imageKnifeOption.gif.speedFactory) { if (this.imageKnifeOption.gif && this.imageKnifeOption.gif.speedFactory) {
stayTime = frames[index].delay / (this.imageKnifeOption.gif.speedFactory * 1.0); stayTime = stayTime / (this.imageKnifeOption.gif?.speedFactory * 1.0);
} }
// 减去程序执行消耗,剩余的准确延迟时间 // 减去程序执行消耗,剩余的准确延迟时间
let delayTime = Math.max(0, Math.floor(stayTime - diff)); let delayTime = Math.max(0, Math.floor(stayTime - diff));
@ -634,21 +689,23 @@ export struct ImageKnifeComponent {
// 整个gif累计的时长; // 整个gif累计的时长;
this.gifLoopDuration += loopStayTime; this.gifLoopDuration += loopStayTime;
// 返回gif一次循环结束回调并且把当前循环的时间给出 // 返回gif一次循环结束回调并且把当前循环的时间给出
if (index === (frames.length - 1) && this.imageKnifeOption.gif && this.imageKnifeOption.gif.loopFinish) { if (this.renderFrames_frames != undefined && this.renderFrames_index === (this.renderFrames_frames.length - 1) && this.imageKnifeOption.gif != undefined && this.imageKnifeOption.gif?.loopFinish) {
this.imageKnifeOption.gif.loopFinish(this.gifLoopDuration) this.imageKnifeOption.gif.loopFinish(this.gifLoopDuration)
this.gifLoopDuration = 0; this.gifLoopDuration = 0;
} }
// update the frame index // update the frame index
index++ this.renderFrames_index++
if (index >= frames.length) { if (this.renderFrames_frames != undefined && this.renderFrames_index >= this.renderFrames_frames.length) {
index = 0; this.renderFrames_index = 0;
} }
// @ts-ignore this.gifTimerId = setTimeout(this.renderFrames, delayTime)
this.gifTimerId = setTimeout(this.renderFrames.bind(this, frames, index, context, compWidth, compHeight), delayTime)
} }
} }
private drawFrame(frames: GIFFrame[], index: number, context: CanvasRenderingContext2D, compWidth: number, compHeight: number) { private drawFrame(frames: GIFFrame[]|undefined, index: number, context: CanvasRenderingContext2D|undefined, compWidth: number, compHeight: number) {
if(frames == undefined){
return
}
// get current frame // get current frame
let frame = frames[index]; let frame = frames[index];
if (!frame || !context) { if (!frame || !context) {
@ -676,7 +733,8 @@ export struct ImageKnifeComponent {
disposal = preFrame.disposalType disposal = preFrame.disposalType
if (disposal === FrameDisposalType.DISPOSE_RestoreBackground) { if (disposal === FrameDisposalType.DISPOSE_RestoreBackground) {
const {left, top } = preFrame.dims; let left:number = preFrame.dims.left;
let top:number = preFrame.dims.top
context.clearRect(left, top, compWidth, compHeight); context.clearRect(left, top, compWidth, compHeight);
} }
} else { } else {
@ -731,7 +789,7 @@ export enum ScaleType {
export class ScaleTypeHelper { export class ScaleTypeHelper {
static drawImageWithScaleType(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX: number, imageOffsetY: number) { static drawImageWithScaleType(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | undefined, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX: number, imageOffsetY: number) {
let scaleW = compWidth / imageWidth let scaleW = compWidth / imageWidth
let scaleH = compHeight / imageHeight let scaleH = compHeight / imageHeight
let minScale = scaleW > scaleH ? scaleH : scaleW let minScale = scaleW > scaleH ? scaleH : scaleW
@ -769,63 +827,73 @@ export class ScaleTypeHelper {
} }
static drawFitStart(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, minScale: number, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawFitStart(context: CanvasRenderingContext2D, source: PixelMap | undefined, minScale: number, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
context.setTransform(minScale, 0, 0, minScale, 0, 0) context.setTransform(minScale, 0, 0, minScale, 0, 0)
let dx = 0 let dx:number = 0
let dy = 0 let dy:number = 0
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) if(source!= undefined) {
context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawFitEnd(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawFitEnd(context: CanvasRenderingContext2D, source: PixelMap | undefined, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
context.setTransform(minScale, 0, 0, minScale, 0, 0) context.setTransform(minScale, 0, 0, minScale, 0, 0)
let dx = (compWidth - imageWidth * minScale) / (minScale * 1.0); let dx:number = (compWidth - imageWidth * minScale) / (minScale * 1.0);
let dy = (compHeight - imageHeight * minScale) / (minScale * 1.0); let dy:number = (compHeight - imageHeight * minScale) / (minScale * 1.0);
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
if(source!= undefined) {
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawFitCenter(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawFitCenter(context: CanvasRenderingContext2D, source: PixelMap | undefined, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
context.setTransform(minScale, 0, 0, minScale, 0, 0) context.setTransform(minScale, 0, 0, minScale, 0, 0)
let dx = (compWidth - imageWidth * minScale) / (minScale * 2.0); let dx:number = (compWidth - imageWidth * minScale) / (minScale * 2.0);
let dy = (compHeight - imageHeight * minScale) / (minScale * 2.0); let dy:number = (compHeight - imageHeight * minScale) / (minScale * 2.0);
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
if(source!= undefined) {
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawCenter(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawCenter(context: CanvasRenderingContext2D, source: PixelMap | undefined, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
let dx = (compWidth - imageWidth) / 2.0; let dx:number = (compWidth - imageWidth) / 2.0;
let dy = (compHeight - imageHeight) / 2.0; let dy:number = (compHeight - imageHeight) / 2.0;
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) if(source!= undefined) {
context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawCenterCrop(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, maxScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawCenterCrop(context: CanvasRenderingContext2D, source: PixelMap | undefined, maxScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
context.setTransform(maxScale, 0, 0, maxScale, 0, 0) context.setTransform(maxScale, 0, 0, maxScale, 0, 0)
let dx = (compWidth - imageWidth * maxScale) / (maxScale * 2.0); let dx:number = (compWidth - imageWidth * maxScale) / (maxScale * 2.0);
let dy = (compHeight - imageHeight * maxScale) / (maxScale * 2.0); let dy:number = (compHeight - imageHeight * maxScale) / (maxScale * 2.0);
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) if(source!= undefined) {
context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawFitXY(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, scaleW: number, scaleH: number, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawFitXY(context: CanvasRenderingContext2D, source: PixelMap | undefined, scaleW: number, scaleH: number, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
context.setTransform(scaleW, 0, 0, scaleH, 0, 0) context.setTransform(scaleW, 0, 0, scaleH, 0, 0)
let dx = 0; let dx:number = 0;
let dy = 0; let dy:number = 0;
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) if(source!= undefined) {
context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
} }
static drawCenterInside(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawCenterInside(context: CanvasRenderingContext2D, source: PixelMap | undefined, minScale: number, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
if (minScale < 1) { if (minScale < 1) {
ScaleTypeHelper.drawFitCenter(context, source, minScale, imageWidth, imageHeight, compWidth, compHeight, imageOffsetX, imageOffsetY) ScaleTypeHelper.drawFitCenter(context, source, minScale, imageWidth, imageHeight, compWidth, compHeight, imageOffsetX, imageOffsetY)
} else { } else {
@ -833,13 +901,15 @@ export class ScaleTypeHelper {
} }
} }
static drawNone(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) { static drawNone(context: CanvasRenderingContext2D, source: PixelMap | undefined, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
let dx = 0; let dx:number = 0;
let dy = 0; let dy:number = 0;
let dw = imageWidth; let dw:number = imageWidth;
let dh = imageHeight; let dh:number = imageHeight;
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY) if(source!= undefined) {
} context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
}
}
} }

View File

@ -22,19 +22,19 @@ export enum ImageKnifeType {
} }
export class DrawPixelMap { export class DrawPixelMap {
imagePixelMap: PixelMap imagePixelMap: PixelMap | undefined = undefined
} }
export class DrawString { export class DrawString {
imageString: string imageString: string | undefined = undefined
} }
export class DrawResource { export class DrawResource {
imageResource: Resource imageResource: Resource | undefined = undefined
} }
export class DrawGIFFrame { export class DrawGIFFrame {
imageGIFFrames: GIFFrame[] imageGIFFrames: GIFFrame[] | undefined = undefined
} }
export class ImageKnifeData { export class ImageKnifeData {
@ -47,11 +47,11 @@ export class ImageKnifeData {
waitSaveDisk = false; waitSaveDisk = false;
imageKnifeType: ImageKnifeType; imageKnifeType: ImageKnifeType | undefined = undefined;
drawPixelMap: DrawPixelMap; drawPixelMap: DrawPixelMap | undefined = undefined;
drawGIFFrame: DrawGIFFrame; drawGIFFrame: DrawGIFFrame | undefined = undefined;
drawResource: DrawResource; drawResource: DrawResource | undefined = undefined;
drawString: DrawString; drawString: DrawString | undefined = undefined;
static createImagePixelMap(type: ImageKnifeType, value: PixelMap) { static createImagePixelMap(type: ImageKnifeType, value: PixelMap) {
let data = new ImageKnifeData(); let data = new ImageKnifeData();

View File

@ -26,10 +26,10 @@ export class ImageKnifeDrawFactory{
* @param colorString 例如 "#FF00FF" * @param colorString 例如 "#FF00FF"
*/ */
public static createOvalLifeCycle(borderWidth:number, colorString:string):IDrawLifeCycle{ public static createOvalLifeCycle(borderWidth:number, colorString:string):IDrawLifeCycle{
let viewLifeCycle = { let viewLifeCycle:IDrawLifeCycle = {
// 展示占位图 // 展示占位图
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示加载进度 // 展示加载进度
@ -38,29 +38,29 @@ export class ImageKnifeDrawFactory{
}, },
// 展示缩略图 // 展示缩略图
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示主图 // 展示主图
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
if (data.isPixelMap()) { if (data.isPixelMap()) {
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER
context.clearRect(0,0,compWidth,compHeight) context.clearRect(0,0,compWidth,compHeight)
context.save(); context.save();
// 绘制适配后的图像 // 绘制适配后的图像
context.save(); context.save();
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0)
context.restore(); context.restore();
// 使用 destination-in 裁剪出椭圆 // 使用 destination-in 裁剪出椭圆
context.save(); context.save();
context.globalCompositeOperation = 'destination-in' context.globalCompositeOperation = 'destination-in'
context.beginPath(); context.beginPath();
this.setOval(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth) ImageKnifeDrawFactory.setOval(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth)
context.closePath(); context.closePath();
context.fill() context.fill()
context.restore(); context.restore();
@ -72,7 +72,7 @@ export class ImageKnifeDrawFactory{
context.lineWidth = borderWidth; context.lineWidth = borderWidth;
context.globalCompositeOperation = 'source-over' context.globalCompositeOperation = 'source-over'
context.beginPath(); context.beginPath();
this.setOval(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0, borderWidth) ImageKnifeDrawFactory.setOval(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight, 0, 0, borderWidth)
context.closePath(); context.closePath();
context.stroke() context.stroke()
context.restore(); context.restore();
@ -108,7 +108,7 @@ export class ImageKnifeDrawFactory{
* @param imageOffsetY * @param imageOffsetY
* @param borderWidth * @param borderWidth
*/ */
private static setOval(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX:number,imageOffsetY:number private static setOval(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | undefined, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX:number,imageOffsetY:number
,borderWidth:number) { ,borderWidth:number) {
let scaleW = compWidth / imageWidth let scaleW = compWidth / imageWidth
let scaleH = compHeight / imageHeight let scaleH = compHeight / imageHeight
@ -189,10 +189,10 @@ export class ImageKnifeDrawFactory{
* @param connerRadius 圆角半径 * @param connerRadius 圆角半径
*/ */
public static createRoundLifeCycle(borderWidth:number, colorString:string, connerRadius:number){ public static createRoundLifeCycle(borderWidth:number, colorString:string, connerRadius:number){
let viewLifeCycle = { let viewLifeCycle:IDrawLifeCycle = {
// 展示占位图 // 展示占位图
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示加载进度 // 展示加载进度
@ -201,15 +201,15 @@ export class ImageKnifeDrawFactory{
}, },
// 展示缩略图 // 展示缩略图
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示主图 // 展示主图
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
if (data.isPixelMap()) { if (data.isPixelMap()) {
// @ts-ignore
data.drawPixelMap.imagePixelMap.getImageInfo().then((imageInfo) => { data.drawPixelMap?.imagePixelMap?.getImageInfo().then((imageInfo) => {
let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER let scaleType = (typeof imageKnifeOption.mainScaleType == 'number') ? imageKnifeOption.mainScaleType : ScaleType.FIT_CENTER
context.clearRect(0,0,compWidth,compHeight) context.clearRect(0,0,compWidth,compHeight)
@ -217,13 +217,13 @@ export class ImageKnifeDrawFactory{
// 绘制适配后的图像 // 绘制适配后的图像
context.save(); context.save();
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0) ScaleTypeHelper.drawImageWithScaleType(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0)
context.restore(); context.restore();
// 通过 destination-in 裁剪出圆角 // 通过 destination-in 裁剪出圆角
context.save(); context.save();
context.globalCompositeOperation = 'destination-in' context.globalCompositeOperation = 'destination-in'
this.setRect(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth,connerRadius) ImageKnifeDrawFactory.setRect(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth,connerRadius)
context.fill() context.fill()
context.restore(); context.restore();
if(borderWidth > 0){ if(borderWidth > 0){
@ -232,7 +232,7 @@ export class ImageKnifeDrawFactory{
context.strokeStyle = colorString context.strokeStyle = colorString
context.lineWidth = borderWidth context.lineWidth = borderWidth
context.globalCompositeOperation = 'source-over' context.globalCompositeOperation = 'source-over'
this.setRect(context, scaleType, data.drawPixelMap.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth,connerRadius) ImageKnifeDrawFactory.setRect(context, scaleType, data.drawPixelMap?.imagePixelMap, px2vp(imageInfo.size.width), px2vp(imageInfo.size.height), compWidth, compHeight,0,0,borderWidth,connerRadius)
context.stroke() context.stroke()
context.restore(); context.restore();
} }
@ -268,7 +268,7 @@ export class ImageKnifeDrawFactory{
* @param borderWidth * @param borderWidth
* @param cornerRadius * @param cornerRadius
*/ */
private static setRect(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX:number,imageOffsetY:number private static setRect(context: CanvasRenderingContext2D, scaleType: ScaleType, source: PixelMap | undefined, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX:number,imageOffsetY:number
,borderWidth:number,cornerRadius:number) { ,borderWidth:number,cornerRadius:number) {
let scaleW = compWidth / imageWidth let scaleW = compWidth / imageWidth
let scaleH = compHeight / imageHeight let scaleH = compHeight / imageHeight
@ -284,21 +284,21 @@ export class ImageKnifeDrawFactory{
y1 = borderWidth/2 y1 = borderWidth/2
w1 = imageWidth * minScale - borderWidth; w1 = imageWidth * minScale - borderWidth;
h1 = imageHeight * minScale - borderWidth; h1 = imageHeight * minScale - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.FIT_END: case ScaleType.FIT_END:
x1 = compWidth - imageWidth * minScale + borderWidth / 2 x1 = compWidth - imageWidth * minScale + borderWidth / 2
y1 = compHeight - imageHeight * minScale + borderWidth / 2 y1 = compHeight - imageHeight * minScale + borderWidth / 2
w1 = imageWidth * minScale - borderWidth; w1 = imageWidth * minScale - borderWidth;
h1 = imageHeight * minScale - borderWidth; h1 = imageHeight * minScale - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.FIT_CENTER: case ScaleType.FIT_CENTER:
x1 = (compWidth - imageWidth * minScale) / 2 + borderWidth / 2 x1 = (compWidth - imageWidth * minScale) / 2 + borderWidth / 2
y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2 y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2
w1 = imageWidth * minScale - borderWidth w1 = imageWidth * minScale - borderWidth
h1 = imageHeight * minScale - borderWidth h1 = imageHeight * minScale - borderWidth
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.CENTER: case ScaleType.CENTER:
x1 = Math.max(0,(compWidth - Math.min(compWidth, imageWidth)))/2 + borderWidth/2 x1 = Math.max(0,(compWidth - Math.min(compWidth, imageWidth)))/2 + borderWidth/2
@ -307,7 +307,7 @@ export class ImageKnifeDrawFactory{
w1 = Math.min(compWidth, imageWidth) - borderWidth; w1 = Math.min(compWidth, imageWidth) - borderWidth;
h1 = Math.min(compHeight, imageHeight) - borderWidth; h1 = Math.min(compHeight, imageHeight) - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.CENTER_CROP: case ScaleType.CENTER_CROP:
x1 = borderWidth/2 x1 = borderWidth/2
@ -315,7 +315,7 @@ export class ImageKnifeDrawFactory{
w1 = compWidth - borderWidth; w1 = compWidth - borderWidth;
h1 = compHeight - borderWidth; h1 = compHeight - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.FIT_XY: case ScaleType.FIT_XY:
x1 = borderWidth/2 x1 = borderWidth/2
@ -323,7 +323,7 @@ export class ImageKnifeDrawFactory{
w1 = compWidth - borderWidth; w1 = compWidth - borderWidth;
h1 = compHeight - borderWidth; h1 = compHeight - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break break
case ScaleType.CENTER_INSIDE: case ScaleType.CENTER_INSIDE:
if(minScale < 1){ // FIT_CENTER if(minScale < 1){ // FIT_CENTER
@ -331,7 +331,7 @@ export class ImageKnifeDrawFactory{
y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2 y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2
w1 = imageWidth * minScale - borderWidth w1 = imageWidth * minScale - borderWidth
h1 = imageHeight * minScale - borderWidth h1 = imageHeight * minScale - borderWidth
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
}else{ // CENTER }else{ // CENTER
x1 = Math.max(0,(compWidth - Math.min(compWidth, imageWidth)))/2 + borderWidth/2 x1 = Math.max(0,(compWidth - Math.min(compWidth, imageWidth)))/2 + borderWidth/2
y1 = Math.max(0,(compHeight - Math.min(compHeight, imageHeight)))/2 + borderWidth/2 y1 = Math.max(0,(compHeight - Math.min(compHeight, imageHeight)))/2 + borderWidth/2
@ -339,7 +339,7 @@ export class ImageKnifeDrawFactory{
w1 = Math.min(compWidth, imageWidth) - borderWidth; w1 = Math.min(compWidth, imageWidth) - borderWidth;
h1 = Math.min(compHeight, imageHeight) - borderWidth; h1 = Math.min(compHeight, imageHeight) - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
} }
break; break;
@ -351,7 +351,7 @@ export class ImageKnifeDrawFactory{
w1 = Math.min(compWidth, imageWidth) - borderWidth; w1 = Math.min(compWidth, imageWidth) - borderWidth;
h1 = Math.min(compHeight, imageHeight) - borderWidth; h1 = Math.min(compHeight, imageHeight) - borderWidth;
this.roundRect(context, x1, y1, w1, h1, cornerRadius) ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
break; break;
} }
} }
@ -390,36 +390,36 @@ export class ImageKnifeDrawFactory{
let viewLifeCycle: IDrawLifeCycle = { let viewLifeCycle: IDrawLifeCycle = {
// 展示占位图 // 展示占位图
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示加载进度 // 展示加载进度
displayProgress: (context: CanvasRenderingContext2D, progress: number, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayProgress: (context: CanvasRenderingContext2D, progress: number, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
this.drawDefaultProgress(context, progress, imageKnifeOption, compWidth, compHeight,fontColor,fontSizeRate,setGifTimeId) ImageKnifeDrawFactory.drawDefaultProgress(context, progress, imageKnifeOption, compWidth, compHeight,fontColor,fontSizeRate,setGifTimeId)
return true; return true;
}, },
// 展示缩略图 // 展示缩略图
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示主图 // 展示主图
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示重试图层 // 展示重试图层
displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
}, },
// 展示失败占位图 // 展示失败占位图
displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => { displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
// @ts-ignore
return false; return false;
} }
} }

View File

@ -0,0 +1,75 @@
/*
* Copyright (C) 2023 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 { ImageKnife } from './ImageKnife';
import { LogUtil } from './utils/LogUtil';
export enum GlobalEnum{
// 主hap的context对象key
HAP_CONTEXT_KEY = 'HAP_CONTEXT_KEY',
// ImageKnife的对象key
IMAGE_KNIFE_KEY = 'IMAGE_KNIFE_KEY'
}
// 构造单例对象
export class ImageKnifeGlobal {
private constructor() {}
private static instance: ImageKnifeGlobal;
private _objects = new Map<string, Object>();
public static getInstance(): ImageKnifeGlobal {
if (!ImageKnifeGlobal.instance) {
ImageKnifeGlobal.instance = new ImageKnifeGlobal();
}
return ImageKnifeGlobal.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
getImageKnife():ImageKnife | undefined{
let imageKnifeObj:Object | undefined = this._objects.get(GlobalEnum.IMAGE_KNIFE_KEY);
if(imageKnifeObj == undefined){
LogUtil.error('ImageKnifeGlobal imageKnifeObj is undefined, you need to initialize before using')
return undefined
}else{
return (imageKnifeObj as ImageKnife)
}
}
setImageKnife(imageKnife:ImageKnife):void{
this._objects.set(GlobalEnum.IMAGE_KNIFE_KEY, imageKnife);
}
getHapContext():Object | undefined{
let hapContext:Object | undefined = this._objects.get(GlobalEnum.HAP_CONTEXT_KEY);
if(hapContext == undefined){
LogUtil.error('ImageKnifeGlobal hapContext is undefined, you need to initialize before using')
return undefined
}else{
return hapContext
}
}
setHapContext(hapContext:Object):void{
this._objects.set(GlobalEnum.HAP_CONTEXT_KEY, hapContext);
}
}

View File

@ -22,12 +22,44 @@ import { CropType } from '../imageknife/transform/CropTransformation'
import { AllCacheInfo, IAllCacheInfoCallback } from '../imageknife/interface/IAllCacheInfoCallback' import { AllCacheInfo, IAllCacheInfoCallback } from '../imageknife/interface/IAllCacheInfoCallback'
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle' import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
import { ScaleType } from '../imageknife/ImageKnifeComponent' import { ScaleType } from '../imageknife/ImageKnifeComponent'
import { rgbColor } from './transform/CropCircleWithBorderTransformation'
import { RoundCorner } from './transform/RoundedCornersTransformation'
export interface CropCircleWithBorder{
border: number,
obj: rgbColor
}
export interface Crop{
width: number,
height: number,
cropType: CropType
}
export interface GifOptions{
loopFinish?: (loopTime?:number) => void
speedFactory?: number
seekTo?: number
}
export interface TransformOptions{
transformType: number,
blur?: number,
roundedCorners?: RoundCorner
cropCircleWithBorder?: CropCircleWithBorder
crop?:Crop
brightnessFilter?: number,
contrastFilter?: number,
pixelationFilter?: number,
swirlFilter?: number,
mask?: Resource,
rotateImage?: number
}
@Observed @Observed
export class ImageKnifeOption { export class ImageKnifeOption {
// 主图资源 // 主图资源
loadSrc: string | PixelMap | Resource; loadSrc: string | PixelMap | Resource = '';
mainScaleType?: ScaleType = ScaleType.FIT_CENTER mainScaleType?: ScaleType = ScaleType.FIT_CENTER
enableGpu?:boolean = true; enableGpu?:boolean = true;
@ -77,43 +109,11 @@ export class ImageKnifeOption {
// 设置点击事件回调 // 设置点击事件回调
onClick?:(event?: ClickEvent) => void onClick?:(event?: ClickEvent) => void
gif?: { gif?: GifOptions = undefined;
loopFinish?: (loopTime?) => void
speedFactory?: number
seekTo?: number
}
// 变换相关 不推荐使用该接口 建议直接使用transformation transformations这2个接口实现 // 变换相关 不推荐使用该接口 建议直接使用transformation transformations这2个接口实现
transform?: { transform?:TransformOptions = undefined
transformType: number,
blur?: number,
roundedCorners?: {
top_left: number,
top_right: number,
bottom_left: number,
bottom_right: number
}
cropCircleWithBorder?: {
border: number,
obj: {
r_color: number,
g_color: number,
b_color: number
}
}
crop?: {
width: number,
height: number,
cropType: CropType
}
brightnessFilter?: number,
contrastFilter?: number,
pixelationFilter?: number,
swirlFilter?: number,
mask?: Resource,
rotateImage?: number
}
transformation?: BaseTransform<PixelMap>; transformation?: BaseTransform<PixelMap>;
transformations?: Array<BaseTransform<PixelMap>>; transformations?: Array<BaseTransform<PixelMap>>;

View File

@ -14,9 +14,9 @@
*/ */
import { DiskStrategy } from "../cache/diskstrategy/DiskStrategy" import { DiskStrategy } from "../cache/diskstrategy/DiskStrategy"
import type { AsyncCallback } from "../imageknife/interface/AsyncCallback" import { AsyncCallback } from "../imageknife/interface/AsyncCallback"
import type { AsyncSuccess } from "../imageknife/interface/AsyncSuccess" import { AsyncSuccess } from "../imageknife/interface/AsyncSuccess"
import type { IAllCacheInfoCallback } from "../imageknife/interface/IAllCacheInfoCallback" import { IAllCacheInfoCallback } from "../imageknife/interface/IAllCacheInfoCallback"
import { AUTOMATIC } from "../cache/diskstrategy/enum/AUTOMATIC" import { AUTOMATIC } from "../cache/diskstrategy/enum/AUTOMATIC"
import { BaseTransform } from "../imageknife/transform/BaseTransform" import { BaseTransform } from "../imageknife/transform/BaseTransform"
import { RotateImageTransformation } from "../imageknife/transform/RotateImageTransformation" import { RotateImageTransformation } from "../imageknife/transform/RotateImageTransformation"
@ -24,11 +24,11 @@ import { ImageKnifeData } from "../imageknife/ImageKnifeData"
import { CenterCrop } from '../imageknife/transform/pixelmap/CenterCrop' import { CenterCrop } from '../imageknife/transform/pixelmap/CenterCrop'
import { CenterInside } from '../imageknife/transform/pixelmap/CenterInside' import { CenterInside } from '../imageknife/transform/pixelmap/CenterInside'
import { FitCenter } from '../imageknife/transform/pixelmap/FitCenter' import { FitCenter } from '../imageknife/transform/pixelmap/FitCenter'
import { RoundedCornersTransformation } from '../imageknife/transform/RoundedCornersTransformation' import { RoundedCornersTransformation, RoundCorner } from '../imageknife/transform/RoundedCornersTransformation'
import { CropCircleTransformation } from '../imageknife/transform/CropCircleTransformation' import { CropCircleTransformation } from '../imageknife/transform/CropCircleTransformation'
import { CropCircleWithBorderTransformation } from '../imageknife/transform/CropCircleWithBorderTransformation' import { CropCircleWithBorderTransformation, rgbColor } from '../imageknife/transform/CropCircleWithBorderTransformation'
import { CropSquareTransformation } from '../imageknife/transform/CropSquareTransformation' import { CropSquareTransformation } from '../imageknife/transform/CropSquareTransformation'
import { CropTransformation } from '../imageknife/transform/CropTransformation' import { CropTransformation } from '../imageknife/transform/CropTransformation'
import { CropType } from '../imageknife/transform/CropTransformation' import { CropType } from '../imageknife/transform/CropTransformation'
@ -46,37 +46,39 @@ import { KuwaharaFilterTransform } from '../imageknife/transform/KuwaharaFilterT
import { ToonFilterTransform } from '../imageknife/transform/ToonFilterTransform' import { ToonFilterTransform } from '../imageknife/transform/ToonFilterTransform'
import { VignetteFilterTransform } from '../imageknife/transform/VignetteFilterTransform' import { VignetteFilterTransform } from '../imageknife/transform/VignetteFilterTransform'
import { LogUtil } from '../imageknife/utils/LogUtil' import { LogUtil } from '../imageknife/utils/LogUtil'
import { ImageKnifeGlobal } from './ImageKnifeGlobal'
import { BusinessError } from '@ohos.base'
export interface Size {
width: number,
height: number
}
export class RequestOption { export class RequestOption {
loadSrc: string | PixelMap | Resource; loadSrc: string | PixelMap | Resource = '';
strategy: DiskStrategy = new AUTOMATIC(); strategy: DiskStrategy = new AUTOMATIC();
dontAnimateFlag = false; dontAnimateFlag = false;
placeholderSrc: PixelMap | Resource; placeholderSrc: PixelMap | Resource | undefined = undefined;
placeholderFunc: AsyncSuccess<ImageKnifeData>; placeholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
errorholderSrc: PixelMap | Resource; errorholderSrc: PixelMap | Resource | undefined = undefined;
errorholderFunc: AsyncSuccess<ImageKnifeData>; errorholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
errorholderData: ImageKnifeData; errorholderData: ImageKnifeData | undefined = undefined;;
thumbSizeMultiplier: number; thumbSizeMultiplier: number = 0;
// 如果存在缩略图则主图延时1s加载 // 如果存在缩略图则主图延时1s加载
thumbDelayTime: number = 1000 thumbDelayTime: number = 1000
thumbHolderFunc: AsyncSuccess<ImageKnifeData>; thumbHolderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
requestListeners: Array<AsyncCallback<ImageKnifeData>>; requestListeners: Array<AsyncCallback<ImageKnifeData>> | undefined = undefined;
// 进度条 // 进度条
progressFunc: AsyncSuccess<number>; progressFunc: AsyncSuccess<number> | undefined = undefined;
// 重试图层 // 重试图层
retryholderSrc: PixelMap | Resource; retryholderSrc: PixelMap | Resource | undefined = undefined;
retryholderFunc: AsyncSuccess<ImageKnifeData> retryholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
retryholderData: ImageKnifeData retryholderData: ImageKnifeData | undefined = undefined;
size: { size:Size= { width: -1, height: -1 };
width: number,
height: number
} = { width: -1, height: -1 };
// 网络下载数据回调 // 网络下载数据回调
allCacheInfoCallback: IAllCacheInfoCallback; allCacheInfoCallback: IAllCacheInfoCallback | undefined = undefined;
onlyRetrieveFromCache: boolean = false; onlyRetrieveFromCache: boolean = false;
isCacheable: boolean = true; isCacheable: boolean = true;
@ -118,10 +120,7 @@ export class RequestOption {
/** /**
* set image Component size * set image Component size
*/ */
setImageViewSize(imageSize: { setImageViewSize(imageSize:Size) {
width: number,
height: number
}) {
this.size.width = imageSize.width; this.size.width = imageSize.width;
this.size.height = imageSize.height; this.size.height = imageSize.height;
return this; return this;
@ -192,7 +191,9 @@ export class RequestOption {
} }
addListener(func: AsyncCallback<ImageKnifeData>) { addListener(func: AsyncCallback<ImageKnifeData>) {
this.requestListeners.push(func); if(this.requestListeners != undefined) {
this.requestListeners?.push(func);
}
return this; return this;
} }
@ -210,7 +211,10 @@ export class RequestOption {
this.onlyRetrieveFromCache = flag; this.onlyRetrieveFromCache = flag;
} }
rotateImage(degreesToRotate: number) { rotateImage(degreesToRotate: number|undefined) {
if(degreesToRotate == undefined){
return
}
let rotateImage = new RotateImageTransformation(degreesToRotate); let rotateImage = new RotateImageTransformation(degreesToRotate);
this.transformations.push(rotateImage); this.transformations.push(rotateImage);
return this; return this;
@ -231,12 +235,10 @@ export class RequestOption {
return this; return this;
} }
roundedCorners(obj: { roundedCorners(obj: RoundCorner|undefined) {
top_left: number, if(obj == undefined){
top_right: number, return
bottom_left: number, }
bottom_right: number
}) {
let transformation = new RoundedCornersTransformation({ let transformation = new RoundedCornersTransformation({
top_left: obj.top_left, top_left: obj.top_left,
top_right: obj.top_right, top_right: obj.top_right,
@ -253,11 +255,10 @@ export class RequestOption {
return this; return this;
} }
cropCircleWithBorder(border: number, obj: { cropCircleWithBorder(border: number|undefined, obj: rgbColor|undefined) {
r_color: number, if(border == undefined || obj == undefined){
g_color: number, return
b_color: number }
}) {
let transformation = new CropCircleWithBorderTransformation(border, obj) let transformation = new CropCircleWithBorderTransformation(border, obj)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
@ -269,7 +270,10 @@ export class RequestOption {
return this; return this;
} }
crop(width: number, height: number, cropType: CropType) { crop(width: number|undefined, height: number|undefined, cropType: CropType|undefined) {
if(width == undefined || height == undefined || cropType == undefined){
return
}
let transformation = new CropTransformation(width, height, cropType) let transformation = new CropTransformation(width, height, cropType)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
@ -281,13 +285,19 @@ export class RequestOption {
return this; return this;
} }
brightnessFilter(brightness: number) { brightnessFilter(brightness: number|undefined) {
if(brightness == undefined){
return
}
let transformation = new BrightnessFilterTransformation(brightness) let transformation = new BrightnessFilterTransformation(brightness)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
contrastFilter(contrast: number) { contrastFilter(contrast: number|undefined) {
if(contrast == undefined){
return
}
let transformation = new ContrastFilterTransformation(contrast) let transformation = new ContrastFilterTransformation(contrast)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
@ -311,43 +321,64 @@ export class RequestOption {
return this; return this;
} }
blur(radius: number) { blur(radius: number|undefined) {
if(radius == undefined){
return
}
let transformation = new BlurTransformation(radius) let transformation = new BlurTransformation(radius)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
pixelationFilter(pixel: number) { pixelationFilter(pixel: number|undefined) {
if(pixel == undefined){
return
}
let transformation = new PixelationFilterTransformation(pixel) let transformation = new PixelationFilterTransformation(pixel)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
swirlFilter(degree: number) { swirlFilter(degree: number|undefined) {
if(degree == undefined){
return
}
let transformation = new SwirlFilterTransformation(degree) let transformation = new SwirlFilterTransformation(degree)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
mask(maskResource: Resource) { mask(maskResource: Resource|undefined) {
if(maskResource == undefined){
return
}
let transformation = new MaskTransformation(maskResource) let transformation = new MaskTransformation(maskResource)
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
kuwaharaFilter(radius: number) { kuwaharaFilter(radius: number|undefined) {
if(radius == undefined){
return
}
let transformation = new KuwaharaFilterTransform(radius); let transformation = new KuwaharaFilterTransform(radius);
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
toonFilter(threshold: number, quantizationLevels: number) { toonFilter(threshold: number|undefined, quantizationLevels: number|undefined) {
if(threshold == undefined || quantizationLevels == undefined){
return
}
let transformation = new ToonFilterTransform(threshold, quantizationLevels); let transformation = new ToonFilterTransform(threshold, quantizationLevels);
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
} }
vignetteFilter(centerPoint: Array<number>, vignetteColor: Array<number>, vignetteSpace: Array<number>) { vignetteFilter(centerPoint: Array<number>|undefined, vignetteColor: Array<number>|undefined, vignetteSpace: Array<number>|undefined) {
if(centerPoint == undefined || vignetteColor == undefined || vignetteSpace == undefined){
return
}
let transformation = new VignetteFilterTransform(centerPoint, vignetteColor, vignetteSpace); let transformation = new VignetteFilterTransform(centerPoint, vignetteColor, vignetteSpace);
this.transformations.push(transformation); this.transformations.push(transformation);
return this; return this;
@ -369,66 +400,77 @@ export class RequestOption {
} }
// 占位图解析成功 // 占位图解析成功
placeholderOnComplete(imageKnifeData: ImageKnifeData) { placeholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
LogUtil.log("placeholderOnComplete has called!"); LogUtil.log("placeholderOnComplete has called!");
LogUtil.log("Main Image is Ready:" + this.loadMainReady); LogUtil.log("Main Image is Ready:" + this.loadMainReady);
if (!this.loadMainReady && !(this.loadErrorReady || this.loadRetryReady) && !this.loadThumbnailReady) { if (!this.loadMainReady && !(this.loadErrorReady || this.loadRetryReady) && !this.loadThumbnailReady) {
// 主图未加载成功,并且未加载失败 显示占位图 主图加载成功或者加载失败后=>不展示占位图 // 主图未加载成功,并且未加载失败 显示占位图 主图加载成功或者加载失败后=>不展示占位图
this.placeholderFunc(imageKnifeData) if(this.placeholderSrc != undefined) {
this.placeholderFunc?.asyncSuccess(imageKnifeData)
}
} }
} }
// 占位图解析失败 // 占位图解析失败
placeholderOnError(error) { placeholderOnError = (error:BusinessError|string)=>{
LogUtil.log("占位图解析失败 error =" + error) LogUtil.log("占位图解析失败 error =" + error)
} }
// 缩略图解析成功 // 缩略图解析成功
thumbholderOnComplete(imageKnifeData: ImageKnifeData) { thumbholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
if (!this.loadMainReady && !(this.loadErrorReady || this.loadRetryReady)) { if (!this.loadMainReady && !(this.loadErrorReady || this.loadRetryReady)) {
//主图未加载成功,并且未加载失败 显示占位图 主图加载成功或者加载失败后=>不展示占位图 //主图未加载成功,并且未加载失败 显示占位图 主图加载成功或者加载失败后=>不展示占位图
this.thumbHolderFunc(imageKnifeData) if(this.thumbHolderFunc != undefined) {
this.thumbHolderFunc?.asyncSuccess(imageKnifeData)
}
} }
} }
// 缩略图解析失败 // 缩略图解析失败
thumbholderOnError(error) { thumbholderOnError=(error? :BusinessError|string)=>{
LogUtil.log("缩略图解析失败 error =" + error) LogUtil.log("缩略图解析失败 error =" + error)
} }
// 加载失败 占位图解析成功 // 加载失败 占位图解析成功
errorholderOnComplete(imageKnifeData: ImageKnifeData) { errorholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
// 如果有错误占位图 先解析并保存在RequestOption中 等到加载失败时候进行调用 // 如果有错误占位图 先解析并保存在RequestOption中 等到加载失败时候进行调用
this.errorholderData = imageKnifeData; this.errorholderData = imageKnifeData;
if (this.loadErrorReady) { if (this.loadErrorReady) {
this.errorholderFunc(imageKnifeData) if(this.errorholderFunc != undefined) {
this.errorholderFunc.asyncSuccess(imageKnifeData)
}
} }
} }
//加载失败 占位图解析失败 //加载失败 占位图解析失败
errorholderOnError(error) { errorholderOnError = (error:BusinessError|string)=> {
LogUtil.log("失败占位图解析失败 error =" + error) LogUtil.log("失败占位图解析失败 error =" + error)
} }
retryholderOnComplete(imageKnifeData: ImageKnifeData) { retryholderOnComplete = (imageKnifeData: ImageKnifeData)=>{
this.retryholderData = imageKnifeData; this.retryholderData = imageKnifeData;
if (this.loadRetryReady) { if (this.loadRetryReady) {
this.retryholderFunc(imageKnifeData) if(this.retryholderFunc != undefined) {
this.retryholderFunc?.asyncSuccess(imageKnifeData)
}
} }
} }
retryholderOnError(error) { retryholderOnError = (error:BusinessError|string)=>{
LogUtil.log("重试占位图解析失败 error =" + error) LogUtil.log("重试占位图解析失败 error =" + error)
} }
loadComplete(imageKnifeData: ImageKnifeData) { loadComplete = (imageKnifeData: ImageKnifeData)=>{
this.loadMainReady = true; this.loadMainReady = true;
// 三级缓存数据加载成功 // 三级缓存数据加载成功
for (let requestListener of this.requestListeners) { if(this.requestListeners != undefined) {
var ret = requestListener("", imageKnifeData); for (let i = 0;i < this.requestListeners.length; i++) {
if (ret) { let requestListener = this.requestListeners[i];
break; let boolInterception = requestListener.callback("", imageKnifeData);
if (boolInterception) {
break;
}
} }
} }
@ -436,36 +478,46 @@ export class RequestOption {
// 等落盘结束后主动调用#removeCurrentAndSearchNext方法 // 等落盘结束后主动调用#removeCurrentAndSearchNext方法
}else{ }else{
// 非落盘情况,直接进行寻找下一个加载 // 非落盘情况,直接进行寻找下一个加载
globalThis.ImageKnife.removeRunning(this); if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
(ImageKnifeGlobal.getInstance().getImageKnife())?.removeRunning(this);
}
} }
// 加载成功之后 // 加载成功之后
globalThis.ImageKnife.removeRunning(this); if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
(ImageKnifeGlobal.getInstance().getImageKnife())?.removeRunning(this);
}
} }
// 图片文件落盘之后会自动去寻找下一个数据加载 // 图片文件落盘之后会自动去寻找下一个数据加载
removeCurrentAndSearchNext(){ removeCurrentAndSearchNext =()=>{
globalThis.ImageKnife.removeRunning(this); if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
(ImageKnifeGlobal.getInstance().getImageKnife())?.removeRunning(this);
}
} }
loadError(err) { loadError = (err:BusinessError|string)=>{
LogUtil.log("loadError:" + err); LogUtil.log("loadError:" + err);
//失败占位图展示规则 //失败占位图展示规则
if (this.retryholderFunc) { if (this.retryholderFunc) {
// 重试图层优先于加载失败展示 // 重试图层优先于加载失败展示
this.loadRetryReady = true; this.loadRetryReady = true;
if (this.retryholderData != null) { if (this.retryholderData != null) {
this.retryholderFunc(this.retryholderData) this.retryholderFunc.asyncSuccess(this.retryholderData)
} }
} else { } else {
// 失败图层标记,如果已经有数据直接展示失败图层 // 失败图层标记,如果已经有数据直接展示失败图层
this.loadErrorReady = true; this.loadErrorReady = true;
if (this.errorholderData != null) { if (this.errorholderData != null) {
this.errorholderFunc(this.errorholderData) if(this.errorholderFunc != undefined) {
this.errorholderFunc.asyncSuccess(this.errorholderData)
}
} }
} }
// 加载失败之后 // 加载失败之后
globalThis.ImageKnife.removeRunning(this); if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
(ImageKnifeGlobal.getInstance().getImageKnife())?.removeRunning(this);
}
} }
} }

View File

@ -22,16 +22,24 @@ import {DataStringPathProvider} from '../compress/provider/DataStringPathProvide
import {RecourseProvider} from '../compress/provider/RecourseProvider' import {RecourseProvider} from '../compress/provider/RecourseProvider'
import { Engine } from '../compress/Engine' import { Engine } from '../compress/Engine'
import { ImageKnife } from '../ImageKnife' import { ImageKnife } from '../ImageKnife'
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
import common from '@ohos.app.ability.common';
export class CompressBuilder { export class CompressBuilder {
private _mTargetDir: string; private _mTargetDir: string = '';
private _mLeastCompressSize: number= 100; //KB private _mLeastCompressSize: number= 100; //KB
private _mRenameListener: OnRenameListener; private _mRenameListener: OnRenameListener = {reName:()=>{return ''}};
private _mCompressListener: OnCompressListener; private _mCompressListener: OnCompressListener={
private _mCompressionPredicate: CompressionPredicate start:()=> {},
private _mStreamProviders: Array<CompressAdapter>; onSuccess:(p: PixelMap|null|undefined, path: string)=> {},
private _mFocusAlpha: boolean; onError:(s: string)=> {}
private _outFilePath: string; };
private _mCompressionPredicate: CompressionPredicate ={
apply:(path: string)=> { return false }
}
private _mStreamProviders: Array<CompressAdapter> = new Array<CompressAdapter>();
private _mFocusAlpha: boolean = false;
private _outFilePath: string = '';
constructor() { constructor() {
this._mStreamProviders = new Array(); this._mStreamProviders = new Array();
} }
@ -54,14 +62,14 @@ export class CompressBuilder {
public setTargetDir(targetDir: string): CompressBuilder { public setTargetDir(targetDir: string): CompressBuilder {
this._mTargetDir = targetDir; this._mTargetDir = targetDir;
if (this._mTargetDir) { if (this._mTargetDir) {
var timestamp = (new Date()).valueOf(); let timestamp = (new Date()).valueOf();
this._outFilePath = this._mTargetDir + "/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg"; this._outFilePath = this._mTargetDir + "/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
} }
return this; return this;
} }
public load(list: Array<string | Resource>): CompressBuilder { public load(list: Array<string | Resource>): CompressBuilder {
for (var i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
let element = list[i]; let element = list[i];
if (typeof element === "string") { if (typeof element === "string") {
this.loadString(element); this.loadString(element);
@ -106,9 +114,9 @@ export class CompressBuilder {
public async get():Promise<string> { public async get():Promise<string> {
if (!this._mTargetDir) { if (!this._mTargetDir) {
let context = globalThis.ImageKnife.getImageKnifeContext(); let context= (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext);
let path = context.filesDir; let path = context.filesDir;
var timestamp = (new Date()).valueOf(); let timestamp = (new Date()).valueOf();
this._outFilePath = path + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg"; this._outFilePath = path + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
let result = await this.startAsyncCompress(); let result = await this.startAsyncCompress();
return result; return result;
@ -119,15 +127,15 @@ export class CompressBuilder {
} }
private async startAsyncCompress():Promise<string> { private async startAsyncCompress():Promise<string> {
let compressPromise = new Promise((resolve, reject) => { let compressPromise:Promise<string> = new Promise((resolve, reject) => {
let compressListener: OnCompressListener = { let compressListener: OnCompressListener = {
start() { start:()=>{
}, },
onScuccess(p: PixelMap, path: string) { onSuccess:(p: PixelMap|undefined|null, path: string)=> {
resolve(path); resolve(path);
}, },
onError(s: string) { onError:(s: string)=> {
} }
} }
@ -138,7 +146,7 @@ export class CompressBuilder {
return; return;
} }
for (var i = 0; i < this._mStreamProviders.length; i++) { for (let i = 0; i < this._mStreamProviders.length; i++) {
let element = this._mStreamProviders[i]; let element = this._mStreamProviders[i];
let isOpenfilter = false; let isOpenfilter = false;
if (this._mCompressionPredicate) { if (this._mCompressionPredicate) {
@ -171,11 +179,11 @@ export class CompressBuilder {
return; return;
} }
if (this._mRenameListener) { if (this._mRenameListener) {
var name = this._mRenameListener.reName(); let name = this._mRenameListener.reName();
if (this._outFilePath && name) { if (this._outFilePath && name) {
var start = this._outFilePath.lastIndexOf("/") + 1 let start = this._outFilePath.lastIndexOf("/") + 1
var end = this._outFilePath.length; let end = this._outFilePath.length;
var replaceStr = this._outFilePath.substring(start, end); let replaceStr = this._outFilePath.substring(start, end);
this._outFilePath = this._outFilePath.replace(replaceStr, name); this._outFilePath = this._outFilePath.replace(replaceStr, name);
} }
} }
@ -183,7 +191,7 @@ export class CompressBuilder {
this._mCompressListener.start(); this._mCompressListener.start();
} }
for (var i = 0; i < this._mStreamProviders.length; i++) { for (let i = 0; i < this._mStreamProviders.length; i++) {
let element = this._mStreamProviders[i]; let element = this._mStreamProviders[i];
let isOpenfilter = false; let isOpenfilter = false;
if (this._mCompressionPredicate) { if (this._mCompressionPredicate) {
@ -194,15 +202,15 @@ export class CompressBuilder {
this._mCompressListener, this._mCompressionPredicate).compress(); this._mCompressListener, this._mCompressionPredicate).compress();
} else { } else {
if (this._mCompressListener) { if (this._mCompressListener) {
this._mCompressListener.onScuccess(null, element.getRecoursePath()); this._mCompressListener.onSuccess(null, element.getRecoursePath());
} }
} }
} }
} }
private getImageCacheFile() { private getImageCacheFile() {
let context = globalThis.ImageKnife.getImageKnifeContext(); let context = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
var timestamp = (new Date()).valueOf(); let timestamp = (new Date()).valueOf();
this._outFilePath = context.filesDir + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg"; this._outFilePath = context.filesDir + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
this.startCompress(); this.startCompress();
} }

View File

@ -13,14 +13,15 @@
* limitations under the License. * limitations under the License.
*/ */
import {OnCompressListener} from '../compress/listener/OnCompressListener' import { OnCompressListener } from '../compress/listener/OnCompressListener'
import {CompressionPredicate} from '../compress/listener/CompressionPredicate' import { CompressionPredicate } from '../compress/listener/CompressionPredicate'
import {CompressAdapter} from "../compress/provider/CompressAdapter" import { CompressAdapter } from "../compress/provider/CompressAdapter"
import {DataStringPathProvider} from '../compress/provider/DataStringPathProvider' import { DataStringPathProvider } from '../compress/provider/DataStringPathProvider'
import {RecourseProvider} from '../compress/provider/RecourseProvider' import { RecourseProvider } from '../compress/provider/RecourseProvider'
import {FileUtils} from '../../cache/FileUtils' import { FileUtils } from '../../cache/FileUtils'
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base'
export class Engine { export class Engine {
private mFocusAlpha: boolean; private mFocusAlpha: boolean;
@ -48,10 +49,10 @@ export class Engine {
srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth; srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight; srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;
var longSide = Math.max(srcWidth, srcHeight); let longSide = Math.max(srcWidth, srcHeight);
var shortSide = Math.min(srcWidth, srcHeight); let shortSide = Math.min(srcWidth, srcHeight);
var scale = shortSide / longSide; let scale = shortSide / longSide;
if (scale <= 1 && scale > 0.5625) { if (scale <= 1 && scale > 0.5625) {
if (longSide < 1664) { if (longSide < 1664) {
return 1; return 1;
@ -72,7 +73,7 @@ export class Engine {
compress() { compress() {
if (this.mCompressAdapter instanceof DataStringPathProvider) { if (this.mCompressAdapter instanceof DataStringPathProvider) {
// file // file
this.mCompressAdapter.openInternal((buffer) => { this.mCompressAdapter.openInternal({ compressDataListener: (buffer: ArrayBuffer) => {
if (!buffer) { if (!buffer) {
if (this.mCompressListener) { if (this.mCompressListener) {
this.mCompressListener.onError("file read fail,and date is empty") this.mCompressListener.onError("file read fail,and date is empty")
@ -83,36 +84,36 @@ export class Engine {
return; return;
} }
var imageResource = image.createImageSource(buffer as any); let imageResource: image.ImageSource = image.createImageSource(buffer);
imageResource.getImageInfo() imageResource.getImageInfo()
.then(info => { .then(info => {
var height = info.size.height; let height = info.size.height;
var width = info.size.width; let width = info.size.width;
var computeSize = this.computeSize(width, height); let computeSize = this.computeSize(width, height);
console.info("Engine compress computeSize:" + computeSize); console.info("Engine compress computeSize:" + computeSize);
let options = { let options: image.DecodingOptions = {
editable: true, editable: true,
sampleSize: computeSize, sampleSize: computeSize,
desiredPixelFormat: image.PixelMapFormat.RGB_565, desiredPixelFormat: image.PixelMapFormat.RGB_565,
} }
imageResource.createPixelMap(options) imageResource.createPixelMap(options)
.then(bitmap => { .then(bitmap => {
})
.catch((error: BusinessError) => {
this.mCompressListener.onError("ptah createPixelMap fail,because error:" + JSON.stringify(error as BusinessError))
})
}) })
.catch(error => { .catch((error: BusinessError) => {
this.mCompressListener.onError("ptah createPixelMap fail,because error:" + JSON.stringify(error)) this.mCompressListener.onError("ptah getImageInfo fail,because error:" + JSON.stringify(error as BusinessError))
}) })
} })
})
.catch(error => {
this.mCompressListener.onError("ptah getImageInfo fail,because error:" + JSON.stringify(error))
})
})
} else if (this.mCompressAdapter instanceof RecourseProvider) { } else if (this.mCompressAdapter instanceof RecourseProvider) {
// resource // resource
this.mCompressAdapter.openInternal((buffer) => { this.mCompressAdapter.openInternal({ compressDataListener: (buffer: ArrayBuffer) => {
if (!buffer) { if (!buffer) {
if (this.mCompressListener) { if (this.mCompressListener) {
this.mCompressListener.onError("resource read fail,and date is empty") this.mCompressListener.onError("resource read fail,and date is empty")
@ -122,86 +123,78 @@ export class Engine {
if (!this.checkNeedCompress(buffer)) { if (!this.checkNeedCompress(buffer)) {
return; return;
} }
var imageResource = image.createImageSource(buffer as any); let imageResource: image.ImageSource = image.createImageSource(buffer);
imageResource.getImageInfo() imageResource.getImageInfo()
.then(info => { .then(info => {
var height = info.size.height; let height = info.size.height;
var width = info.size.width; let width = info.size.width;
var computeSize = this.computeSize(width, height); let computeSize = this.computeSize(width, height);
let packer = { let packer: image.PackingOption = {
format: ["image/jpeg"], format: "image/jpeg",
quality: computeSize, quality: computeSize,
}
var imagePacker = image.createImagePacker();
imagePacker.packing(imageResource, packer as any, (err,compressBuffer)=>{
if(err){
this.mCompressListener.onError("resource packing fail,because error:" + err);
} }
let imagePacker: image.ImagePacker = image.createImagePacker();
imagePacker.packing(imageResource, packer, (err, compressBuffer) => {
if (err) {
this.mCompressListener.onError("resource packing fail,because error:" + err);
}
console.log("compressBuffer is null ="+ (compressBuffer==null)); console.log("compressBuffer is null =" + (compressBuffer == null));
console.log("compressBuffer is undefined ="+ (compressBuffer == undefined) ); console.log("compressBuffer is undefined =" + (compressBuffer == undefined));
let dirPath = this.mPath.substring(0, this.mPath.lastIndexOf("/") + 1); let dirPath = this.mPath.substring(0, this.mPath.lastIndexOf("/") + 1);
var isDirectory = this.checkDirExist(dirPath); let isDirectory = this.checkDirExist(dirPath);
if (isDirectory) { if (isDirectory) {
this.saveFile(this.mPath, compressBuffer);
this.handResult(compressBuffer, this.mPath);
} else {
fileio.mkdir(dirPath)
.then(() => {
this.saveFile(this.mPath, compressBuffer); this.saveFile(this.mPath, compressBuffer);
this.handResult(compressBuffer, this.mPath); this.handResult(compressBuffer, this.mPath);
}); } else {
} fs.mkdir(dirPath)
}) .then(() => {
this.saveFile(this.mPath, compressBuffer);
this.handResult(compressBuffer, this.mPath);
});
}
})
}) })
}) } })
} }
} }
private handResult(buffer: ArrayBuffer, path: string) { private handResult(buffer: ArrayBuffer, path: string) {
var imageRes = image.createImageSource(buffer as any); let imageRes:image.ImageSource = image.createImageSource(buffer);
let a={ let a:image.DecodingOptions = {
editable: true, editable: true,
} }
imageRes.createPixelMap(a) imageRes.createPixelMap(a)
.then(bitmap => { .then(bitmap => {
if (this.mCompressListener) { if (this.mCompressListener) {
this.mCompressListener.onScuccess(bitmap, path); this.mCompressListener.onSuccess(bitmap, path);
} }
}) })
.catch(error => { .catch((error:BusinessError) => {
if (this.mCompressListener) { if (this.mCompressListener) {
this.mCompressListener.onError("buffer generated pixelMap fail,because error:" + JSON.stringify(error)) this.mCompressListener.onError("buffer generated pixelMap fail,because error:" + JSON.stringify(error as BusinessError))
} }
}) })
} }
private checkNeedCompress(buf: ArrayBuffer): boolean{ private checkNeedCompress(buf: ArrayBuffer): boolean {
if (!buf) { if (!buf) {
return false; return false;
} }
var length = buf.byteLength / 1024; let length = buf.byteLength / 1024;
return length > this._mLeastCompressSize; return length > this._mLeastCompressSize;
} }
private saveFile(path: string, content: ArrayBuffer) { private saveFile(path: string, content: ArrayBuffer) {
FileUtils.getInstance().writeFile(path,content); FileUtils.getInstance().writeFile(path, content);
} }
private checkDirExist(dirPath: string): boolean{ private checkDirExist(dirPath: string): boolean {
var isExist; let isExist:boolean = fs.accessSync(dirPath);
try {
fileio.accessSync(dirPath, 0)
isExist = true;
} catch (e) {
//不符合条件则进入
isExist = false;
}
return isExist; return isExist;
} }
} }

View File

@ -14,5 +14,5 @@
*/ */
export interface CompressDataListener<T> { export interface CompressDataListener<T> {
(t: T); compressDataListener:(t: T)=>void;
} }

View File

@ -17,5 +17,5 @@
* filter out unsupported * filter out unsupported
*/ */
export interface CompressionPredicate { export interface CompressionPredicate {
apply(path: string): boolean; apply:(path: string)=>boolean;
} }

View File

@ -19,13 +19,13 @@ export interface OnCompressListener {
/** /**
* compress start * compress start
*/ */
start(); start:()=>void;
/** /**
* compress success * compress success
*/ */
onScuccess(p: PixelMap, path: string); onSuccess:(p: PixelMap|undefined|null, path: string)=>void;
/** /**
* compress fail * compress fail
*/ */
onError(s: string); onError:(s: string)=>void;
} }

View File

@ -17,5 +17,5 @@
* rename listener * rename listener
*/ */
export interface OnRenameListener { export interface OnRenameListener {
reName():string; reName:()=>string;
} }

View File

@ -17,8 +17,8 @@ import {CompressProvider} from "../provider/CompressProvider"
import {CompressDataListener} from "../listener/CompressDataListener" import {CompressDataListener} from "../listener/CompressDataListener"
export abstract class CompressAdapter implements CompressProvider { export abstract class CompressAdapter implements CompressProvider {
mData: ArrayBuffer; mData: ArrayBuffer = new ArrayBuffer(0);
mPath: string; mPath: string = '';
close() { close() {
} }
@ -35,9 +35,9 @@ export abstract class CompressAdapter implements CompressProvider {
abstract getRecoursePath(): string; abstract getRecoursePath(): string;
abstract getPixelMapFormat(): PixelMapFormat; abstract getPixelMapFormat(): PixelMapFormat | undefined;
getFormat(s: string): PixelMapFormat{ getFormat(s: string): PixelMapFormat | undefined{
if (!s) { if (!s) {
return undefined; return undefined;
} }

View File

@ -31,14 +31,14 @@ export class DataStringPathProvider extends CompressAdapter {
if (!this.mPath) { if (!this.mPath) {
throw new Error('DataStringPathProvider error path is empty'); throw new Error('DataStringPathProvider error path is empty');
} }
var buffer = FileUtils.getInstance().readFilePic(this.mPath); let buffer = FileUtils.getInstance().readFilePic(this.mPath);
this.mData = buffer; this.mData = buffer;
if (callback) { if (callback) {
callback(buffer); callback.compressDataListener(buffer);
} }
} }
getPixelMapFormat(): PixelMapFormat{ getPixelMapFormat(): PixelMapFormat|undefined{
if (!this.mPath) { if (!this.mPath) {
return PixelMapFormat.NONE; return PixelMapFormat.NONE;
} }

View File

@ -13,27 +13,30 @@
* limitations under the License. * limitations under the License.
*/ */
import {CompressAdapter, PixelMapFormat} from "../provider/CompressAdapter" import { CompressAdapter, PixelMapFormat } from "../provider/CompressAdapter"
import {CompressDataListener} from "../listener/CompressDataListener" import { CompressDataListener } from "../listener/CompressDataListener"
import {FileTypeUtil} from '../../../imageknife/utils/FileTypeUtil' import { FileTypeUtil } from '../../../imageknife/utils/FileTypeUtil'
import { ImageKnifeGlobal } from '../../ImageKnifeGlobal';
import resourceManager from '@ohos.resourceManager';
import { BusinessError } from '@ohos.base'
export class RecourseProvider extends CompressAdapter { export class RecourseProvider extends CompressAdapter {
private static CHARS: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; private static CHARS: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
private static DEFAULT_RESOURCE_PATH: string= "Resource" private static DEFAULT_RESOURCE_PATH: string = "Resource"
private _mLookup: Uint8Array = new Uint8Array(256); private _mLookup: Uint8Array = new Uint8Array(256);
private _mResourceData: Resource; private _mResourceData?: Resource = undefined;
private _mPixelMapHeader: string; private _mPixelMapHeader: string = '';
constructor(s: Resource) { constructor(s: Resource) {
super() super()
this._mResourceData = s; this._mResourceData = s;
this.mPath = RecourseProvider.DEFAULT_RESOURCE_PATH; this.mPath = RecourseProvider.DEFAULT_RESOURCE_PATH;
for (var index = 0; index < RecourseProvider.CHARS.length; index++) { for (let index = 0; index < RecourseProvider.CHARS.length; index++) {
this._mLookup[RecourseProvider.CHARS.charCodeAt(index)] = index; this._mLookup[RecourseProvider.CHARS.charCodeAt(index)] = index;
} }
} }
getRecoursePath(): string{ getRecoursePath(): string {
return this.mPath; return this.mPath;
} }
@ -42,21 +45,22 @@ export class RecourseProvider extends CompressAdapter {
if (!this._mResourceData) { if (!this._mResourceData) {
throw Error("compress resource is empty"); throw Error("compress resource is empty");
} }
globalThis.ImageKnife.getImageKnifeContext().resourceManager ((ImageKnifeGlobal.getInstance()
.getMedia(this._mResourceData.id) .getHapContext() as Record<string, Object>).resourceManager as resourceManager.ResourceManager)
.getMediaContent(this._mResourceData.id)
.then(data => { .then(data => {
let buffer = this.uint8ArrayToBuffer(data); let buffer = this.uint8ArrayToBuffer(data);
let fileTypeUtil = new FileTypeUtil() let fileTypeUtil = new FileTypeUtil()
this._mPixelMapHeader = fileTypeUtil.getFileType(buffer); this._mPixelMapHeader = fileTypeUtil.getFileType(buffer);
callback(buffer); callback.compressDataListener(buffer);
}) })
.catch(err => { .catch((err: BusinessError) => {
console.log("RecourseProvider openInternal err" + JSON.stringify(err)); console.log("RecourseProvider openInternal err" + JSON.stringify(err as BusinessError));
}) })
} }
getPixelMapFormat(): PixelMapFormat{ getPixelMapFormat(): PixelMapFormat|undefined{
if (!this._mPixelMapHeader) { if (!this._mPixelMapHeader) {
return PixelMapFormat.NONE; return PixelMapFormat.NONE;
} }
@ -66,14 +70,14 @@ export class RecourseProvider extends CompressAdapter {
* data decode * data decode
*/ */
decode(base64: string, callback: CompressDataListener<ArrayBuffer>) { decode(base64: string, callback: CompressDataListener<ArrayBuffer>) {
let bufferLength = base64.length, let bufferLength: number = base64.length;
len = base64.length, let len: number = base64.length;
i, let i: number = 0;
p = 0, let p: number = 0;
encoded1, let encoded1: number = 0;
encoded2, let encoded2: number = 0;
encoded3, let encoded3: number = 0;
encoded4; let encoded4: number = 0;
if (base64[base64.length - 1] === '=') { if (base64[base64.length - 1] === '=') {
bufferLength--; bufferLength--;
@ -98,7 +102,7 @@ export class RecourseProvider extends CompressAdapter {
} }
this.mData = arraybuffer; this.mData = arraybuffer;
if (callback) { if (callback) {
callback(arraybuffer); callback.compressDataListener(arraybuffer);
} }
} }

View File

@ -15,37 +15,39 @@
import { CropCallback } from './CropCallback' import { CropCallback } from './CropCallback'
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { BusinessError } from '@ohos.base'
export namespace Crop { export namespace Crop {
export function crop(buf: ArrayBuffer, x: number, y: number, cropWidth: number, cropHeight: number, func?: CropCallback<PixelMap>, colorRatio?: number) { export interface CropSize{
width:number,
height:number
}
export function crop(buf: ArrayBuffer, x: number, y: number, cropWidth: number, cropHeight: number, func?: CropCallback<PixelMap|null>, colorRatio?: number) {
if (!buf || buf.byteLength <= 0) { if (!buf || buf.byteLength <= 0) {
console.log("Crop buf is empty"); console.log("Crop buf is empty");
if (func) { if (func) {
func("Crop buf is empty", null); func.cropCallback("Crop buf is empty", null);
} }
return; return;
} }
var imageSource = image.createImageSource(buf as any); let imageSource:image.ImageSource = image.createImageSource(buf);
getPixelMapSize(imageSource, (error, size: { let crop:CropCallback<CropSize|null> = { cropCallback: (error:BusinessError|string, size: CropSize|null) => {
width: number,
height: number
}) => {
if (!size) { if (!size) {
func(error, null) func?.cropCallback(error, null)
return; return;
} }
var pixelMapWidth = size.width; let pixelMapWidth = size.width;
var pixelMapHeight = size.height; let pixelMapHeight = size.height;
if (x < 0 || x > pixelMapWidth) { if (x < 0 || x > pixelMapWidth) {
func("Crop error x must be less than pixelMapWidth ", null) func?.cropCallback("Crop error x must be less than pixelMapWidth ", null)
return; return;
} }
if (y < 0 || y > pixelMapHeight) { if (y < 0 || y > pixelMapHeight) {
func("Crop error x must be less than pixelMapHeight ", null) func?.cropCallback("Crop error x must be less than pixelMapHeight ", null)
return; return;
} }
var options = { let options: image.DecodingOptions = {
editable: true, editable: true,
rotate: 0, rotate: 0,
desiredSize: { desiredSize: {
@ -58,58 +60,57 @@ export namespace Crop {
}, },
} }
imageSource.createPixelMap(options) imageSource.createPixelMap(options)
.then((data) => { .then((data:PixelMap) => {
if (colorRatio && colorRatio <= 1) { if (colorRatio && colorRatio <= 1) {
colorRatioPixelMap(data, pixelMapWidth, pixelMapHeight, colorRatio, func); colorRatioPixelMap(data, pixelMapWidth, pixelMapHeight, colorRatio, func);
} else { } else {
func("", data); func?.cropCallback("", data);
} }
}) })
.catch((e) => { .catch((e:BusinessError) => {
func(e, null); func?.cropCallback(e, null);
}) })
}) }
}
getPixelMapSize(imageSource, crop)
} }
var colorRatioPixelMap = async (data: any, width: number, height: number, colorRatio: number, func?: CropCallback<PixelMap>)=> { let colorRatioPixelMap = async (data: PixelMap, width: number, height: number, colorRatio: number, func?: CropCallback<PixelMap|null>)=> {
if (!data) { if (!data) {
func("colorRatio pixelMap is null", null); func?.cropCallback("colorRatio pixelMap is null", null);
return; return;
} }
if (colorRatio > 1) { if (colorRatio > 1) {
throw new Error("the colorRatio must be <= 1"); throw new Error("the colorRatio must be <= 1");
} }
var buffer = new ArrayBuffer(width * height * 5); let buffer = new ArrayBuffer(width * height * 5);
var bytes = new Uint8Array(buffer); let bytes = new Uint8Array(buffer);
var buffer1B = new ArrayBuffer(width * height * 5); let buffer1B = new ArrayBuffer(width * height * 5);
var bytes1B = new Uint8Array(buffer1B); let bytes1B = new Uint8Array(buffer1B);
let readPromise = data.readPixelsToBuffer(buffer) let readPromise:Promise<void> = data.readPixelsToBuffer(buffer)
await readPromise; await readPromise;
for (let i = 0;i < bytes.length; i++) { for (let i = 0;i < bytes.length; i++) {
bytes1B[i] = bytes[i] * colorRatio; bytes1B[i] = bytes[i] * colorRatio;
} }
let writePromise = data.writeBufferToPixels(buffer1B) let writePromise:Promise<void> = data.writeBufferToPixels(buffer1B)
await writePromise; await writePromise;
func("", data); func?.cropCallback("", data);
} }
var getPixelMapSize = (imageSource: any, func: CropCallback<{ let getPixelMapSize = (imageSource: image.ImageSource, func: CropCallback<CropSize|null>)=> {
width: number,
height: number
}>)=> {
if (!imageSource) { if (!imageSource) {
return; return;
} }
imageSource.getImageInfo((err, value) => { imageSource.getImageInfo((err, value) => {
if (err) { if (err) {
func(err, null) func.cropCallback(err, null)
return; return;
} }
var pWidth = value.size.width; let pWidth = value.size.width;
var pHeight = value.size.height; let pHeight = value.size.height;
func('', { width: pWidth, height: pHeight }); func.cropCallback('', { width: pWidth, height: pHeight });
}) })
} }
} }

View File

@ -12,6 +12,7 @@
* 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 { BusinessError } from '@ohos.base'
export interface CropCallback<T> { export interface CropCallback<T> {
(err, data: T) cropCallback:(err:BusinessError|string, data: T)=>void
} }

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import {CropOptions} from "../crop/CropOptions"; import {CropOptions,Size} from "../crop/CropOptions";
@Component @Component
export struct CropImage { export struct CropImage {
@ -35,10 +35,15 @@ export struct CropImage {
}) })
.scale({ x: this._scale, y: this._scale, z: 1.0 }) .scale({ x: this._scale, y: this._scale, z: 1.0 })
.gesture(GestureGroup(GestureMode.Parallel, .gesture(GestureGroup(GestureMode.Parallel,
RotationGesture({ fingers: 1 }).onActionUpdate(event => { RotationGesture({ fingers: 1 }).onActionUpdate((event?: GestureEvent) => {
this._rotate = event.angle; if(event != undefined) {
}), PinchGesture({ fingers: 2 }).onActionUpdate(event => { this._rotate = event.angle;
this._scale = event.scale; }
}), PinchGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
if(event != undefined) {
this._scale = event.scale;
}
}) })
).onCancel(() => { ).onCancel(() => {
console.log("CropImage gesture cancel"); console.log("CropImage gesture cancel");

View File

@ -12,11 +12,12 @@
* 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.
*/ */
export interface Size{
width: number,
height: number;
}
export class CropOptions { export interface CropOptions {
src: string | PixelMap | Resource; src: string | PixelMap | Resource;
size: { size: Size
width: number,
height: number;
}
} }

View File

@ -15,11 +15,11 @@
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { Crop } from './Crop' import { Crop } from './Crop'
import { CropCallback } from './CropCallback' import { CropCallback } from './CropCallback'
import { BusinessError } from '@ohos.base'
@Component @Component
struct PixelMapCrop { export struct PixelMapCrop {
@Watch('watchOptions') @Link options: PixelMapCrop.Options; @Watch('watchOptions') @Link options: Options;
@Watch('watchCropTap') @Prop cropTap: boolean; @Watch('watchCropTap') @Prop cropTap: boolean = false;
@State bWidth: number = 0; @State bWidth: number = 0;
@State bHeight: number = 0; @State bHeight: number = 0;
@State cWidth: number = 0; @State cWidth: number = 0;
@ -305,59 +305,60 @@ struct PixelMapCrop {
// .backgroundColor('#33000000') // .backgroundColor('#33000000')
.onReady(() => { .onReady(() => {
}) })
.onTouch((event: TouchEvent) => { .onTouch((event?: TouchEvent) => {
if (event.type === TouchType.Down) { if(event != undefined) {
// 手指按下 if (event.type === TouchType.Down) {
this.downX = event.touches[0].x; // 手指按下
this.downY = event.touches[0].y; this.downX = event.touches[0].x;
this.downY = event.touches[0].y;
this.lastMoveX = event.touches[0].x; this.lastMoveX = event.touches[0].x;
this.lastMoveY = event.touches[0].y; this.lastMoveY = event.touches[0].y;
this.belongRegion() this.belongRegion()
}
if (event.type === TouchType.Up) {
// 手指放开
this.downX = 0;
this.downY = 0;
this.moveX = 0;
this.moveY = 0;
this.resetTouch();
}
if (event.type === TouchType.Move) {
// 手指移动
this.moveX = event.touches[0].x;
this.moveY = event.touches[0].y;
// 每次移动的delta数据
let dx = this.moveX - this.lastMoveX;
let dy = this.moveY - this.lastMoveY;
console.log('PMC this.isTopLeftAreaTouch =' + this.isTopLeftAreaTouch + ' this.isTopRightAreaTouch =' + this.isTopRightAreaTouch
+ ' this.isBottomLeftAreaTouch=' + this.isBottomLeftAreaTouch + ' isBottomRightAreaTouch' + this.isBottomRightAreaTouch
+ ' dx =' + dx + ' dy =' + dy)
this.touchLeftTopArea(dx, dy)
this.touchRightTopArea(dx, dy)
this.touchLeftBottomArea(dx, dy)
this.touchRightBottomArea(dx, dy)
this.touchTopLineArea(dx, dy)
this.touchLeftLineArea(dx, dy)
this.touchRightLineArea(dx, dy)
this.touchBottomLineArea(dx, dy)
this.touchMoveCropBox(dx, dy);
this.lastMoveX = event.touches[0].x
this.lastMoveY = event.touches[0].y
}
} }
if (event.type === TouchType.Up) {
// 手指放开
this.downX = 0;
this.downY = 0;
this.moveX = 0;
this.moveY = 0;
this.resetTouch();
}
if (event.type === TouchType.Move) {
// 手指移动
this.moveX = event.touches[0].x;
this.moveY = event.touches[0].y;
// 每次移动的delta数据
let dx = this.moveX - this.lastMoveX;
let dy = this.moveY - this.lastMoveY;
console.log('PMC this.isTopLeftAreaTouch =' + this.isTopLeftAreaTouch + ' this.isTopRightAreaTouch =' + this.isTopRightAreaTouch
+ ' this.isBottomLeftAreaTouch=' + this.isBottomLeftAreaTouch + ' isBottomRightAreaTouch' + this.isBottomRightAreaTouch
+ ' dx =' + dx + ' dy =' + dy)
this.touchLeftTopArea(dx, dy)
this.touchRightTopArea(dx, dy)
this.touchLeftBottomArea(dx, dy)
this.touchRightBottomArea(dx, dy)
this.touchTopLineArea(dx, dy)
this.touchLeftLineArea(dx, dy)
this.touchRightLineArea(dx, dy)
this.touchBottomLineArea(dx, dy)
this.touchMoveCropBox(dx, dy);
this.lastMoveX = event.touches[0].x
this.lastMoveY = event.touches[0].y
}
}) })
} }
@ -785,46 +786,46 @@ struct PixelMapCrop {
} }
} }
namespace PixelMapCrop { export class Options {
width: number = 0;
height: number = 0;
export class Options { pixelMap?: PixelMap = undefined;
width: number;
height: number;
pixelMap: PixelMap;
// 是否需要绘制线 // 是否需要绘制线
hasGuideLine: boolean; hasGuideLine: boolean = false;
pixelBuffer: ArrayBuffer; pixelBuffer: ArrayBuffer = new ArrayBuffer(0);
// 展示pixel宽度 // 展示pixel宽度
pixelWidth: number; pixelWidth: number = 0;
// 展示pixel高度 // 展示pixel高度
pixelHeight: number; pixelHeight: number = 0;
// 缩放scale:center-inside类型缩放的比例 // 缩放scale:center-inside类型缩放的比例
pixelScale: number; pixelScale: number = 1;
// 用户裁剪后的回调 // 用户裁剪后的回调
cropFunction: Function; cropFunction: (error:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number) => void = (error:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number)=>{};
// 本地裁剪框 回调 // 本地裁剪框 回调
cropAction: Function; cropAction: (topLeftPoint:number[], bottomRightPoint:number[], scaleInside:number) =>void = (topLeftPoint:number[], bottomRightPoint:number[], scaleInside:number)=>{};
constructor() { constructor() {
} }
// 裁剪动作 // 裁剪动作
setCropFunction(crop: (error, pixelmap, sx, sy) => void) { setCropFunction(crop: (error:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number) => void) {
this.cropFunction = crop; this.cropFunction = crop;
this.cropAction = (topLeftPoint, bottomRightPoint, scaleInside) => { this.cropAction = (topLeftPoint:number[], bottomRightPoint:number[], scaleInside:number) => {
let dx = vp2px(1) * topLeftPoint[0] * 1.0 / scaleInside; let dx:number = vp2px(1) * topLeftPoint[0] * 1.0 / scaleInside;
let dy = vp2px(1) * topLeftPoint[1] * 1.0 / scaleInside; let dy:number = vp2px(1) * topLeftPoint[1] * 1.0 / scaleInside;
let sx = vp2px(1) * (bottomRightPoint[0] - topLeftPoint[0]) * 1.0 / scaleInside; let sx:number = vp2px(1) * (bottomRightPoint[0] - topLeftPoint[0]) * 1.0 / scaleInside;
let sy = vp2px(1) * (bottomRightPoint[1] - topLeftPoint[1]) * 1.0 / scaleInside; let sy:number = vp2px(1) * (bottomRightPoint[1] - topLeftPoint[1]) * 1.0 / scaleInside;
Crop.crop(this.pixelBuffer, dx, dy, sx, sy, (error, pixelmap) => { Crop.crop(this.pixelBuffer, dx, dy, sx, sy, {
this.cropFunction(error, pixelmap, sx, sy) cropCallback: (error: BusinessError | string, pixelmap: PixelMap | null) => {
this.cropFunction(error, pixelmap, sx, sy)
}
}, 1); }, 1);
} }
return this; return this;
@ -857,7 +858,7 @@ namespace PixelMapCrop {
//数据赋值 //数据赋值
this.pixelBuffer = buffer; this.pixelBuffer = buffer;
let imageSource = image.createImageSource(buffer as any); let imageSource:image.ImageSource = image.createImageSource(buffer);
imageSource.getImageInfo().then((imageInfo) => { imageSource.getImageInfo().then((imageInfo) => {
//获取宽高 //获取宽高
@ -879,7 +880,7 @@ namespace PixelMapCrop {
this.pixelWidth = imageInfo.size.width * scaleInside; this.pixelWidth = imageInfo.size.width * scaleInside;
this.pixelHeight = imageInfo.size.height * scaleInside; this.pixelHeight = imageInfo.size.height * scaleInside;
let options = { let options:image.DecodingOptions = {
editable: true, editable: true,
rotate: 0, rotate: 0,
desiredSize: { desiredSize: {
@ -887,7 +888,7 @@ namespace PixelMapCrop {
height: imageInfo.size.height * scaleInside, height: imageInfo.size.height * scaleInside,
} }
} }
imageSource.createPixelMap(options).then((pixelmap) => { imageSource.createPixelMap(options).then((pixelmap:PixelMap) => {
this.pixelMap = pixelmap; this.pixelMap = pixelmap;
if (readyCrop) { if (readyCrop) {
readyCrop(); readyCrop();
@ -898,6 +899,6 @@ namespace PixelMapCrop {
} }
} }
}
export default PixelMapCrop;

View File

@ -14,8 +14,8 @@
*/ */
export class ArcPoint { export class ArcPoint {
private x: number; private x: number = 0;
private y: number; private y: number = 0;
constructor(x: number, y: number) { constructor(x: number, y: number) {
this.y = y; this.y = y;

View File

@ -13,12 +13,12 @@
* limitations under the License. * limitations under the License.
*/ */
export class PixelEntry { export class PixelEntry {
a: number; a: number = 0;
b: number; b: number = 0;
r: number; r: number = 0;
g: number; g: number = 0;
f: number; f: number = 0;
pixel: number; pixel: number = 0;
public toString(): string { public toString(): string {
return "PixelEntry a:" + this.a + ";b:" + this.b + ";r:" + this.r + ";g:" + this.g + ";f:" + this.f; return "PixelEntry a:" + this.a + ";b:" + this.b + ";r:" + this.r + ";g:" + this.g + ";f:" + this.f;

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { RequestOption } from '../../imageknife/RequestOption' import { RequestOption,Size } from '../../imageknife/RequestOption'
import { FileTypeUtil } from '../../imageknife/utils/FileTypeUtil' import { FileTypeUtil } from '../../imageknife/utils/FileTypeUtil'
import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData' import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData'
import { ParseImageUtil } from '../utils/ParseImageUtil' import { ParseImageUtil } from '../utils/ParseImageUtil'
@ -22,8 +22,9 @@ import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
import { ParseResClient } from '../resourcemanage/ParseResClient' import { ParseResClient } from '../resourcemanage/ParseResClient'
import {LogUtil} from '../../imageknife/utils/LogUtil' import {LogUtil} from '../../imageknife/utils/LogUtil'
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image'
import { BusinessError } from '@ohos.base'
export class ErrorHolderManager { export class ErrorHolderManager<T> {
private options: RequestOption; private options: RequestOption;
constructor(option: RequestOption) { constructor(option: RequestOption) {
@ -31,16 +32,16 @@ export class ErrorHolderManager {
} }
static execute(option: RequestOption) { static execute(option: RequestOption) {
let manager = new ErrorHolderManager(option); let manager:ErrorHolderManager<ImageKnifeData> = new ErrorHolderManager<ImageKnifeData>(option);
return new Promise(manager.process.bind(manager)) return new Promise(manager.process)
.then(option.errorholderOnComplete.bind(option)).catch(option.errorholderOnError.bind(option)); .then(option.errorholderOnComplete).catch(option.errorholderOnError);
} }
process(onComplete, onError) { process = (onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void)=>{
this.displayErrorholder(onComplete, onError); this.displayErrorholder(onComplete, onError);
} }
private displayErrorholder(onComplete, onError) { private displayErrorholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("displayErrorholder") LogUtil.log("displayErrorholder")
if ((typeof (this.options.errorholderSrc as image.PixelMap).isEditable) == 'boolean') { if ((typeof (this.options.errorholderSrc as image.PixelMap).isEditable) == 'boolean') {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.errorholderSrc as PixelMap) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.errorholderSrc as PixelMap)
@ -51,9 +52,9 @@ export class ErrorHolderManager {
let res = this.options.errorholderSrc as Resource; let res = this.options.errorholderSrc as Resource;
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') { if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
let resourceFetch = new ParseResClient(); let resourceFetch = new ParseResClient();
let suc = (arraybuffer) => { let suc = (arraybuffer:ArrayBuffer) => {
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil:FileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(arraybuffer); let typeValue:string = fileTypeUtil.getFileType(arraybuffer);
switch (typeValue) { switch (typeValue) {
case SupportFormat.svg: case SupportFormat.svg:
this.svgProcess(onComplete, onError, arraybuffer, typeValue) this.svgProcess(onComplete, onError, arraybuffer, typeValue)
@ -78,18 +79,18 @@ export class ErrorHolderManager {
} }
} }
private svgProcess(onComplete, onError, arraybuffer, typeValue) { private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let svgParseImpl = new SVGParseImpl() let svgParseImpl:SVGParseImpl = new SVGParseImpl()
let size = { width: this.options.size.width, height: this.options.size.height } let size:Size = { width: this.options.size.width, height: this.options.size.height }
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => { svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
onComplete(imageKnifeData) onComplete(imageKnifeData)
}).catch(err => { }).catch((err:BusinessError) => {
onError(err) onError(err)
}) })
} }
private mediaImageProcess(onComplete, onError, arraybuffer, typeValue) { private mediaImageProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let parseImageUtil = new ParseImageUtil() let parseImageUtil = new ParseImageUtil()
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)

View File

@ -12,7 +12,7 @@
* 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 {RequestOption} from "../../imageknife/RequestOption" import {RequestOption,Size} from "../../imageknife/RequestOption"
import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts" import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts"
import {Base64} from "../../cache/Base64" import {Base64} from "../../cache/Base64"
import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil" import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil"
@ -20,12 +20,12 @@ import {ImageKnifeData,ImageKnifeType} from "../ImageKnifeData"
import {ParseImageUtil} from '../utils/ParseImageUtil' import {ParseImageUtil} from '../utils/ParseImageUtil'
import {ParseResClient} from '../resourcemanage/ParseResClient' import {ParseResClient} from '../resourcemanage/ParseResClient'
import { SupportFormat } from '../utils/FileTypeUtil' import { SupportFormat } from '../utils/FileTypeUtil'
import { SVGParseImpl } from '../utils/svg/SVGParseImpl' import { SVGParseImpl} from '../utils/svg/SVGParseImpl'
import {LogUtil} from '../../imageknife/utils/LogUtil' import {LogUtil} from '../../imageknife/utils/LogUtil'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { BusinessError } from '@ohos.base'
export class PlaceHolderManager { export class PlaceHolderManager<T> {
private options: RequestOption; private options: RequestOption;
constructor(option: RequestOption) { constructor(option: RequestOption) {
@ -33,16 +33,16 @@ export class PlaceHolderManager {
} }
static execute(option: RequestOption) { static execute(option: RequestOption) {
let manager = new PlaceHolderManager(option); let manager:PlaceHolderManager<ImageKnifeData> = new PlaceHolderManager<ImageKnifeData>(option);
return new Promise(manager.process.bind(manager)) return new Promise(manager.process)
.then(option.placeholderOnComplete.bind(option)).catch(option.placeholderOnError.bind(option)); .then(option.placeholderOnComplete).catch(option.placeholderOnError);
} }
process(onComplete, onError) { process = (onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void)=>{
this.displayPlaceholder(onComplete, onError); this.displayPlaceholder(onComplete, onError);
} }
private displayPlaceholder(onComplete, onError) { private displayPlaceholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void){
LogUtil.log("displayPlaceholder") LogUtil.log("displayPlaceholder")
if ((typeof (this.options.placeholderSrc as image.PixelMap).isEditable) == 'boolean') { if ((typeof (this.options.placeholderSrc as image.PixelMap).isEditable) == 'boolean') {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.placeholderSrc as PixelMap) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.placeholderSrc as PixelMap)
@ -53,7 +53,7 @@ export class PlaceHolderManager {
let res = this.options.placeholderSrc as Resource; let res = this.options.placeholderSrc as Resource;
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') { if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
let resourceFetch = new ParseResClient(); let resourceFetch = new ParseResClient();
let suc = (arraybuffer) => { let suc = (arraybuffer:ArrayBuffer) => {
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(arraybuffer); let typeValue = fileTypeUtil.getFileType(arraybuffer);
switch (typeValue) { switch (typeValue) {
@ -82,19 +82,19 @@ export class PlaceHolderManager {
private svgProcess(onComplete, onError, arraybuffer, typeValue) { private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let svgParseImpl = new SVGParseImpl() let svgParseImpl:SVGParseImpl = new SVGParseImpl()
let size = { width: this.options.size.width, height: this.options.size.height } let size:Size = { width: this.options.size.width, height: this.options.size.height }
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => { svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
onComplete(imageKnifeData) onComplete(imageKnifeData)
}).catch(err => { }).catch((err:BusinessError) => {
onError(err) onError(err)
}) })
} }
private mediaImageProcess(onComplete, onError, arraybuffer, typeValue) { private mediaImageProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let parseImageUtil = new ParseImageUtil() let parseImageUtil:ParseImageUtil = new ParseImageUtil()
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
onComplete(imageKnifeData) onComplete(imageKnifeData)

View File

@ -12,7 +12,7 @@
* 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 {RequestOption} from "../../imageknife/RequestOption" import {RequestOption,Size} from "../../imageknife/RequestOption"
import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts" import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts"
import {Base64} from "../../cache/Base64" import {Base64} from "../../cache/Base64"
import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil" import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil"
@ -24,8 +24,8 @@ import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
import {LogUtil} from '../../imageknife/utils/LogUtil' import {LogUtil} from '../../imageknife/utils/LogUtil'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { BusinessError } from '@ohos.base'
export class RetryHolderManager { export class RetryHolderManager<T> {
private options: RequestOption; private options: RequestOption;
constructor(option: RequestOption) { constructor(option: RequestOption) {
@ -33,16 +33,16 @@ export class RetryHolderManager {
} }
static execute(option: RequestOption) { static execute(option: RequestOption) {
let manager = new RetryHolderManager(option); let manager:RetryHolderManager<ImageKnifeData> = new RetryHolderManager<ImageKnifeData>(option);
return new Promise(manager.process.bind(manager)) return new Promise(manager.process)
.then(option.retryholderOnComplete.bind(option)).catch(option.retryholderOnError.bind(option)); .then(option.retryholderOnComplete).catch(option.retryholderOnError);
} }
process(onComplete, onError) { process = (onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void)=>{
this.displayRetryholder(onComplete, onError); this.displayRetryholder(onComplete, onError);
} }
private displayRetryholder(onComplete, onError) { private displayRetryholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void){
LogUtil.log("displayRetryholder") LogUtil.log("displayRetryholder")
if ((typeof (this.options.retryholderSrc as image.PixelMap).isEditable) == 'boolean') { if ((typeof (this.options.retryholderSrc as image.PixelMap).isEditable) == 'boolean') {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.placeholderSrc as PixelMap) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, this.options.placeholderSrc as PixelMap)
@ -53,7 +53,7 @@ export class RetryHolderManager {
let res = this.options.retryholderSrc as Resource; let res = this.options.retryholderSrc as Resource;
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') { if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
let resourceFetch = new ParseResClient(); let resourceFetch = new ParseResClient();
let suc = (arraybuffer) => { let suc = (arraybuffer:ArrayBuffer) => {
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(arraybuffer); let typeValue = fileTypeUtil.getFileType(arraybuffer);
switch (typeValue) { switch (typeValue) {
@ -82,18 +82,18 @@ export class RetryHolderManager {
private svgProcess(onComplete, onError, arraybuffer, typeValue) { private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let svgParseImpl = new SVGParseImpl() let svgParseImpl = new SVGParseImpl()
let size = { width: this.options.size.width, height: this.options.size.height } let size:Size = { width: this.options.size.width, height: this.options.size.height }
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => { svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
onComplete(imageKnifeData) onComplete(imageKnifeData)
}).catch(err => { }).catch( (err:BusinessError) => {
onError(err) onError(err)
}) })
} }
private mediaImageProcess(onComplete, onError, arraybuffer, typeValue) { private mediaImageProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
let parseImageUtil = new ParseImageUtil() let parseImageUtil = new ParseImageUtil()
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)

View File

@ -14,5 +14,5 @@
*/ */
export interface AsyncCallback<T> { export interface AsyncCallback<T> {
(err: string, data: T): boolean; callback:(err: string, data: T)=>boolean;
} }

View File

@ -14,5 +14,5 @@
*/ */
export interface AsyncSuccess<T> { export interface AsyncSuccess<T> {
(data: T); asyncSuccess:(data: T)=>void;
} }

View File

@ -14,5 +14,5 @@
*/ */
export interface DataCallBack<T> { export interface DataCallBack<T> {
callback(data: T); callback:(data: T)=>void;
} }

View File

@ -14,24 +14,24 @@
*/ */
import {ImageKnifeData} from "../../imageknife/ImageKnifeData" import {ImageKnifeData} from "../../imageknife/ImageKnifeData"
export interface MemoryCacheInfo{
export class AllCacheInfo { key: string,
memoryCacheInfo: { data: ImageKnifeData | undefined
key: string, }
data: ImageKnifeData export interface ResourceCacheInfo{
} path: string,
key: string
resourceCacheInfo: { }
path: string, export interface DataCacheInfo{
key: string path: string,
} key: string
}
dataCacheInfo: { export interface AllCacheInfo {
path: string, memoryCacheInfo: MemoryCacheInfo | undefined
key: string resourceCacheInfo: ResourceCacheInfo | undefined
} dataCacheInfo: DataCacheInfo | undefined
} }
export interface IAllCacheInfoCallback { export interface IAllCacheInfoCallback {
(cacheInfo: AllCacheInfo); callback :(cacheInfo: AllCacheInfo)=>void;
} }

View File

@ -12,8 +12,8 @@
* 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 { BusinessError } from '@ohos.base'
export interface IParseImage { export interface IParseImage<T> {
parseImage(imageinfo:ArrayBuffer, onCompleteFunction, onErrorFunction); parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
parseImageThumbnail(scale:number, imageinfo:ArrayBuffer, onCompleteFunction, onErrorFunction); parseImageThumbnail:(scale:number, imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
} }

View File

@ -13,12 +13,14 @@
* limitations under the License. * limitations under the License.
*/ */
import type { IDataFetch } from '../networkmanage/IDataFetch' import { IDataFetch } from '../networkmanage/IDataFetch'
import { RequestOption } from '../RequestOption' import { RequestOption } from '../RequestOption'
import { NetworkDownloadClient } from './NetworkDownloadClient' import { NetworkDownloadClient } from './NetworkDownloadClient'
import { LoadLocalFileClient } from './LoadLocalFileClient' import { LoadLocalFileClient } from './LoadLocalFileClient'
import { LoadDataShareFileClient } from './LoadDataShareFileClient' import { LoadDataShareFileClient } from './LoadDataShareFileClient'
import loadRequest from '@ohos.request'; import loadRequest from '@ohos.request';
import { ImageKnifeGlobal } from '../ImageKnifeGlobal'
import common from '@ohos.app.ability.common'
// 数据加载器 // 数据加载器
export class DownloadClient implements IDataFetch { export class DownloadClient implements IDataFetch {
@ -26,10 +28,13 @@ export class DownloadClient implements IDataFetch {
private localFileClient = new LoadLocalFileClient(); private localFileClient = new LoadLocalFileClient();
private dataShareFileClient = new LoadDataShareFileClient(); private dataShareFileClient = new LoadDataShareFileClient();
loadData(request: RequestOption, onCompleteFunction, onErrorFunction) { loadData(request: RequestOption, onCompleteFunction:(img: ArrayBuffer) => void, onErrorFunction: (err: string) => void) {
if (typeof request.loadSrc == 'string') { if (typeof request.loadSrc == 'string') {
if (request.loadSrc.startsWith(globalThis.ImageKnife.getImageKnifeContext() let fileDir:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
.filesDir) || request.loadSrc.startsWith(globalThis.ImageKnife.getImageKnifeContext().cacheDir)) { let cacheDir:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).cacheDir as string
if (request.loadSrc.startsWith(fileDir) ||
request.loadSrc.startsWith(cacheDir)) {
// 本地沙盒 // 本地沙盒
this.localFileClient.loadData(request, onCompleteFunction, onErrorFunction) this.localFileClient.loadData(request, onCompleteFunction, onErrorFunction)
} else if (request.loadSrc.startsWith('datashare://') || request.loadSrc.startsWith('file://')) { } else if (request.loadSrc.startsWith('datashare://') || request.loadSrc.startsWith('file://')) {

View File

@ -17,5 +17,5 @@ import { RequestOption } from '../RequestOption'
// 资源加载接口 // 资源加载接口
export interface IDataFetch { export interface IDataFetch {
loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void); loadData:(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void)=>void;
} }

View File

@ -12,10 +12,10 @@
* 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 type { IDataFetch } from '../networkmanage/IDataFetch' import { IDataFetch } from '../networkmanage/IDataFetch'
import { RequestOption } from '../RequestOption' import { RequestOption } from '../RequestOption'
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base'
export class LoadDataShareFileClient implements IDataFetch { export class LoadDataShareFileClient implements IDataFetch {
loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) { loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) {
@ -26,13 +26,13 @@ export class LoadDataShareFileClient implements IDataFetch {
fs.read(file.fd, buf).then((readLen) => { fs.read(file.fd, buf).then((readLen) => {
onComplete(buf); onComplete(buf);
fs.close(file.fd); fs.close(file.fd);
}).catch(err => { }).catch((err:BusinessError) => {
onError('LoadDataShareFileClient fs.read err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code) onError('LoadDataShareFileClient fs.read err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code)
}) })
}).catch(err => { }).catch((err:BusinessError) => {
onError('LoadDataShareFileClient fs.stat err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code) onError('LoadDataShareFileClient fs.stat err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code)
}) })
}).catch(err => { }).catch((err:BusinessError) => {
onError('LoadDataShareFileClient fs.open err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code) onError('LoadDataShareFileClient fs.open err happend uri=' + request.loadSrc + " err.msg=" + err?.message + " err.code=" + err?.code)
}) })
} }

View File

@ -13,10 +13,10 @@
* limitations under the License. * limitations under the License.
*/ */
import type { IDataFetch } from '../networkmanage/IDataFetch' import { IDataFetch } from '../networkmanage/IDataFetch'
import { RequestOption } from '../RequestOption' import { RequestOption } from '../RequestOption'
import { FileUtils } from '../../cache/FileUtils' import { FileUtils } from '../../cache/FileUtils'
import { BusinessError } from '@ohos.base'
export class LoadLocalFileClient implements IDataFetch { export class LoadLocalFileClient implements IDataFetch {
loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) { loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) {
if (typeof request.loadSrc == 'string') { if (typeof request.loadSrc == 'string') {
@ -26,7 +26,7 @@ export class LoadLocalFileClient implements IDataFetch {
} else { } else {
onComplete(fileBuffer); onComplete(fileBuffer);
} }
}).catch(err=>{ }).catch((err:BusinessError)=>{
onError('LoadLocalFileClient loadLocalFileData Error Msg ='+err?.message) onError('LoadLocalFileClient loadLocalFileData Error Msg ='+err?.message)
}) })

View File

@ -13,13 +13,15 @@
* limitations under the License. * limitations under the License.
*/ */
import type { IDataFetch } from '../networkmanage/IDataFetch' import { IDataFetch } from '../networkmanage/IDataFetch'
import { RequestOption } from '../RequestOption' import { RequestOption } from '../RequestOption'
import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5' import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5'
import { FileUtils } from '../../cache/FileUtils' import { FileUtils } from '../../cache/FileUtils'
import loadRequest from '@ohos.request'; import loadRequest from '@ohos.request';
import { LogUtil } from '../utils/LogUtil' import { LogUtil } from '../utils/LogUtil'
import { ImageKnifeGlobal } from '../ImageKnifeGlobal'
import common from '@ohos.app.ability.common'
import { BusinessError } from '@ohos.base'
// 数据加载器 // 数据加载器
export class NetworkDownloadClient implements IDataFetch { export class NetworkDownloadClient implements IDataFetch {
loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) { loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) {
@ -34,23 +36,23 @@ export class NetworkDownloadClient implements IDataFetch {
if (FileUtils.getInstance().exist(allpath)) { if (FileUtils.getInstance().exist(allpath)) {
FileUtils.getInstance().deleteFile(allpath) FileUtils.getInstance().deleteFile(allpath)
} }
var downloadConfig = { let downloadConfig:loadRequest.DownloadConfig = {
url: (request.loadSrc as string), url: (request.loadSrc as string),
filePath: allpath, filePath: allpath,
// 允许计费流量下载 // 允许计费流量下载
enableMetered: true, enableMetered: true,
}; };
let loadTask = null;
loadRequest.downloadFile(globalThis.ImageKnife.getImageKnifeContext(), downloadConfig).then(downloadTask => { loadRequest.downloadFile( (ImageKnifeGlobal.getInstance().getHapContext() as common.BaseContext ), downloadConfig).then((downloadTask:loadRequest.DownloadTask) => {
if (downloadTask) { if (downloadTask) {
loadTask = downloadTask; let loadTask:loadRequest.DownloadTask | null = downloadTask;
loadTask.on('progress', (receivedSize, totalSize) => { loadTask.on('progress', (receivedSize, totalSize) => {
if (totalSize > 0) { if (totalSize > 0) {
// 并不是所有服务器都会返回totalSize 当没有文件大小的时候,下载进度没有百分比回调,只能知道目前下载了多少数据量 // 并不是所有服务器都会返回totalSize 当没有文件大小的时候,下载进度没有百分比回调,只能知道目前下载了多少数据量
let percent = Math.round(((receivedSize * 1.0) / (totalSize * 1.0)) * 100) let percent = Math.round(((receivedSize * 1.0) / (totalSize * 1.0)) * 100)
if (request.progressFunc) { if (request.progressFunc) {
request.progressFunc(percent); request.progressFunc.asyncSuccess(percent);
} }
} }
}); });
@ -62,69 +64,50 @@ export class NetworkDownloadClient implements IDataFetch {
onComplete(arraybuffer); onComplete(arraybuffer);
FileUtils.getInstance().deleteFileAsync(downloadPath).then(()=>{ FileUtils.getInstance().deleteFileAsync(downloadPath).then(()=>{
LogUtil.log('文件名:'+downloadPath+" 文件删除成功!") LogUtil.log('文件名:'+downloadPath+" 文件删除成功!")
}).catch(err=>{ }).catch((err:BusinessError)=>{
LogUtil.log('文件名:'+downloadPath+" 文件删除失败!") LogUtil.log('文件名:'+downloadPath+" 文件删除失败!")
}); });
}).catch(err=>{ }).catch((err:BusinessError)=>{
onError('NetworkDownloadClient Read File Async Error Msg='+ err?.message) onError('NetworkDownloadClient Read File Async Error Msg='+ (err as BusinessError)?.message)
}) })
if(loadTask != null) {
loadTask.off('complete', () => { loadTask.off('complete', () => {})
loadTask.off('pause', () => {})
}) loadTask.off('remove', () => {})
loadTask.off('progress', () => {})
loadTask.off('pause', () => { loadTask.off('fail', () => {})
}) loadTask = null;
}
loadTask.off('remove', () => {
})
loadTask.off('progress', () => {
})
loadTask.off('fail', () => {
})
loadTask = null;
}) })
loadTask.on('pause', () => { loadTask.on('pause', () => {})
})
loadTask.on('remove', () => { loadTask.on('remove', () => {})
})
loadTask.on('fail', (err) => { loadTask.on('fail', (err) => {
onError('NetworkDownloadClient Download task fail err =' + err) onError('NetworkDownloadClient Download task fail err =' + err)
if (loadTask) { if (loadTask!=null) {
loadTask.remove().then(result => { loadTask.delete().then(result => {
loadTask.off('complete', () => { if(loadTask != undefined) {
}) loadTask.off('complete', () => {})
loadTask.off('pause', () => {})
loadTask.off('pause', () => { loadTask.off('remove', () => {})
}) loadTask.off('progress', () => {})
loadTask.off('fail', () => {})
loadTask.off('remove', () => { loadTask = null
}) }
}).catch((err:BusinessError) => {
loadTask.off('progress', () => {
})
loadTask.off('fail', () => {
})
loadTask = null
}).catch(err => {
loadTask = null; loadTask = null;
console.log('NetworkDownloadClient Download task fail err =' + err); console.log('NetworkDownloadClient Download task fail err =' + err);
}) })
} }
}) })
} else { } else {
onError('NetworkDownloadClient downloadTask dismiss!') onError('NetworkDownloadClient downloadTask dismiss!')
} }
}) })
.catch((err) => { .catch((err:BusinessError)=> {
onError("下载子系统download错误捕获,error=" + err.message); onError("下载子系统download错误捕获,error=" + err.message);
}) })
} }

View File

@ -14,5 +14,5 @@
*/ */
export interface PngCallback<R,T>{ export interface PngCallback<R,T>{
(sender:R, receover:T) pngCallback: (sender:R, receover:T)=>void
} }

View File

@ -12,16 +12,16 @@
* 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 {Closeable} from "/imageknife/pngj/io/Closeable" import {Closeable} from "./io/Closeable"
import {ImageInfo} from "/imageknife/pngj/entry/ImageInfo" import {ImageInfo} from "./entry/ImageInfo"
export class PngReader implements Closeable { export class PngReader implements Closeable {
private static LOG_TAG: string= "PngReader"; private static LOG_TAG: string= "PngReader";
private static MAX_TOTAL_BYTES_READ_DEFAULT: number= 901001001; private static MAX_TOTAL_BYTES_READ_DEFAULT: number= 901001001;
private static MAX_BYTES_METADATA_DEFAULT: number= 5024024; private static MAX_BYTES_METADATA_DEFAULT: number= 5024024;
private static MAX_CHUNK_SIZE_SKIP: number= 2024024; private static MAX_CHUNK_SIZE_SKIP: number= 2024024;
public imgInfo: ImageInfo; public imgInfo: ImageInfo = new ImageInfo(0,0,0,false,false,false);
public interlaced: boolean; public interlaced: boolean = false;
constructor(shouldCloseStream: boolean) { constructor(shouldCloseStream: boolean) {

View File

@ -13,20 +13,20 @@
* limitations under the License. * limitations under the License.
*/ */
import {UPNG} from '../../3rd_party/upng/UPNG'; import {UPNG} from '../../3rd_party/upng/UPNG';
import {PngCallback} from '../pngj/PngCallback'; import {PngCallback} from './PngCallback';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import ArkWorker from '@ohos.worker' import ArkWorker from '@ohos.worker'
import { BusinessError } from '@ohos.base'
export class Pngj { export class Pngj {
readPngImageInfo(arraybuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>) { readPngImageInfo(arraybuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, image.ImageInfo>) {
let imageSource = image.createImageSource(arraybuffer as any); let imageSource:image.ImageSource = image.createImageSource(arraybuffer);
if (imageSource != undefined){ if (imageSource != undefined){
imageSource.getImageInfo((err, value) => { imageSource.getImageInfo((err:BusinessError, value:image.ImageInfo) => {
if (err) { if (err) {
return; return;
} }
callback(arraybuffer, value); callback.pngCallback(arraybuffer, value);
}); });
} }
@ -47,19 +47,19 @@ export class Pngj {
*/ */
readPngImage(pngBuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>) { readPngImage(pngBuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>) {
var png = UPNG.decode(pngBuffer); var png = UPNG.decode(pngBuffer);
callback(pngBuffer, png) callback.pngCallback(pngBuffer, png)
} }
writePngWithString(addInfo:string, pngBuffer: ArrayBuffer,callback:PngCallback<ArrayBuffer, any>) { writePngWithString(addInfo:string, pngBuffer: ArrayBuffer,callback:PngCallback<ArrayBuffer, any>) {
var pngDecode = UPNG.decode(pngBuffer); var pngDecode = UPNG.decode(pngBuffer);
var newPng = UPNG.encodeWithString(addInfo, UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0) var newPng = UPNG.encodeWithString(addInfo, UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0)
callback(pngBuffer, newPng); callback.pngCallback(pngBuffer, newPng);
} }
writePng(pngBuffer: ArrayBuffer,callback:PngCallback<ArrayBuffer, any>) { writePng(pngBuffer: ArrayBuffer,callback:PngCallback<ArrayBuffer, any>) {
var pngDecode = UPNG.decode(pngBuffer); var pngDecode = UPNG.decode(pngBuffer);
var newPng = UPNG.encode(UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0) var newPng = UPNG.encode(UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0)
callback(pngBuffer, newPng); callback.pngCallback(pngBuffer, newPng);
} }
readPngImageAsync(worker: any, pngBuffer: ArrayBuffer, callback: PngCallback<ArrayBuffer, any>) { readPngImageAsync(worker: any, pngBuffer: ArrayBuffer, callback: PngCallback<ArrayBuffer, any>) {
@ -79,7 +79,7 @@ export class Pngj {
var data = e.data; var data = e.data;
switch (data.type) { switch (data.type) {
case 'readPngImageAsync': case 'readPngImageAsync':
callback(data.receiver, data.data) callback.pngCallback(data.receiver, data.data)
break; break;
default: default:
break break
@ -107,7 +107,7 @@ export class Pngj {
var data = e.data; var data = e.data;
switch (data.type) { switch (data.type) {
case 'writePngWithStringAsync': case 'writePngWithStringAsync':
callback(data.receiver, data.data) callback.pngCallback(data.receiver, data.data)
break; break;
default: default:
break break
@ -137,7 +137,7 @@ export class Pngj {
var data = e.data; var data = e.data;
switch (data.type) { switch (data.type) {
case 'writePngAsync': case 'writePngAsync':
callback(data.receiver, data.data) callback.pngCallback(data.receiver, data.data)
break; break;
default: default:
break break

View File

@ -162,7 +162,7 @@ export class ImageInfo {
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
var other = obj; let other = obj;
if (this.alpha != other.alpha) if (this.alpha != other.alpha)
return false; return false;
if (this.bitDepth != other.bitDepth) if (this.bitDepth != other.bitDepth)

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import type { ICache } from "../requestmanage/ICache" import { ICache } from "../requestmanage/ICache"
import { DiskLruCache } from "@ohos/disklrucache" import { DiskLruCache } from "@ohos/disklrucache"
export class DiskCacheProxy implements ICache<string, ArrayBuffer> { export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
@ -47,7 +47,7 @@ export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
removeValue(key: string): ArrayBuffer{ removeValue(key: string): ArrayBuffer{
// Disk暂无实现 // Disk暂无实现
return; return new ArrayBuffer(0);
} }
clear() { clear() {

View File

@ -18,11 +18,11 @@ export interface ICache<K, V> {
// 缓存类型 // 缓存类型
getName(): string getName(): string
getValue(key: K): V; getValue(key: K): V|undefined;
putValue(key: K, value: V); putValue(key: K, value: V);
removeValue(key: K): V; removeValue(key: K): V|undefined;
clear(); clear();

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import type {ICache} from "../requestmanage/ICache" import {ICache} from "../requestmanage/ICache"
import {LruCache} from "../../cache/LruCache" import {LruCache} from "../../cache/LruCache"
export class MemoryCacheProxy <K, V> implements ICache<K, V> { export class MemoryCacheProxy <K, V> implements ICache<K, V> {
@ -28,7 +28,7 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
return "Level1MemoryCache" return "Level1MemoryCache"
} }
getValue(key: K): V{ getValue(key: K): V|undefined{
return this.mLruCache.get(key); return this.mLruCache.get(key);
} }
@ -36,7 +36,7 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
this.mLruCache.put(key, value); this.mLruCache.put(key, value);
} }
removeValue(key: K): V{ removeValue(key: K): V|undefined{
return this.mLruCache.remove(key); return this.mLruCache.remove(key);
} }
@ -46,7 +46,7 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
// 外界调用 // 外界调用
loadMemoryCache(key: K, isMemoryCacheable: boolean): V{ loadMemoryCache(key: K, isMemoryCacheable: boolean): V | null{
// 是否开启内存缓存 // 是否开启内存缓存
if (!isMemoryCacheable) { if (!isMemoryCacheable) {
return null; return null;

View File

@ -13,28 +13,26 @@
* limitations under the License. * limitations under the License.
*/ */
import { RequestOption } from '../../imageknife/RequestOption' import { RequestOption,Size } from '../../imageknife/RequestOption'
import { DiskLruCache } from '@ohos/disklrucache' import { DiskLruCache } from '@ohos/disklrucache'
import { LruCache } from '../../cache/LruCache' import { LruCache } from '../../cache/LruCache'
import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5' import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5'
import { MemoryCacheProxy } from '../requestmanage/MemoryCacheProxy' import { MemoryCacheProxy } from '../requestmanage/MemoryCacheProxy'
import { DiskCacheProxy } from '../requestmanage/DiskCacheProxy' import { DiskCacheProxy } from '../requestmanage/DiskCacheProxy'
import { FileTypeUtil } from '../utils/FileTypeUtil' import { FileTypeUtil } from '../utils/FileTypeUtil'
import type { IDataFetch } from '../../imageknife/networkmanage/IDataFetch' import { IDataFetch } from '../../imageknife/networkmanage/IDataFetch'
import type { IResourceFetch } from '../../imageknife/resourcemanage/IResourceFetch' import { IResourceFetch } from '../../imageknife/resourcemanage/IResourceFetch'
import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData' import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData'
import { AllCacheInfo } from '../../imageknife/interface/IAllCacheInfoCallback' import { AllCacheInfo } from '../../imageknife/interface/IAllCacheInfoCallback'
import { ParseImageUtil } from '../utils/ParseImageUtil' import { ParseImageUtil } from '../utils/ParseImageUtil'
import type { IParseImage } from '../interface/IParseImage' import { IParseImage } from '../interface/IParseImage'
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image'
import { SVGParseImpl } from '../utils/svg/SVGParseImpl' import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
import { GIFParseImpl } from '../utils/gif/GIFParseImpl' import { GIFParseImpl } from '../utils/gif/GIFParseImpl'
import { GIFFrame } from '../utils/gif/GIFFrame' import { GIFFrame } from '../utils/gif/GIFFrame'
import { LogUtil } from '../../imageknife/utils/LogUtil' import { LogUtil } from '../../imageknife/utils/LogUtil'
import { BusinessError } from '@ohos.base'
export interface AsyncString {
(data: string): void;
}
export enum Stage { export enum Stage {
@ -64,13 +62,13 @@ export enum RunReason {
export class RequestManager { export class RequestManager {
private TAG: string = "RequestManager"; private TAG: string = "RequestManager";
private options: RequestOption; private options: RequestOption;
private mMemoryCacheProxy: MemoryCacheProxy<string, any>; private mMemoryCacheProxy: MemoryCacheProxy<string, ImageKnifeData>;
private mDiskCacheProxy: DiskCacheProxy; private mDiskCacheProxy: DiskCacheProxy;
private mIDataFetch: IDataFetch; private mIDataFetch: IDataFetch;
private mIResourceFetch: IResourceFetch; private mIResourceFetch: IResourceFetch<ArrayBuffer>;
private mParseImageUtil: IParseImage; private mParseImageUtil: IParseImage<PixelMap>;
constructor(option: RequestOption, memoryCache1: LruCache<string, any>, diskMemoryCache1: DiskLruCache, dataFetch: IDataFetch, resourceFetch: IResourceFetch) { constructor(option: RequestOption, memoryCache1: LruCache<string, ImageKnifeData>, diskMemoryCache1: DiskLruCache, dataFetch: IDataFetch, resourceFetch: IResourceFetch<ArrayBuffer>) {
this.options = option; this.options = option;
// 缓存部分 // 缓存部分
@ -87,23 +85,27 @@ export class RequestManager {
this.mParseImageUtil = new ParseImageUtil(); this.mParseImageUtil = new ParseImageUtil();
} }
static execute(option: RequestOption, memoryCache1: LruCache<string, any>, diskMemoryCache1: DiskLruCache, dataFetch: IDataFetch, resourceFetch: IResourceFetch) { static execute(option: RequestOption, memoryCache1: LruCache<string, ImageKnifeData>, diskMemoryCache1: DiskLruCache, dataFetch: IDataFetch, resourceFetch: IResourceFetch<ArrayBuffer>) {
LogUtil.log("RequestManager execute") LogUtil.log("RequestManager execute")
let manager = new RequestManager(option, memoryCache1, diskMemoryCache1, dataFetch, resourceFetch); let manager = new RequestManager(option, memoryCache1, diskMemoryCache1, dataFetch, resourceFetch);
return new Promise<PixelMap>(manager.process.bind(manager)) return new Promise<ImageKnifeData>(manager.process)
.then(option.loadComplete.bind(option)) .then(option.loadComplete)
.then(manager.loadCompleteAfter.bind(manager)) .then(manager.loadCompleteAfter)
.catch(option.loadError.bind(option)); .catch(option.loadError);
} }
loadCompleteAfter() { loadCompleteAfter =()=>{
try { // 内部消化问题 try { // 内部消化问题
LogUtil.log("loadCompleteAfter!") LogUtil.log("loadCompleteAfter!")
if (this.options.allCacheInfoCallback) { if (this.options.allCacheInfoCallback) {
LogUtil.log("RequestOption =" + JSON.stringify(this.options)); LogUtil.log("RequestOption =" + JSON.stringify(this.options));
// 内存缓存 // 内存缓存
let allCacheInfo = new AllCacheInfo(); let allCacheInfo:AllCacheInfo = {
memoryCacheInfo:{key:'', data:new ImageKnifeData()},
resourceCacheInfo:{key:'', path:''},
dataCacheInfo:{key:'',path:''}
};
let memoryCache = this.mMemoryCacheProxy.getValue(this.options.generateCacheKey); let memoryCache = this.mMemoryCacheProxy.getValue(this.options.generateCacheKey);
allCacheInfo.memoryCacheInfo = { allCacheInfo.memoryCacheInfo = {
key: this.options.generateCacheKey, key: this.options.generateCacheKey,
@ -121,7 +123,7 @@ export class RequestManager {
key: SparkMD5.hashBinary(this.options.generateDataKey), key: SparkMD5.hashBinary(this.options.generateDataKey),
path: this.mDiskCacheProxy.getCachePath() + SparkMD5.hashBinary(this.options.generateDataKey) path: this.mDiskCacheProxy.getCachePath() + SparkMD5.hashBinary(this.options.generateDataKey)
} }
this.options.allCacheInfoCallback(allCacheInfo) this.options.allCacheInfoCallback.callback(allCacheInfo)
} }
} catch (err) { } catch (err) {
LogUtil.log("after err =" + err) LogUtil.log("after err =" + err)
@ -133,12 +135,12 @@ export class RequestManager {
private mStage: Stage = Stage.INITIALIZE; private mStage: Stage = Stage.INITIALIZE;
private mRunReason: RunReason = RunReason.INITIALIZE; private mRunReason: RunReason = RunReason.INITIALIZE;
process(onComplete, onError) { process = (onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void)=>{
LogUtil.log("RequestManager process !"); LogUtil.log("RequestManager process !");
this.loadLeve1MemoryCache(onComplete, onError) this.loadLeve1MemoryCache(onComplete, onError)
} }
private runWrapped(request: RequestOption, runReason: RunReason, onComplete, onError) { private runWrapped(request: RequestOption, runReason: RunReason, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager runWrapped") LogUtil.log("RequestManager runWrapped")
if (runReason == RunReason.INITIALIZE) { if (runReason == RunReason.INITIALIZE) {
this.mStage = this.getNextStage(request, this.mStage); this.mStage = this.getNextStage(request, this.mStage);
@ -169,7 +171,7 @@ export class RequestManager {
} }
//究竟从哪里加载数据 //究竟从哪里加载数据
private searchLoadFrom(request: RequestOption, current: Stage, onComplete, onError) { private searchLoadFrom(request: RequestOption, current: Stage, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager searchLoadFrom") LogUtil.log("RequestManager searchLoadFrom")
if (current == Stage.RESOURCE_CACHE) { if (current == Stage.RESOURCE_CACHE) {
this.loadDiskFromTransform(request, onComplete, onError); this.loadDiskFromTransform(request, onComplete, onError);
@ -185,8 +187,8 @@ export class RequestManager {
} }
// 加载网络资源 // 加载网络资源
private loadSourceFromNetwork(request: RequestOption, onComplete, onError) { private loadSourceFromNetwork(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
let success = (arraybuffer) => { let success = (arraybuffer:ArrayBuffer) => {
this.downloadSuccess(arraybuffer, onComplete, onError) this.downloadSuccess(arraybuffer, onComplete, onError)
} }
let error = (errorMsg:string) =>{ let error = (errorMsg:string) =>{
@ -196,10 +198,10 @@ export class RequestManager {
} }
// 加载本地资源 // 加载本地资源
private loadSourceFormNative(request: RequestOption, onComplete, onError) { private loadSourceFormNative(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager loadSourceFormNative") LogUtil.log("RequestManager loadSourceFormNative")
// 本地解析后进行一级缓存 // 本地解析后进行一级缓存
let success = (arrayBuffer) => { let success = (arrayBuffer:ArrayBuffer) => {
// 使用媒体子系统 ImageSource解析文件 获取PixelMap // 使用媒体子系统 ImageSource解析文件 获取PixelMap
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(arrayBuffer) let typeValue = fileTypeUtil.getFileType(arrayBuffer)
@ -217,7 +219,7 @@ export class RequestManager {
}) })
} else { } else {
if (request.transformations[0]) { if (request.transformations[0]) {
request.transformations[0].transform(arrayBuffer, request, (error, pixelMap: PixelMap) => { request.transformations[0].transform(arrayBuffer, request, {asyncTransform:(error:BusinessError|string, pixelMap: PixelMap|null) => {
// 输出给Image // 输出给Image
if (pixelMap) { if (pixelMap) {
@ -227,7 +229,7 @@ export class RequestManager {
} else { } else {
onError(error); onError(error);
} }
}) }})
} }
else { else {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
@ -242,7 +244,7 @@ export class RequestManager {
this.mIResourceFetch.loadResource(request.loadSrc as Resource, success, onError); this.mIResourceFetch.loadResource(request.loadSrc as Resource, success, onError);
} }
// 加载磁盘缓存 原图 // 加载磁盘缓存 原图
private loadDiskFromSource(request: RequestOption, onComplete, onError) { private loadDiskFromSource(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager loadDiskFromSource") LogUtil.log("RequestManager loadDiskFromSource")
let cached = this.mDiskCacheProxy.getValue(request.generateDataKey) let cached = this.mDiskCacheProxy.getValue(request.generateDataKey)
if (cached != null && cached.byteLength > 0) { if (cached != null && cached.byteLength > 0) {
@ -254,7 +256,7 @@ export class RequestManager {
} }
// 加载磁盘缓存 变换后图片 // 加载磁盘缓存 变换后图片
private loadDiskFromTransform(request: RequestOption, onComplete, onError) { private loadDiskFromTransform(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager loadDiskFromTransform") LogUtil.log("RequestManager loadDiskFromTransform")
let cached = this.mDiskCacheProxy.getValue(request.generateResourceKey) let cached = this.mDiskCacheProxy.getValue(request.generateResourceKey)
if (cached != null) { if (cached != null) {
@ -265,7 +267,7 @@ export class RequestManager {
} }
} }
parseSource(request: RequestOption, onComplete, onError) { parseSource(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager parseSource") LogUtil.log("RequestManager parseSource")
if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') { if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') {
// PixelMap 外层捕获效率更高,不会进入这里 // PixelMap 外层捕获效率更高,不会进入这里
@ -282,7 +284,7 @@ export class RequestManager {
} }
private loadLeve1MemoryCache(onComplete, onError) { private loadLeve1MemoryCache(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log("RequestManager loadLeve1MemoryCache") LogUtil.log("RequestManager loadLeve1MemoryCache")
// 一级缓存 内存获取 // 一级缓存 内存获取
let cache = this.mMemoryCacheProxy.loadMemoryCache(this.options.generateCacheKey, this.options.isCacheable); let cache = this.mMemoryCacheProxy.loadMemoryCache(this.options.generateCacheKey, this.options.isCacheable);
@ -297,7 +299,7 @@ export class RequestManager {
} }
// 解析磁盘文件变成PixeMap // 解析磁盘文件变成PixeMap
private parseDiskFile2PixelMap(request: RequestOption, source: ArrayBuffer, onComplete, onError) { private parseDiskFile2PixelMap(request: RequestOption, source: ArrayBuffer, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
// 步骤一文件转为pixelMap 然后变换 给Image组件 // 步骤一文件转为pixelMap 然后变换 给Image组件
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(source); let typeValue = fileTypeUtil.getFileType(source);
@ -314,23 +316,23 @@ export class RequestManager {
} else { } else {
if (this.options.transformations[0]) { if (this.options.transformations[0]) {
if (this.options.thumbSizeMultiplier) { if (this.options.thumbSizeMultiplier) {
let thumbOption = new RequestOption(); let thumbOption:RequestOption = new RequestOption();
thumbOption.setImageViewSize({ thumbOption.setImageViewSize({
width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width), width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width),
height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height) height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height)
}) })
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options); let thumbCallback = this.options.thumbholderOnComplete;
let thumbError = this.options.thumbholderOnError.bind(this.options); let thumbError = this.options.thumbholderOnError;
this.options.transformations[0].transform(source, thumbOption, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, thumbOption,{asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
thumbCallback(imageKnifeData); thumbCallback(imageKnifeData);
} else { } else {
thumbError(error); thumbError(error);
} }
}) }})
setTimeout(()=>{ setTimeout(()=>{
this.options.transformations[0].transform(source, request, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, request, {asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
// 保存一份变换后的图片PixelMap到MemoryCache // 保存一份变换后的图片PixelMap到MemoryCache
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
@ -339,11 +341,11 @@ export class RequestManager {
} else { } else {
onError(error); onError(error);
} }
}) }})
},this.options.thumbDelayTime); },this.options.thumbDelayTime);
} }
else { else {
this.options.transformations[0].transform(source, request, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, request, {asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
// 保存一份变换后的图片PixelMap到MemoryCache // 保存一份变换后的图片PixelMap到MemoryCache
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
@ -352,13 +354,13 @@ export class RequestManager {
} else { } else {
onError(error); onError(error);
} }
}) }})
} }
} else { } else {
// thumbnail 缩略图部分 // thumbnail 缩略图部分
if (request.thumbSizeMultiplier) { if (request.thumbSizeMultiplier) {
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options); let thumbCallback = this.options.thumbholderOnComplete
let thumbError = this.options.thumbholderOnError.bind(this.options); let thumbError = this.options.thumbholderOnError
let thumbSuccess = (value: PixelMap) => { let thumbSuccess = (value: PixelMap) => {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
thumbCallback(imageKnifeData); thumbCallback(imageKnifeData);
@ -386,13 +388,13 @@ export class RequestManager {
} }
// 解析磁盘变换后文件变成PixeMap // 解析磁盘变换后文件变成PixeMap
private parseDiskTransformFile2PixelMap(request: RequestOption, source: ArrayBuffer, onComplete, onError) { private parseDiskTransformFile2PixelMap(request: RequestOption, source: ArrayBuffer, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
let fileTypeUtil = new FileTypeUtil(); let fileTypeUtil = new FileTypeUtil();
let typeValue = fileTypeUtil.getFileType(source); let typeValue = fileTypeUtil.getFileType(source);
// thumbnail 缩略图部分 // thumbnail 缩略图部分
if (request.thumbSizeMultiplier) { if (request.thumbSizeMultiplier) {
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options); let thumbCallback = this.options.thumbholderOnComplete
let thumbError = this.options.thumbholderOnError.bind(this.options); let thumbError = this.options.thumbholderOnError
let thumbSuccess = (value: PixelMap) => { let thumbSuccess = (value: PixelMap) => {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
thumbCallback(imageKnifeData); thumbCallback(imageKnifeData);
@ -416,7 +418,7 @@ export class RequestManager {
} }
} }
private downloadSuccess(source: ArrayBuffer, onComplete, onError) { private downloadSuccess(source: ArrayBuffer, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
LogUtil.log('Download task completed.'); LogUtil.log('Download task completed.');
if(source == null || source == undefined || source.byteLength <= 0){ if(source == null || source == undefined || source.byteLength <= 0){
@ -447,8 +449,8 @@ export class RequestManager {
.then(async (arraybuffer: ArrayBuffer)=>{ .then(async (arraybuffer: ArrayBuffer)=>{
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer) await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
}) })
.catch(err=>{ .catch( (err:BusinessError)=>{
LogUtil.log('download file is ='+ImageKnifeData.GIF+'and save diskLruCache error ='+ err) LogUtil.log('download file is ='+ImageKnifeData.GIF+'and save diskLruCache error ='+ (err as BusinessError))
}) })
}else if(ImageKnifeData.SVG == filetype){ }else if(ImageKnifeData.SVG == filetype){
// 处理svg // 处理svg
@ -461,8 +463,8 @@ export class RequestManager {
.then(async (arraybuffer: ArrayBuffer)=>{ .then(async (arraybuffer: ArrayBuffer)=>{
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer) await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
}) })
.catch(err=>{ .catch((err:BusinessError)=>{
LogUtil.log('download file is ='+ImageKnifeData.SVG+'and save diskLruCache error ='+ err) LogUtil.log('download file is ='+ImageKnifeData.SVG+'and save diskLruCache error ='+ (err as BusinessError))
}) })
} else { } else {
// 进行变换 // 进行变换
@ -471,19 +473,19 @@ export class RequestManager {
if (this.options.thumbSizeMultiplier) { if (this.options.thumbSizeMultiplier) {
this.thumbnailProcess(source, filetype, onComplete, onError); this.thumbnailProcess(source, filetype, onComplete, onError);
} else { } else {
this.options.transformations[0].transform(source, this.options, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, this.options, {asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
this.saveCacheAndDisk(pixelMap, filetype, onComplete, source); this.saveCacheAndDisk(pixelMap, filetype, onComplete, source);
} else { } else {
onError(error); onError(error);
} }
}) }})
} }
} else { } else {
// thumbnail 缩略图部分 // thumbnail 缩略图部分
if (this.options.thumbSizeMultiplier) { if (this.options.thumbSizeMultiplier) {
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options); let thumbCallback = this.options.thumbholderOnComplete
let thumbError = this.options.thumbholderOnError.bind(this.options); let thumbError = this.options.thumbholderOnError
let thumbSuccess = (value: PixelMap) => { let thumbSuccess = (value: PixelMap) => {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
thumbCallback(imageKnifeData); thumbCallback(imageKnifeData);
@ -515,16 +517,16 @@ export class RequestManager {
private saveCacheAndDisk(value: PixelMap, filetype:string, onComplete, source:ArrayBuffer) { private saveCacheAndDisk(value: PixelMap, filetype:string, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, source:ArrayBuffer) {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
this.mMemoryCacheProxy.putValue(this.options.generateCacheKey, imageKnifeData); this.mMemoryCacheProxy.putValue(this.options.generateCacheKey, imageKnifeData);
let save2DiskCache = async (arraybuffer) => { let save2DiskCache = async (arraybuffer:ArrayBuffer) => {
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer) await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
// 落盘之后需要主动移除当前request并且调用下一个加载 // 落盘之后需要主动移除当前request并且调用下一个加载
let removeCurrentAndSearchNextRun = this.options.removeCurrentAndSearchNext.bind(this.options) let removeCurrentAndSearchNextRun = this.options.removeCurrentAndSearchNext
removeCurrentAndSearchNextRun(); removeCurrentAndSearchNextRun();
} }
let runSave2Disk = (resolve, reject) => { let runSave2Disk = (resolve:(value:ArrayBuffer)=>void|PromiseLike<ArrayBuffer>, reject:(reason?:BusinessError|string)=>void) => {
resolve(source); resolve(source);
} }
let promise = new Promise(runSave2Disk); let promise = new Promise(runSave2Disk);
@ -533,49 +535,49 @@ export class RequestManager {
onComplete(imageKnifeData); onComplete(imageKnifeData);
} }
thumbnailProcess(source:ArrayBuffer, filetype:string, onComplete, onError){ thumbnailProcess(source:ArrayBuffer, filetype:string, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void){
let thumbOption = new RequestOption(); let thumbOption = new RequestOption();
thumbOption.setImageViewSize({ thumbOption.setImageViewSize({
width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width), width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width),
height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height) height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height)
}) })
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options); let thumbCallback = this.options.thumbholderOnComplete
let thumbError = this.options.thumbholderOnError.bind(this.options); let thumbError = this.options.thumbholderOnError
this.options.transformations[0].transform(source, thumbOption, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, thumbOption, {asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap); let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
thumbCallback(imageKnifeData); thumbCallback(imageKnifeData);
} else { } else {
thumbError(error); thumbError(error);
} }
}) }})
setTimeout(() => { setTimeout(() => {
this.options.transformations[0].transform(source, this.options, (error, pixelMap: PixelMap) => { this.options.transformations[0].transform(source, this.options,{asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
if (pixelMap) { if (pixelMap) {
this.saveCacheAndDisk(pixelMap, filetype, onComplete, source); this.saveCacheAndDisk(pixelMap, filetype, onComplete, source);
} else { } else {
onError(error); onError(error);
} }
}) }})
}, this.options.thumbDelayTime) }, this.options.thumbDelayTime)
} }
private svgProcess(onComplete, onError, arraybuffer, typeValue, cacheStrategy?: (cacheData: ImageKnifeData) => void) { private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string, cacheStrategy?: (cacheData: ImageKnifeData) => void) {
let svgParseImpl = new SVGParseImpl() let svgParseImpl = new SVGParseImpl()
let size = { width: this.options.size.width, height: this.options.size.height } let size:Size = { width: this.options.size.width, height: this.options.size.height }
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => { svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
if(cacheStrategy){ if(cacheStrategy){
cacheStrategy(imageKnifeData) cacheStrategy(imageKnifeData)
} }
onComplete(imageKnifeData) onComplete(imageKnifeData)
}).catch(err => { }).catch((err:BusinessError) => {
onError(err) onError(err)
}) })
} }
private gifProcess(onComplete, onError, arraybuffer, typeValue, cacheStrategy?: (cacheData: ImageKnifeData) => void) { private gifProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string, cacheStrategy?: (cacheData: ImageKnifeData) => void) {
let gifParseImpl = new GIFParseImpl() let gifParseImpl = new GIFParseImpl()
gifParseImpl.parseGifs(arraybuffer, (data?,err?)=>{ gifParseImpl.parseGifs(arraybuffer, (data?:GIFFrame[],err?:BusinessError|string)=>{
if(err){ if(err){
onError(err) onError(err)
} }

View File

@ -13,9 +13,8 @@
* limitations under the License. * limitations under the License.
*/ */
import {RequestOption} from "../RequestOption" import { BusinessError } from '@ohos.base'
// 本地资源解析抽象接口 // 本地资源解析抽象接口
export interface IResourceFetch { export interface IResourceFetch<T> {
loadResource(res: Resource, onCompleteFunction, onErrorFunction); loadResource:(res: Resource, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
} }

View File

@ -13,23 +13,24 @@
* limitations under the License. * limitations under the License.
*/ */
import type {IResourceFetch} from '../resourcemanage/IResourceFetch' import {IResourceFetch} from '../resourcemanage/IResourceFetch'
import {ResourceTypeEts} from '../../imageknife/constants/ResourceTypeEts' import {ResourceTypeEts} from '../../imageknife/constants/ResourceTypeEts'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
export class ParseResClient implements IResourceFetch { import { BusinessError } from '@ohos.base'
loadResource(res: Resource, onCompleteFunction, onErrorFunction) { import common from '@ohos.app.ability.common';
export class ParseResClient implements IResourceFetch<ArrayBuffer> {
loadResource(res: Resource, onCompleteFunction:(value:ArrayBuffer)=>void | PromiseLike<ArrayBuffer>, onErrorFunction:(reason?:BusinessError|string)=>void) {
let resId = res.id; let resId = res.id;
let resType = res.type; let resType = res.type;
if (resType == ResourceTypeEts.MEDIA) { if (resType == ResourceTypeEts.MEDIA) {
globalThis.ImageKnife.getImageKnifeContext().resourceManager ((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
.getMedia(resId) .getMediaContent(resId)
.then(data => { .then(data => {
let arrayBuffer = this.typedArrayToBuffer(data); let arrayBuffer = this.typedArrayToBuffer(data);
onCompleteFunction(arrayBuffer) onCompleteFunction(arrayBuffer)
}) })
.catch(err => { .catch( (err:BusinessError) => {
onErrorFunction(err) onErrorFunction(err)
}) })
} }

View File

@ -13,30 +13,32 @@
* limitations under the License. * limitations under the License.
*/ */
import type {IResourceFetch} from '../resourcemanage/IResourceFetch' import { IResourceFetch } from '../resourcemanage/IResourceFetch'
import {ResourceTypeEts} from '../../imageknife/constants/ResourceTypeEts' import { ResourceTypeEts } from '../../imageknife/constants/ResourceTypeEts'
import {Base64} from '../../cache/Base64' import { Base64 } from '../../cache/Base64'
import { BusinessError } from '@ohos.base'
import resourceManager from '@ohos.resourceManager'; import resourceManager from '@ohos.resourceManager';
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
export class ParseResClientBase64 implements IResourceFetch { export class ParseResClientBase64 implements IResourceFetch<ArrayBuffer> {
loadResource(res: Resource, onCompleteFunction, onErrorFunction) { loadResource(res: Resource, onCompleteFunction: (value: ArrayBuffer) => void | PromiseLike<ArrayBuffer>, onErrorFunction: (reason?: BusinessError | string) => void) {
let resId = res.id; let resId = res.id;
let resType = res.type; let resType = res.type;
if (resType == ResourceTypeEts.MEDIA) { if (resType == ResourceTypeEts.MEDIA) {
globalThis.ImageKnife.getImageKnifeContext().resourceManager ((ImageKnifeGlobal.getInstance()
.getMediaBase64(resId) .getHapContext() as Record<string, Object>).resourceManager as resourceManager.ResourceManager)
.getMediaContentBase64(resId)
.then(data => { .then(data => {
let matchReg = ';base64,'; let matchReg = ';base64,';
var firstIndex = data.indexOf(matchReg) let firstIndex = data.indexOf(matchReg)
data = data.substring(firstIndex + matchReg.length, data.length) data = data.substring(firstIndex + matchReg.length, data.length)
let arrayBuffer = Base64.getInstance() let arrayBuffer = Base64.getInstance()
.decode(data); .decode(data);
onCompleteFunction(arrayBuffer) onCompleteFunction(arrayBuffer)
}) })
.catch(err => { .catch((err: BusinessError) => {
onErrorFunction(err) onErrorFunction(err)
}) })
} }
else if (resType == ResourceTypeEts.RAWFILE) { else if (resType == ResourceTypeEts.RAWFILE) {
onErrorFunction('ParseResClientBase64 本地资源是rawfile暂时无法解析出错') onErrorFunction('ParseResClientBase64 本地资源是rawfile暂时无法解析出错')

View File

@ -12,7 +12,7 @@
* 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 { BusinessError } from '@ohos.base'
export interface AsyncTransform<T> { export interface AsyncTransform<T> {
(err, data: T) asyncTransform:(err:BusinessError|string, data: T | null)=>void
} }

View File

@ -21,7 +21,8 @@ import { TransformUtils } from "../transform/TransformUtils"
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { fastBlur } from "../utils/FastBlur" import { fastBlur } from "../utils/FastBlur"
import {LogUtil} from '../../imageknife/utils/LogUtil' import {LogUtil} from '../../imageknife/utils/LogUtil'
import { BusinessError } from '@ohos.base'
import {Size} from '../../imageknife/RequestOption'
export class BlurTransformation implements BaseTransform<PixelMap> { export class BlurTransformation implements BaseTransform<PixelMap> {
private _mRadius: number; private _mRadius: number;
@ -38,23 +39,20 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
if (!buf || buf.byteLength <= 0) { if (!buf || buf.byteLength <= 0) {
LogUtil.log(Constants.PROJECT_TAG + ";BlurTransformation buf is empty"); LogUtil.log(Constants.PROJECT_TAG + ";BlurTransformation buf is empty");
if (func) { if (func) {
func(Constants.PROJECT_TAG + ";BlurTransformation buf is empty", null); func?.asyncTransform(Constants.PROJECT_TAG + ";BlurTransformation buf is empty", null);
} }
return; return;
} }
var imageSource = image.createImageSource(buf as any); let imageSource:image.ImageSource = image.createImageSource(buf);
TransformUtils.getPixelMapSize(imageSource, (error, size: { TransformUtils.getPixelMapSize(imageSource, {asyncTransform:(error:BusinessError|string, size: Size|null) => {
width: number,
height: number
}) => {
if (!size) { if (!size) {
func(error, null) func?.asyncTransform(error, null)
return; return;
} }
var pixelMapWidth = size.width; let pixelMapWidth = size.width;
var pixelMapHeight = size.height; let pixelMapHeight = size.height;
var targetWidth = request.size.width; let targetWidth = request.size.width;
var targetHeight = request.size.height; let targetHeight = request.size.height;
if (pixelMapWidth < targetWidth) { if (pixelMapWidth < targetWidth) {
targetWidth = pixelMapWidth; targetWidth = pixelMapWidth;
} }
@ -62,7 +60,7 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
targetHeight = pixelMapHeight; targetHeight = pixelMapHeight;
} }
var options = { let options:image.DecodingOptions = {
editable: true, editable: true,
desiredSize: { desiredSize: {
width: targetWidth, width: targetWidth,
@ -77,10 +75,10 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
fastBlur.blur(data, this._mRadius, true, func); fastBlur.blur(data, this._mRadius, true, func);
} }
}) })
.catch((e) => { .catch((e:BusinessError) => {
LogUtil.log(Constants.PROJECT_TAG + ";error:" + e); LogUtil.log(Constants.PROJECT_TAG + ";error:" + e);
func(e, null); func?.asyncTransform(e, null);
}) })
}) }})
} }
} }

View File

@ -20,6 +20,8 @@ import { RequestOption } from "../../imageknife/RequestOption"
import { LogUtil } from '../../imageknife/utils/LogUtil' import { LogUtil } from '../../imageknife/utils/LogUtil'
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { GPUImageBrightnessFilter } from '@ohos/gpu_transform' import { GPUImageBrightnessFilter } from '@ohos/gpu_transform'
import { BusinessError } from '@ohos.base'
import {Size} from '../../imageknife/RequestOption'
/** /**
* brightness value ranges from -1.0 to 1.0, with 0.0 as the normal level * brightness value ranges from -1.0 to 1.0, with 0.0 as the normal level
@ -38,27 +40,27 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) { async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) {
if (!buf || buf.byteLength <= 0) { if (!buf || buf.byteLength <= 0) {
LogUtil.log(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty"); LogUtil.log(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty");
if (func) { if (func != undefined) {
func(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty", null); func?.asyncTransform(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty", null);
} }
return; return;
} }
var imageSource = image.createImageSource(buf as any); let imageSource:image.ImageSource = image.createImageSource(buf);
let imageInfo = await imageSource.getImageInfo(); let imageInfo:image.ImageInfo = await imageSource.getImageInfo();
let size = { let size:Size = {
width: imageInfo.size.width, width: imageInfo.size.width,
height: imageInfo.size.height height: imageInfo.size.height
} }
if (!size) { if (!size) {
func(new Error("GrayscaleTransformation The image size does not exist."), null) func?.asyncTransform("GrayscaleTransformation The image size does not exist.", null)
return; return;
} }
var pixelMapWidth = size.width; let pixelMapWidth:number = size.width;
var pixelMapHeight = size.height; let pixelMapHeight:number = size.height;
var targetWidth = request.size.width; let targetWidth:number = request.size.width;
var targetHeight = request.size.height; let targetHeight:number = request.size.height;
if (pixelMapWidth < targetWidth) { if (pixelMapWidth < targetWidth) {
targetWidth = pixelMapWidth; targetWidth = pixelMapWidth;
} }
@ -66,7 +68,7 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
targetHeight = pixelMapHeight; targetHeight = pixelMapHeight;
} }
var options = { let options:image.DecodingOptions = {
editable: true, editable: true,
desiredSize: { desiredSize: {
width: targetWidth, width: targetWidth,
@ -79,18 +81,18 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
await data.readPixelsToBuffer(bufferData); await data.readPixelsToBuffer(bufferData);
if (request.gpuEnabled) { if (request.gpuEnabled) {
let filter = new GPUImageBrightnessFilter(); let filter:GPUImageBrightnessFilter = new GPUImageBrightnessFilter();
filter.setImageData(bufferData, targetWidth, targetHeight); filter.setImageData(bufferData, targetWidth, targetHeight);
filter.setBrightness(this._mBrightness); filter.setBrightness(this._mBrightness);
let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight); let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight);
data.writeBufferToPixels(buf); data.writeBufferToPixels(buf);
if (func) { if (func) {
func("success", data); func?.asyncTransform("success", data);
} }
return; return;
} }
var dataArray = new Uint8Array(bufferData); let dataArray = new Uint8Array(bufferData);
for (let index = 0; index < dataArray.length; index += 4) { for (let index = 0; index < dataArray.length; index += 4) {
dataArray[index] = this.checkVisAble(dataArray[index] * this._mBrightness + dataArray[index]); dataArray[index] = this.checkVisAble(dataArray[index] * this._mBrightness + dataArray[index]);
@ -102,7 +104,7 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
await data.writeBufferToPixels(bufferData); await data.writeBufferToPixels(bufferData);
if (func) { if (func) {
func("", data); func?.asyncTransform("", data);
} }
} }

View File

@ -20,6 +20,8 @@ import { RequestOption } from "../../imageknife/RequestOption"
import { LogUtil } from '../../imageknife/utils/LogUtil' import { LogUtil } from '../../imageknife/utils/LogUtil'
import image from "@ohos.multimedia.image" import image from "@ohos.multimedia.image"
import { GPUImageContrastFilter } from '@ohos/gpu_transform' import { GPUImageContrastFilter } from '@ohos/gpu_transform'
import { BusinessError } from '@ohos.base'
import {Size} from '../../imageknife/RequestOption'
/** /**
* 以24位色图像为例子每种色彩都可以用0-255 * 以24位色图像为例子每种色彩都可以用0-255
@ -50,27 +52,27 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) { async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) {
if (!buf || buf.byteLength <= 0) { if (!buf || buf.byteLength <= 0) {
LogUtil.log(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty"); LogUtil.log(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty");
if (func) { if (func!=undefined) {
func(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty", null); func?.asyncTransform(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty", null);
} }
return; return;
} }
var imageSource = image.createImageSource(buf as any); let imageSource:image.ImageSource = image.createImageSource(buf);
let imageInfo = await imageSource.getImageInfo(); let imageInfo:image.ImageInfo = await imageSource.getImageInfo();
let size = { let size:Size = {
width: imageInfo.size.width, width: imageInfo.size.width,
height: imageInfo.size.height height: imageInfo.size.height
} }
if (!size) { if (!size) {
func(new Error("ContrastFilterTransformation The image size does not exist."), null) func?.asyncTransform("ContrastFilterTransformation The image size does not exist.", null)
return; return;
} }
var pixelMapWidth = size.width; let pixelMapWidth:number = size.width;
var pixelMapHeight = size.height; let pixelMapHeight:number = size.height;
var targetWidth = request.size.width; let targetWidth:number = request.size.width;
var targetHeight = request.size.height; let targetHeight:number = request.size.height;
if (pixelMapWidth < targetWidth) { if (pixelMapWidth < targetWidth) {
targetWidth = pixelMapWidth; targetWidth = pixelMapWidth;
} }
@ -78,7 +80,7 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
targetHeight = pixelMapHeight; targetHeight = pixelMapHeight;
} }
var options = { let options:image.DecodingOptions = {
editable: true, editable: true,
desiredSize: { desiredSize: {
width: targetWidth, width: targetWidth,
@ -97,13 +99,13 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
filter.setContrast(this._mContrast) filter.setContrast(this._mContrast)
let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight); let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight);
data.writeBufferToPixels(buf); data.writeBufferToPixels(buf);
if (func) { if (func != undefined) {
func("success", data); func?.asyncTransform("success", data);
} }
return; return;
} }
var dataArray = new Uint8Array(bufferData); let dataArray = new Uint8Array(bufferData);
let brightness = 0; //亮度的偏移量可以默认0 let brightness = 0; //亮度的偏移量可以默认0
for (let index = 0; index < dataArray.length; index += 4) { for (let index = 0; index < dataArray.length; index += 4) {
@ -114,8 +116,8 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
} }
await data.writeBufferToPixels(bufferData); await data.writeBufferToPixels(bufferData);
if (func) { if (func != undefined) {
func("", data); func?.asyncTransform("", data);
} }
} }

Some files were not shown because too many files have changed in this diff Show More