forked from floraachy/ImageKnife
commit
660e4d0052
14
CHANGELOG.md
14
CHANGELOG.md
|
@ -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
|
||||
|
||||
- 修复若干问题:
|
||||
|
|
58
README.md
58
README.md
|
@ -37,7 +37,7 @@ ohpm install @ohos/imageknife
|
|||
"author": "",
|
||||
"license": "",
|
||||
"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) {
|
||||
windowStage.loadContent('pages/Index', (err, data) => {
|
||||
});
|
||||
//初始化全局ImageKnife
|
||||
globalThis.ImageKnife = ImageKnife.with(this.context);
|
||||
// 初始化全局ImageKnife
|
||||
ImageKnife.with(this.context);
|
||||
// 后续访问ImageKnife请通过:ImageKnifeGlobal.getInstance().getImageKnife()方式
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -109,13 +110,13 @@ GIF图片即可。
|
|||
```extendtypescript
|
||||
import router from '@ohos.router'
|
||||
|
||||
import { ImageKnifeComponent, ImageKnifeOption, } from '@ohos/imageknife'
|
||||
import { ImageKnifeComponent, ImageKnifeOption,ImageKnife } from '@ohos/imageknife'
|
||||
import worker from '@ohos.worker';
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct IndexFunctionDemo {
|
||||
private globalGifWorker: any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined;
|
||||
@State imageKnifeOption1: ImageKnifeOption = {
|
||||
loadSrc: $r('app.media.icon'),
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
|
@ -174,9 +175,15 @@ struct IndexFunctionDemo {
|
|||
}
|
||||
|
||||
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
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
|
||||
aboutToDisappear() {
|
||||
|
@ -322,17 +329,20 @@ svg返回的都是PixelMap,gif返回GIFFrame数组),我们返回了true。
|
|||
当进行加载网络图片时,可能需要展示网络下载百分比动画。但是默认的动画又不能满足需求,这个时候我们就需要自定义网络下载百分比效果。代码如下:
|
||||
|
||||
```typescript
|
||||
import AbilityStage from '@ohos.application.AbilityStage'
|
||||
import { ImageKnife, ImageKnifeDrawFactory } from '@ohos/imageknife'
|
||||
|
||||
import ArkWorker from '@ohos.worker'
|
||||
|
||||
export default class MyAbilityStage extends AbilityStage {
|
||||
onCreate() {
|
||||
globalThis.ImageKnife = ImageKnife.with(this.context);
|
||||
// 全局配置网络加载进度条
|
||||
globalThis.ImageKnife.setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
|
||||
}
|
||||
import UIAbility from '@ohos.app.ability.UIAbility';
|
||||
import window from '@ohos.window';
|
||||
import { ImageKnifeGlobal,ImageKnife,ImageKnifeDrawFactory,LogUtil } from '@ohos/imageknife'
|
||||
import abilityAccessCtrl,{Permissions} from '@ohos.abilityAccessCtrl';
|
||||
export default class EntryAbility extends UIAbility {
|
||||
onWindowStageCreate(windowStage: window.WindowStage) {
|
||||
//.. 删除不必要代码
|
||||
windowStage.loadContent('pages/index', (err, data) => {
|
||||
});
|
||||
// 初始化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组件代码进行分析。
|
||||
|
||||
**从`imageKnifeExecute()`函数入口,首先我们需要构建一个RequestOption对象,`let request = new RequestOption()`,
|
||||
接下来就是按需配置request对象的内容,最后使用 `globalThis.ImageKnife.call(request)`发送request执行任务即可。**
|
||||
接下来就是按需配置request对象的内容,最后使用 `ImageKnifeGlobal.getInstance().getImageKnife()?.call(request)`发送request执行任务即可。**
|
||||
|
||||
是不是很简单,而其实最重要的内容是就是: **按需配置request对象的内容** 为了更好理解,我举例说明一下:
|
||||
|
||||
|
@ -374,7 +384,7 @@ let request = new RequestOption();
|
|||
// (必传)
|
||||
request.load("图片url")
|
||||
// (可选 整个request监听回调)
|
||||
.addListener((err, data) => {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
// data 是ImageKnifeData对象
|
||||
if(data.isPixelMap()){
|
||||
// 这样就获取到了目标PixelMap
|
||||
|
@ -383,14 +393,18 @@ request.load("图片url")
|
|||
return false;
|
||||
})
|
||||
|
||||
let compSize = {
|
||||
let compSize:Size = {
|
||||
width: this.currentWidth,
|
||||
height:this.currentHeight
|
||||
}
|
||||
// (必传)这里setImageViewSize函数必传组件大小,因为涉及到图片变换效果都需要适配图像源和组件大小
|
||||
request.setImageViewSize(compSize)
|
||||
// 最后使用ImageKnife的call函数调用request即可
|
||||
globalThis.ImageKnife.call(request)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife();
|
||||
if(imageKnife != undefined){
|
||||
imageKnife.call(request)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
**其他场景,可以按需加载**
|
||||
|
|
|
@ -1,14 +1,21 @@
|
|||
{
|
||||
"app": {
|
||||
"compileSdkVersion": 9,
|
||||
"compatibleSdkVersion": 9,
|
||||
"products": [
|
||||
{
|
||||
"name": "default",
|
||||
"signingConfig": "default"
|
||||
"signingConfig": "default",
|
||||
"compileSdkVersion": 10,
|
||||
"compatibleSdkVersion": 10
|
||||
}
|
||||
],
|
||||
"signingConfigs": []
|
||||
"buildModeSet":[
|
||||
{
|
||||
"name":"debug"
|
||||
},
|
||||
{
|
||||
"name":"release"
|
||||
}
|
||||
]
|
||||
},
|
||||
"modules": [
|
||||
{
|
||||
|
|
|
@ -19,7 +19,7 @@ export class CustomEngineKeyImpl implements EngineKeyInterface {
|
|||
addOtherInfo: string = "Version=1.0.0;"
|
||||
|
||||
constructor() {
|
||||
this.redefineUrl = this.urlNeedClearToken.bind(this);
|
||||
this.redefineUrl = this.urlNeedClearToken;
|
||||
}
|
||||
// request只读
|
||||
generateMemoryCacheKey(loadSrc: string, size: string, transformed: string, dontAnimate: boolean): string {
|
||||
|
@ -36,7 +36,7 @@ export class CustomEngineKeyImpl implements EngineKeyInterface {
|
|||
|
||||
|
||||
// 需求场景: 请求图片可能 请求中存在token需要清除, 可以把输入的url清除token后作为key的一部分,这样token发生变化也能命中缓存。
|
||||
urlNeedClearToken(url: string): string {
|
||||
urlNeedClearToken = (url: string)=>{
|
||||
if (this.isHttpRequest(url)) {
|
||||
return this.clearToken(url)
|
||||
} else {
|
||||
|
|
|
@ -15,7 +15,7 @@
|
|||
import UIAbility from '@ohos.app.ability.UIAbility';
|
||||
import hilog from '@ohos.hilog';
|
||||
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 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) ?? '');
|
||||
});
|
||||
|
||||
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
|
||||
globalThis.ImageKnife.setEngineKeyImpl(new CustomEngineKeyImpl())
|
||||
ImageKnifeGlobal.getInstance().getImageKnife().setEngineKeyImpl(new CustomEngineKeyImpl())
|
||||
//开启ImageKnife所有级别日志开关
|
||||
LogUtil.mLogLevel = LogUtil.ALL
|
||||
}
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { ImageKnifeComponent, ImageKnifeOption,NONE } from '@ohos/imageknife'
|
||||
import { ImageKnifeComponent, ImageKnifeOption,NONE,DiskStrategy } from '@ohos/imageknife'
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
|
@ -39,13 +39,14 @@ struct OptionTestPage {
|
|||
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
||||
Button("加载")
|
||||
.onClick(() => {
|
||||
let setting:DiskStrategy = new NONE();
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: 'https://img-blog.csdn.net/20140514114029140',
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
onlyRetrieveFromCache: false,
|
||||
isCacheable: false,
|
||||
strategy: new NONE()
|
||||
strategy: setting
|
||||
}
|
||||
}).margin({ top: 5, left: 3 })
|
||||
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption1 }).width(300).height(300)
|
||||
|
@ -55,13 +56,14 @@ struct OptionTestPage {
|
|||
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
||||
Button("加载")
|
||||
.onClick(() => {
|
||||
let setting2:DiskStrategy = new NONE();
|
||||
this.imageKnifeOption2 = {
|
||||
loadSrc: 'https://img-blog.csdn.net/20140514114029140',
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
onlyRetrieveFromCache: true,
|
||||
isCacheable: true,
|
||||
strategy: new NONE()
|
||||
strategy: setting2
|
||||
}
|
||||
}).margin({ top: 5, left: 3 })
|
||||
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption2 }).width(300).height(300)
|
||||
|
|
|
@ -22,7 +22,7 @@ struct BasicTestFeatureAbilityPage {
|
|||
watchPathChange() {
|
||||
console.log("watchPathChange")
|
||||
}
|
||||
urls=[
|
||||
urls:string[]=[
|
||||
"http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
|
||||
"http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.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",
|
||||
]
|
||||
|
||||
@State options:Array<ImageKnifeOption> = []
|
||||
@State options:Array<ImageKnifeOption> = new Array
|
||||
|
||||
aboutToAppear(){
|
||||
this.options = this.urls.map((url)=>{
|
||||
this.options = this.urls.map<ImageKnifeOption>((url:string)=>{
|
||||
return {
|
||||
loadSrc:url
|
||||
}
|
||||
|
@ -60,11 +60,11 @@ struct BasicTestFeatureAbilityPage {
|
|||
Stack({ alignContent: Alignment.TopStart }) {
|
||||
Column() {
|
||||
List({ space: 20, initialIndex: 0 }) {
|
||||
ForEach(this.options, (item) => {
|
||||
ForEach(this.options, (item:ImageKnifeOption) => {
|
||||
ListItem() {
|
||||
ImageKnifeComponent({imageKnifeOption:item}).width(300).height(300)
|
||||
}
|
||||
}, item => item.loadSrc)
|
||||
}, (item:ImageKnifeOption )=> item.loadSrc as string)
|
||||
}
|
||||
.listDirection(Axis.Vertical) // 排列方向
|
||||
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线
|
||||
|
|
|
@ -13,9 +13,10 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { FileUtils } from '@ohos/imageknife'
|
||||
import { FileUtils, ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import common from '@ohos.app.ability.common';
|
||||
@Entry
|
||||
@Component
|
||||
struct basicTestFileIOPage {
|
||||
|
@ -25,7 +26,7 @@ struct basicTestFileIOPage {
|
|||
@State imageHint: string = ''
|
||||
@State imageFile: string = '文字提醒'
|
||||
@State imageRes: Resource = $r('app.media.pngSample')
|
||||
@State imagePixelMap: PixelMap = undefined
|
||||
@State imagePixelMap?: PixelMap = undefined
|
||||
@State normalPixelMap: boolean = false;
|
||||
@State normalResource: boolean = false;
|
||||
|
||||
|
@ -41,7 +42,7 @@ struct basicTestFileIOPage {
|
|||
.margin({ top: 10 })
|
||||
.onClick(() => {
|
||||
|
||||
let data = globalThis.ImageKnife.getImageKnifeContext().filesDir;
|
||||
let data:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
|
||||
console.log('ImageKnife filesPath = ' + data)
|
||||
this.filePath = data
|
||||
this.appFilePath = data;
|
||||
|
@ -51,7 +52,7 @@ struct basicTestFileIOPage {
|
|||
.margin({ top: 10 })
|
||||
.onClick(() => {
|
||||
|
||||
let data = globalThis.ImageKnife.getImageKnifeContext().cacheDir;
|
||||
let data:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).cacheDir as string;
|
||||
console.log('ImageKnife cachesPath = ' + data)
|
||||
this.filePath = data
|
||||
this.appFilePath = data;
|
||||
|
@ -79,8 +80,8 @@ struct basicTestFileIOPage {
|
|||
this.appFilePath = 'appFilePath未取到值,请按顺序从上往下,从左往右依次测试'
|
||||
return
|
||||
}
|
||||
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 => {
|
||||
console.log('result.getMedia')
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength)
|
||||
|
@ -89,8 +90,8 @@ struct basicTestFileIOPage {
|
|||
this.imageFile = 'file://' + this.appFilePath + '/Folder1/jpgSample.gif'
|
||||
console.log('Folder1 imaeFile =' + this.imageFile)
|
||||
})
|
||||
.catch(err => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err as BusinessError));
|
||||
})
|
||||
})
|
||||
Button('copy:Folder1至Folder2, 验证copyFileSync')
|
||||
|
|
|
@ -18,11 +18,13 @@ import { FileTypeUtil } from '@ohos/imageknife'
|
|||
import resourceManager from '@ohos.resourceManager';
|
||||
import { Base64 } 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
|
||||
@Component
|
||||
struct BasicTestMediaImage {
|
||||
@State imagePixelMap: PixelMap = undefined;
|
||||
@State imagePixelMap?: PixelMap = undefined;
|
||||
|
||||
build() {
|
||||
Scroll() {
|
||||
|
@ -30,76 +32,81 @@ struct BasicTestMediaImage {
|
|||
Flex({ direction: FlexDirection.Row }) {
|
||||
Button('本地资源jpg')
|
||||
.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 => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
let parseImageUtil = new ParseImageUtil();
|
||||
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
|
||||
this.imagePixelMap = pxielmap;
|
||||
}, (err) => {
|
||||
}, (err:BusinessError|string|undefined) => {
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
}).margin({ left: 15 }).backgroundColor(Color.Blue)
|
||||
Button('本地资源png')
|
||||
.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 => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
let parseImageUtil = new ParseImageUtil();
|
||||
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
|
||||
this.imagePixelMap = pxielmap;
|
||||
}, (err) => {
|
||||
},(err:BusinessError|string|undefined) => {
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
}).margin({ left: 15 }).backgroundColor(Color.Blue)
|
||||
Button('本地资源bmp')
|
||||
.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 => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
let parseImageUtil = new ParseImageUtil();
|
||||
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
|
||||
this.imagePixelMap = pxielmap;
|
||||
}, (err) => {
|
||||
}, (err:BusinessError|string|undefined) => {
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
}).margin({ left: 15 }).backgroundColor(Color.Blue)
|
||||
Button('本地资源webp')
|
||||
.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 => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
let parseImageUtil = new ParseImageUtil();
|
||||
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
|
||||
this.imagePixelMap = pxielmap;
|
||||
}, (err) => {
|
||||
}, (err:BusinessError|string|undefined) => {
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
}).margin({ left: 15 }).backgroundColor(Color.Blue)
|
||||
Button('本地资源gif')
|
||||
.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 => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
let parseImageUtil = new ParseImageUtil();
|
||||
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
|
||||
this.imagePixelMap = pxielmap;
|
||||
}, (err) => {
|
||||
}, (err:BusinessError|string|undefined) => {
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
}).margin({ left: 15 }).backgroundColor(Color.Blue)
|
||||
|
|
|
@ -17,7 +17,9 @@ import {FileUtils} from '@ohos/imageknife'
|
|||
import {FileTypeUtil} from '@ohos/imageknife'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import {Base64} from '@ohos/imageknife'
|
||||
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import common from '@ohos.app.ability.common';
|
||||
@Entry
|
||||
@Component
|
||||
struct BasicTestResourceManagerPage {
|
||||
|
@ -31,8 +33,9 @@ struct BasicTestResourceManagerPage {
|
|||
Button('getMedia解析一张jpg图片')
|
||||
.margin({ top: 10 })
|
||||
.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 => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
|
@ -40,19 +43,20 @@ struct BasicTestResourceManagerPage {
|
|||
let fileType = filetypeUtil.getFileType(arrayBuffer);
|
||||
this.fileTypeStr = fileType;
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
})
|
||||
Button('getMediaBase64解析一张png图片')
|
||||
.margin({ top: 10 })
|
||||
.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)
|
||||
.then(data => {
|
||||
console.log('ParseResClientBase64 - 本地加载资源 解析后数据data')
|
||||
let matchReg = ';base64,';
|
||||
var firstIndex = data.indexOf(matchReg);
|
||||
let firstIndex = data.indexOf(matchReg);
|
||||
data = data.substring(firstIndex + matchReg.length, data.length)
|
||||
console.log('ParseResClientBase64 - 本地加载资源 解析后数据剔除非必要数据后data= ' + data)
|
||||
let arrayBuffer = Base64.getInstance()
|
||||
|
@ -61,7 +65,7 @@ struct BasicTestResourceManagerPage {
|
|||
let fileType = filetypeUtil.getFileType(arrayBuffer);
|
||||
this.fileTypeStr = fileType;
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
})
|
||||
|
|
|
@ -15,12 +15,13 @@
|
|||
import {ImageKnife} from '@ohos/imageknife'
|
||||
import {OnRenameListener} from '@ohos/imageknife'
|
||||
import {OnCompressListener} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct CompressPage {
|
||||
@State mRPixelMap: PixelMap = undefined;
|
||||
@State mFPixelMap: PixelMap = undefined;
|
||||
@State mRPixelMap?: PixelMap = undefined;
|
||||
@State mFPixelMap?: PixelMap = undefined;
|
||||
@State mResultText: string= "压缩回调结果"
|
||||
@State mResultPath: string= "压缩路径:"
|
||||
@State mAsyncPath: string= ""
|
||||
|
@ -90,58 +91,62 @@ struct CompressPage {
|
|||
}.width('100%').height('100%');
|
||||
}
|
||||
private compressAsyncRecource() {
|
||||
var data = new Array<Resource>();
|
||||
let data = new Array<Resource>();
|
||||
data.push($r('app.media.jpgSample'))
|
||||
|
||||
console.info("asasd start compress")
|
||||
globalThis.ImageKnife
|
||||
.compressBuilder()
|
||||
.load(data)
|
||||
.ignoreBy(100)
|
||||
.get()
|
||||
.then((path)=>{
|
||||
this.mAsyncPathHint = path;
|
||||
this.mAsyncPath='file://' + path;
|
||||
})
|
||||
;
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife!=undefined) {
|
||||
imageKnife
|
||||
.compressBuilder()
|
||||
.load(data)
|
||||
.ignoreBy(100)
|
||||
.get()
|
||||
.then((path: string) => {
|
||||
this.mAsyncPathHint = path;
|
||||
this.mAsyncPath = 'file://' + path;
|
||||
});
|
||||
}
|
||||
console.info("asasd start compress end")
|
||||
}
|
||||
private cropressRecource() {
|
||||
var data = new Array<Resource>();
|
||||
let data = new Array<Resource>();
|
||||
data.push($r('app.media.jpgSample'))
|
||||
var rename: OnRenameListener = {
|
||||
let rename: OnRenameListener = {
|
||||
reName() {
|
||||
return "test_1.jpg";
|
||||
}
|
||||
}
|
||||
var that = this;
|
||||
var listener: OnCompressListener = {
|
||||
start() {
|
||||
that.mResultText = "start"
|
||||
|
||||
let listener: OnCompressListener = {
|
||||
start:()=>{
|
||||
this.mResultText = "start"
|
||||
console.info("asasd start")
|
||||
},
|
||||
onScuccess(p: PixelMap, path: string) {
|
||||
let pack = undefined;
|
||||
pack = p;
|
||||
that.mRPixelMap = pack;
|
||||
console.info("asasd success path:" + this.mRPixelMap)
|
||||
that.mResultText = "success";
|
||||
that.mResultPath = path;
|
||||
onSuccess:(p: PixelMap | null | undefined, path: string)=> {
|
||||
if(p!=null && p!=undefined) {
|
||||
let pack = p;
|
||||
this.mRPixelMap = pack as PixelMap;
|
||||
console.info("asasd success path:" + this.mRPixelMap)
|
||||
this.mResultText = "success";
|
||||
this.mResultPath = path;
|
||||
}
|
||||
},
|
||||
onError(s: string) {
|
||||
onError:(s: string)=>{
|
||||
console.info("asasd onError:" + s)
|
||||
that.mResultText = "fail";
|
||||
this.mResultText = "fail";
|
||||
}
|
||||
}
|
||||
console.info("asasd start compress")
|
||||
|
||||
globalThis.ImageKnife
|
||||
.compressBuilder()
|
||||
.load(data)
|
||||
.ignoreBy(100)
|
||||
.setRenameListener(rename)
|
||||
.setCompressListener(listener)
|
||||
.launch();
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
(ImageKnifeGlobal.getInstance().getImageKnife())
|
||||
.compressBuilder()
|
||||
.load(data)
|
||||
.ignoreBy(100)
|
||||
.setRenameListener(rename)
|
||||
.setCompressListener(listener)
|
||||
.launch();
|
||||
}
|
||||
console.info("asasd start compress end")
|
||||
}
|
||||
}
|
|
@ -17,16 +17,18 @@ import { CropImage } from '@ohos/imageknife'
|
|||
import { CropOptions } from '@ohos/imageknife'
|
||||
import { Crop } 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 { 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
|
||||
@Component
|
||||
export struct CropImagePage2 {
|
||||
@State options1: PixelMapCrop.Options = new PixelMapCrop.Options();
|
||||
@State options1: Options = new Options();
|
||||
@State cropTap: boolean = false;
|
||||
|
||||
@State width1: number = 0;
|
||||
|
@ -41,24 +43,24 @@ export struct CropImagePage2 {
|
|||
Column() {
|
||||
Button('点击解析图片')
|
||||
.onClick(() => {
|
||||
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.bmpSample').id)
|
||||
.then(data => {
|
||||
((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
|
||||
.getMediaContent($r('app.media.bmpSample').id)
|
||||
.then((data:Uint8Array) => {
|
||||
let arrayBuffer = FileUtils.getInstance().uint8ArrayToBuffer(data);
|
||||
let optionx = new PixelMapCrop.Options();
|
||||
let optionx = new Options();
|
||||
optionx.setWidth(800)
|
||||
.setHeight(800)
|
||||
.setCropFunction((err, pixelmap, sx, sy) => {
|
||||
.setCropFunction((err:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number) => {
|
||||
console.log('PMC setCropFunction callback')
|
||||
if (err) {
|
||||
console.error('PMC crop err =' + err)
|
||||
} else {
|
||||
|
||||
this.width1 = sx * 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, () => {
|
||||
this.options1 = optionx;
|
||||
|
@ -87,10 +89,14 @@ export struct CropImagePage2 {
|
|||
})
|
||||
.scale({ x: this._scale, y: this._scale, z: 1.0 })
|
||||
.gesture(GestureGroup(GestureMode.Parallel,
|
||||
RotationGesture({ fingers: 2 }).onActionUpdate(event => {
|
||||
this._rotate = event.angle;
|
||||
}), PinchGesture({ fingers: 2 }).onActionUpdate(event => {
|
||||
this._scale = event.scale;
|
||||
RotationGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
|
||||
if(event != undefined) {
|
||||
this._rotate = event.angle;
|
||||
}
|
||||
}), PinchGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
|
||||
if(event != undefined) {
|
||||
this._scale = event.scale;
|
||||
}
|
||||
})))
|
||||
}
|
||||
.backgroundColor(Color.Brown)
|
||||
|
|
|
@ -14,7 +14,7 @@
|
|||
*/
|
||||
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
|
||||
import { ImageKnifeComponent, ImageKnifeOption, } from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
|
@ -26,7 +26,7 @@ struct DataShareUriLoadPage {
|
|||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed')
|
||||
};
|
||||
private globalGifWorker: any = undefined
|
||||
|
||||
|
||||
build() {
|
||||
Scroll() {
|
||||
|
@ -42,7 +42,7 @@ struct DataShareUriLoadPage {
|
|||
let fileKeyObj = mediaLibrary.FileKey;
|
||||
let imageType = mediaLibrary.MediaType.IMAGE;
|
||||
// 创建文件获取选项,此处参数为获取image类型的文件资源
|
||||
let imagesFetchOp = {
|
||||
let imagesFetchOp:mediaLibrary.MediaFetchOptions = {
|
||||
selections: fileKeyObj.MEDIA_TYPE + '= ?',
|
||||
selectionArgs: [imageType.toString()],
|
||||
};
|
||||
|
|
|
@ -13,14 +13,18 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
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 resourceManager from '@ohos.resourceManager';
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import common from '@ohos.app.ability.common';
|
||||
@Entry
|
||||
@Component
|
||||
struct gifTestCasePage {
|
||||
|
||||
@State pixels:PixelMap = undefined
|
||||
private globalGifWorker = undefined;
|
||||
@State pixels?:PixelMap = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined;
|
||||
|
||||
build() {
|
||||
Scroll() {
|
||||
|
@ -28,7 +32,8 @@ struct gifTestCasePage {
|
|||
Flex({direction:FlexDirection.Row}){
|
||||
Button("加载gif图片")
|
||||
.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 => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength)
|
||||
let gifImpl = new GIFParseImpl();
|
||||
|
@ -42,14 +47,15 @@ struct gifTestCasePage {
|
|||
}
|
||||
},undefined,true)
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
|
||||
}).margin({left:5}).backgroundColor(Color.Blue)
|
||||
Button("加载gif图片自带worker")
|
||||
.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 => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length = ' + data.byteLength)
|
||||
let local_worker = new worker.ThreadWorker('entry/ets/workers/GifLoadWorker.ts', {
|
||||
|
@ -67,14 +73,15 @@ struct gifTestCasePage {
|
|||
}
|
||||
},local_worker)
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
|
||||
}).margin({left:5}).backgroundColor(Color.Blue)
|
||||
Button("加载gif图片全局配置worker")
|
||||
.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 => {
|
||||
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));
|
||||
})
|
||||
|
||||
|
@ -116,7 +123,10 @@ struct gifTestCasePage {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
(ImageKnifeGlobal.getInstance().getImageKnife())?.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -16,13 +16,15 @@ import router from '@system.router';
|
|||
import {
|
||||
ImageKnifeComponent,
|
||||
ImageKnifeOption,
|
||||
ImageKnifeGlobal,
|
||||
ImageKnife
|
||||
} from '@ohos/imageknife'
|
||||
import worker from '@ohos.worker';
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct IndexFunctionDemo {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.icon'),
|
||||
|
@ -91,7 +93,10 @@ struct IndexFunctionDemo {
|
|||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
// gif解析在子线程,请在页面构建后创建worker,注入imageknife
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
imageKnife?.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -14,6 +14,7 @@
|
|||
*/
|
||||
import {ImageKnifeComponent, ScaleType} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
import {Material} from './model/Material'
|
||||
import {TestDataSource} from './model/TestDataSource'
|
||||
|
@ -32,10 +33,13 @@ struct ManyPhotoShowPage {
|
|||
|
||||
Button('设置磁盘存储为50M')
|
||||
.onClick(()=>{
|
||||
let disk:DiskLruCache = globalThis.ImageKnife.getDiskMemoryCache();
|
||||
disk.setMaxSize(50*1024*1024)
|
||||
Prompt.showToast({message:"设置成功"})
|
||||
|
||||
if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
|
||||
let disk: DiskLruCache | undefined = (ImageKnifeGlobal.getInstance().getImageKnife())?.getDiskMemoryCache();
|
||||
if(disk != undefined) {
|
||||
disk.setMaxSize(50 * 1024 * 1024)
|
||||
Prompt.showToast({ message: "设置成功" })
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
List({ space: 20, scroller: this.elementScroller }) {
|
||||
|
|
|
@ -12,14 +12,14 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
export class BasicDataSource implements IDataSource {
|
||||
export class BasicDataSource<T> implements IDataSource {
|
||||
private listeners: DataChangeListener[] = [];
|
||||
|
||||
public totalCount(): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public getData(index: number): any {
|
||||
public getData(index: number):T | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
export class Material{
|
||||
material_id: string;
|
||||
thumbnail: string;
|
||||
name: string;
|
||||
material_id: string ='';
|
||||
thumbnail: string = '';
|
||||
name: string ='';
|
||||
}
|
|
@ -14,7 +14,7 @@
|
|||
*/
|
||||
import {BasicDataSource} from './BasicDataSource'
|
||||
import { Material } from './Material';
|
||||
export class TestDataSource extends BasicDataSource {
|
||||
export class TestDataSource extends BasicDataSource<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:"通用天空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;
|
||||
}
|
||||
|
||||
public getData(index: number): any {
|
||||
public getData(index: number): Material | undefined {
|
||||
return this.dataArray[index];
|
||||
}
|
||||
|
||||
|
|
|
@ -15,18 +15,19 @@
|
|||
import router from '@system.router';
|
||||
import { Pngj } from '@ohos/imageknife'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import { FileUtils } from '@ohos/imageknife'
|
||||
import { FileUtils,ImageKnifeGlobal } from '@ohos/imageknife'
|
||||
import featureability from '@ohos.ability.featureAbility'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker';
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import common from '@ohos.app.ability.common';
|
||||
@Entry
|
||||
@Component
|
||||
struct PngjTestCasePage {
|
||||
pngSource1: ArrayBuffer = undefined;
|
||||
pngSource2: ArrayBuffer = undefined;
|
||||
pngSource3: ArrayBuffer = undefined;
|
||||
pngSource4: ArrayBuffer = undefined;
|
||||
pngSource1?: ArrayBuffer = undefined;
|
||||
pngSource2?: ArrayBuffer = undefined;
|
||||
pngSource3?: ArrayBuffer = undefined;
|
||||
pngSource4?: ArrayBuffer = undefined;
|
||||
pngdecodeRun1: boolean = false;
|
||||
pngdecodeRun2: boolean = false;
|
||||
pngdecodeRun3: boolean = false;
|
||||
|
@ -52,29 +53,29 @@ struct PngjTestCasePage {
|
|||
|
||||
Button(this.hint7).fontSize(30)
|
||||
.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 => {
|
||||
this.pngSource1 = FileUtils.getInstance().uint8ArrayToBuffer(data);
|
||||
this.hint7 = '获取buffer成功,可以测试'
|
||||
})
|
||||
.catch(err => {
|
||||
.catch( (err:BusinessError) => {
|
||||
console.log('点击获取Png图片buffer err=' + err)
|
||||
})
|
||||
})
|
||||
Button('测试readPng')
|
||||
.onClick(() => {
|
||||
|
||||
if (this.pngSource1) {
|
||||
if (this.pngSource1!=undefined) {
|
||||
if (!this.pngdecodeRun1) {
|
||||
this.pngdecodeRun1 = true;
|
||||
let pngj = new Pngj();
|
||||
pngj.readPngImageInfo(this.pngSource1, (sender, value) => {
|
||||
pngj.readPngImageInfo(this.pngSource1,{pngCallback: (sender, value) => {
|
||||
this.hint1 = JSON.stringify(value);
|
||||
this.pngdecodeRun1 = false;
|
||||
})
|
||||
}})
|
||||
|
||||
} else {
|
||||
this.hint7 = '已经在执行了,请稍等'
|
||||
|
@ -91,22 +92,26 @@ struct PngjTestCasePage {
|
|||
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
||||
Button(this.hint8).fontSize(30)
|
||||
.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 => {
|
||||
this.pngSource2 = FileUtils.getInstance().uint8ArrayToBuffer(data);
|
||||
this.hint8 = '获取buffer成功,可以测试'
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('点击获取Png图片buffer err=' + err)
|
||||
})
|
||||
})
|
||||
Button('readPngAsync')
|
||||
.onClick(() => {
|
||||
|
||||
if (this.pngSource2) {
|
||||
if (this.pngSource2!=undefined) {
|
||||
if (!this.pngdecodeRun2) {
|
||||
this.pngdecodeRun2 = true;
|
||||
let pngj = new Pngj();
|
||||
|
@ -114,12 +119,12 @@ struct PngjTestCasePage {
|
|||
type: 'classic',
|
||||
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.hint2 = 'img with=' + value.width + ' img height=' + value.height
|
||||
+ ' img depth=' + value.depth + ' img ctype=' + value.ctype
|
||||
this.pngdecodeRun2 = false;
|
||||
})
|
||||
}})
|
||||
|
||||
} else {
|
||||
this.hint8 = '已经在执行了,请稍等'
|
||||
|
@ -136,22 +141,22 @@ struct PngjTestCasePage {
|
|||
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
|
||||
Button(this.hint9).fontSize(30)
|
||||
.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 => {
|
||||
this.pngSource3 = FileUtils.getInstance().uint8ArrayToBuffer(data);
|
||||
this.hint9 = '获取buffer成功,可以测试'
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('点击获取Png图片buffer err=' + err)
|
||||
})
|
||||
})
|
||||
Button('测试writePngWithString')
|
||||
.onClick(() => {
|
||||
|
||||
if (this.pngSource3) {
|
||||
if (this.pngSource3 != undefined) {
|
||||
if (!this.pngdecodeRun3) {
|
||||
this.pngdecodeRun3 = true;
|
||||
let pngj = new Pngj();
|
||||
|
@ -159,7 +164,7 @@ struct PngjTestCasePage {
|
|||
type: 'classic',
|
||||
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
|
||||
FileUtils.getInstance().createFileProcess(
|
||||
this.rootFolder + '/pngj',
|
||||
|
@ -168,7 +173,7 @@ struct PngjTestCasePage {
|
|||
let png1 = new Uint8Array(value)
|
||||
this.hint3 = 'png写入后长度' + png1.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng.png' + '保存后使用2进制查看数据是否新增'
|
||||
this.pngdecodeRun3 = false;
|
||||
})
|
||||
}})
|
||||
} else {
|
||||
this.hint9 = '已经在执行了,请稍等'
|
||||
}
|
||||
|
@ -186,21 +191,21 @@ struct PngjTestCasePage {
|
|||
|
||||
Button(this.hint10).fontSize(30)
|
||||
.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 => {
|
||||
this.pngSource4 = FileUtils.getInstance().uint8ArrayToBuffer(data);
|
||||
this.hint10 = '获取buffer成功,可以测试'
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('点击获取Png图片buffer err=' + err)
|
||||
})
|
||||
})
|
||||
Button('writePng')
|
||||
.onClick(()=>{
|
||||
if (this.pngSource4) {
|
||||
if (this.pngSource4 != undefined) {
|
||||
if (!this.pngdecodeRun4) {
|
||||
this.pngdecodeRun4 = true;
|
||||
let pngj = new Pngj();
|
||||
|
@ -208,7 +213,7 @@ struct PngjTestCasePage {
|
|||
type: 'classic',
|
||||
name: 'writePngAsync'
|
||||
})
|
||||
pngj.writePngAsync(png_worker, this.pngSource4, (sender, value) => {
|
||||
pngj.writePngAsync(png_worker, this.pngSource4,{pngCallback: (sender:ArrayBuffer, value:ArrayBuffer) => {
|
||||
this.pngSource4 = sender
|
||||
FileUtils.getInstance().createFileProcess(
|
||||
this.rootFolder + '/pngj',
|
||||
|
@ -217,7 +222,7 @@ struct PngjTestCasePage {
|
|||
let png2 = new Uint8Array(value)
|
||||
this.hint4 = 'png2未写入长度' + png2.byteLength + '目录文件:' + this.rootFolder + '/pngj/newPng2.png' + '保存后使用2进制查看数据是否新增'
|
||||
this.pngdecodeRun4 = false;
|
||||
})
|
||||
}})
|
||||
} else {
|
||||
this.hint10 = '已经在执行了,请稍等'
|
||||
}
|
||||
|
|
|
@ -15,7 +15,7 @@
|
|||
|
||||
import {LruCache} from '@ohos/imageknife'
|
||||
|
||||
function getRandomInt(min, max) {
|
||||
function getRandomInt(min:number, max:number):number {
|
||||
min = Math.ceil(min);
|
||||
max = Math.floor(max);
|
||||
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
|
||||
|
|
|
@ -13,13 +13,16 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
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
|
||||
@Component
|
||||
struct svgTestCasePage {
|
||||
|
||||
@State svgSamplePixelMap:PixelMap = undefined
|
||||
@State svgIconPixelMap:PixelMap = undefined
|
||||
@State svgSamplePixelMap?:PixelMap = undefined
|
||||
@State svgIconPixelMap?:PixelMap = undefined
|
||||
|
||||
build() {
|
||||
Scroll() {
|
||||
|
@ -28,15 +31,16 @@ struct svgTestCasePage {
|
|||
Button("加载SVG图片")
|
||||
.onClick(()=>{
|
||||
|
||||
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.svgSample').id)
|
||||
.then(data => {
|
||||
((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
|
||||
.getMediaContent($r('app.media.svgSample').id)
|
||||
.then((data:Uint8Array) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
|
||||
let svgImpl = new SVGParseImpl();
|
||||
svgImpl.parseSvg(data.buffer).then((pixelmap)=>{
|
||||
this.svgSamplePixelMap = pixelmap;
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
|
||||
|
@ -57,7 +61,8 @@ struct svgTestCasePage {
|
|||
Button("加载SVG图片")
|
||||
.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 => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
|
||||
let svgImpl = new SVGParseImpl();
|
||||
|
@ -65,7 +70,7 @@ struct svgTestCasePage {
|
|||
this.svgIconPixelMap = pixelmap;
|
||||
})
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err:BusinessError) => {
|
||||
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
|
||||
})
|
||||
|
||||
|
|
|
@ -12,19 +12,20 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import router from '@system.router';
|
||||
|
||||
import {
|
||||
ImageKnifeComponent,
|
||||
ImageKnifeOption,
|
||||
ImageKnifeGlobal,
|
||||
ImageKnife,
|
||||
ImageKnifeDrawFactory,
|
||||
ScaleType
|
||||
} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker';
|
||||
@Entry
|
||||
@Component
|
||||
struct tempUrlTestPage {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.icon'),
|
||||
|
@ -89,8 +90,11 @@ struct tempUrlTestPage {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
// gif解析在子线程,请在页面构建后创建worker,注入imageknife
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
// gif解析在子线程,请在页面构建后创建worker,注入imageknife
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -13,18 +13,20 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
import {RequestOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeData} from '@ohos/imageknife'
|
||||
import {AllCacheInfo,IAllCacheInfoCallback} from '@ohos/imageknife'
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {TransformType} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
|
||||
import {BusinessError} from '@ohos.base'
|
||||
@Entry
|
||||
@Component
|
||||
struct TestAllCacheInfoPage {
|
||||
@State nativePixelMap: PixelMap = undefined;
|
||||
@State networkPixelMap: PixelMap = undefined;
|
||||
allCacheInfoCallback1 =(allCacheInfo)=>{
|
||||
@State nativePixelMap?: PixelMap = undefined;
|
||||
@State networkPixelMap?: PixelMap = undefined;
|
||||
allCacheInfoCallback1:IAllCacheInfoCallback ={callback:(allCacheInfo:AllCacheInfo)=>{
|
||||
let info = allCacheInfo as AllCacheInfo;
|
||||
console.log("AllCacheInfoCallback imageknifecomponent1 memory ="+JSON.stringify(info.memoryCacheInfo))
|
||||
console.log("AllCacheInfoCallback imageknifecomponent1 resource ="+JSON.stringify(info.resourceCacheInfo))
|
||||
|
@ -32,8 +34,8 @@ struct TestAllCacheInfoPage {
|
|||
this.cacheinfo3 = "memory="+JSON.stringify(info.memoryCacheInfo)+
|
||||
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+
|
||||
"\n data ="+JSON.stringify(info.dataCacheInfo)
|
||||
}
|
||||
allCacheInfoCallback2 =(allCacheInfo)=>{
|
||||
}}
|
||||
allCacheInfoCallback2:IAllCacheInfoCallback ={callback:(allCacheInfo:AllCacheInfo)=>{
|
||||
let info = allCacheInfo as AllCacheInfo;
|
||||
console.log("AllCacheInfoCallback ImageKnifeComponent memory ="+JSON.stringify(info.memoryCacheInfo))
|
||||
console.log("AllCacheInfoCallback ImageKnifeComponent resource ="+JSON.stringify(info.resourceCacheInfo))
|
||||
|
@ -41,7 +43,7 @@ struct TestAllCacheInfoPage {
|
|||
this.cacheinfo4 = "memory="+JSON.stringify(info.memoryCacheInfo)+
|
||||
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+
|
||||
"\n data ="+JSON.stringify(info.dataCacheInfo)
|
||||
}
|
||||
}}
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.pngSample'),
|
||||
|
@ -164,12 +166,11 @@ struct TestAllCacheInfoPage {
|
|||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load($r('app.media.pngSample'))
|
||||
.setImageViewSize({width:300,height:300})
|
||||
.addListener((err, data) => {
|
||||
let pack = undefined;
|
||||
pack = data.drawPixelMap.imagePixelMap as PixelMap;;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
let pack = data.drawPixelMap?.imagePixelMap as PixelMap;;
|
||||
this.nativePixelMap = pack;
|
||||
return false;
|
||||
}).addAllCacheInfoCallback((allCacheInfo)=>{
|
||||
}}).addAllCacheInfoCallback({callback:(allCacheInfo:AllCacheInfo)=>{
|
||||
let info = allCacheInfo as AllCacheInfo;
|
||||
console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo))
|
||||
console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo))
|
||||
|
@ -177,20 +178,19 @@ struct TestAllCacheInfoPage {
|
|||
this.cacheinfo1 = "memory="+JSON.stringify(info.memoryCacheInfo)+
|
||||
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+
|
||||
"\n data ="+JSON.stringify(info.dataCacheInfo)
|
||||
})
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
}})
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
private testAllCacheInfoNetwork() {
|
||||
let ImageKnifeOption = new RequestOption();
|
||||
ImageKnifeOption.load("https://hbimg.huabanimg.com/0ef60041445edcfd6b38d20e19024b2cd9281dcc3525a4-Vy8fYO_fw658/format/webp")
|
||||
.addListener((err, data) => {
|
||||
let pack = undefined;
|
||||
pack = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
let pack = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
this.networkPixelMap = pack;
|
||||
console.log("imageknife2 图片2 赋值!")
|
||||
return false;
|
||||
}).addAllCacheInfoCallback((allCacheInfo)=>{
|
||||
}}).addAllCacheInfoCallback({callback:(allCacheInfo:AllCacheInfo)=>{
|
||||
let info = allCacheInfo as AllCacheInfo;
|
||||
console.log("AllCacheInfoCallback memory ="+JSON.stringify(info.memoryCacheInfo))
|
||||
console.log("AllCacheInfoCallback resource ="+JSON.stringify(info.resourceCacheInfo))
|
||||
|
@ -198,12 +198,12 @@ struct TestAllCacheInfoPage {
|
|||
this.cacheinfo2 = "memory="+JSON.stringify(info.memoryCacheInfo)+
|
||||
"\n resource ="+JSON.stringify(info.resourceCacheInfo)+
|
||||
"\n data ="+JSON.stringify(info.dataCacheInfo)
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({width:300,height:300})
|
||||
.rotateImage(180)
|
||||
ImageKnife.call(ImageKnifeOption);
|
||||
ImageKnife?.call(ImageKnifeOption);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var ImageKnife = globalThis.ImageKnife
|
||||
let ImageKnife = (ImageKnifeGlobal.getInstance().getImageKnife())
|
|
@ -14,13 +14,14 @@
|
|||
*/
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import {ImageKnife} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker'
|
||||
@Entry
|
||||
@Component
|
||||
struct TestGifDontAnimatePage {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
|
@ -90,7 +91,10 @@ struct TestGifDontAnimatePage {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife : ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife!= undefined) {
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* 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 Prompt from '@system.prompt'
|
||||
|
||||
|
@ -23,8 +23,8 @@ struct TestGifLoadWithWorkerPage {
|
|||
@State options: ImageKnifeOption = {
|
||||
loadSrc: $r('app.media.icon')
|
||||
}
|
||||
private my_worker: worker.ThreadWorker;
|
||||
private my_gif_worker: worker.ThreadWorker;
|
||||
private my_worker?: worker.ThreadWorker = undefined;
|
||||
private my_gif_worker?: worker.ThreadWorker = undefined;
|
||||
|
||||
/**
|
||||
* 界面进入时回调
|
||||
|
@ -86,7 +86,7 @@ struct TestGifLoadWithWorkerPage {
|
|||
this.my_gif_worker.onmessage = (e: MessageEvents) => {
|
||||
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的消失
|
||||
this.options = {
|
||||
|
@ -100,9 +100,9 @@ struct TestGifLoadWithWorkerPage {
|
|||
Button('加载gif')
|
||||
.margin({ top: 16 })
|
||||
.onClick(() => {
|
||||
console.log("ImageKnifeComponent button 加载gif onClick()")
|
||||
|
||||
globalThis.ImageKnife.setGifWorker(undefined)
|
||||
|
||||
(ImageKnifeGlobal.getInstance().getImageKnife()).setGifWorker(undefined)
|
||||
|
||||
//主线程加载gif,阻塞toast的消失
|
||||
this.options = {
|
||||
|
|
|
@ -14,6 +14,8 @@
|
|||
*/
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import {ImageKnife} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker'
|
||||
|
@ -21,7 +23,7 @@ import worker from '@ohos.worker'
|
|||
@Component
|
||||
struct TestImageKnifeOptionChangedPage {
|
||||
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
|
@ -190,7 +192,10 @@ struct TestImageKnifeOptionChangedPage {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -14,9 +14,11 @@
|
|||
*/
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {BaseTransform} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
import {GrayscaleTransformation} from '@ohos/imageknife'
|
||||
import {SketchFilterTransformation} from '@ohos/imageknife'
|
||||
import image from '@ohos.multimedia.image'
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
|
@ -38,6 +40,7 @@ struct TestImageKnifeOptionChangedPage2 {
|
|||
Flex({direction:FlexDirection.Row}){
|
||||
Button("网络jpg")
|
||||
.onClick(()=>{
|
||||
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
|
||||
|
||||
|
@ -45,7 +48,7 @@ struct TestImageKnifeOptionChangedPage2 {
|
|||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
|
||||
thumbSizeMultiplier:0.1,
|
||||
transformation:new RotateImageTransformation(180)
|
||||
transformation:rotateTrans
|
||||
};
|
||||
}).margin({left:5}).backgroundColor(Color.Blue)
|
||||
Button("png")
|
||||
|
|
|
@ -14,16 +14,20 @@
|
|||
*/
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import {ImageKnife} from '@ohos/imageknife'
|
||||
import {ScaleType} from '@ohos/imageknife'
|
||||
import {RotateImageTransformation} from '@ohos/imageknife'
|
||||
import {GrayscaleTransformation} from '@ohos/imageknife'
|
||||
import {SketchFilterTransformation} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker'
|
||||
import {BaseTransform} from '@ohos/imageknife'
|
||||
import image from '@ohos.multimedia.image'
|
||||
@Entry
|
||||
@Component
|
||||
struct TestImageKnifeOptionChangedPage3 {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
|
@ -41,13 +45,14 @@ struct TestImageKnifeOptionChangedPage3 {
|
|||
Flex({direction:FlexDirection.Row}){
|
||||
Button("本地jpg")
|
||||
.onClick(()=>{
|
||||
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
mainScaleType: ScaleType.FIT_CENTER,
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
thumbSizeMultiplier:0.1,
|
||||
transformation:new RotateImageTransformation(180),
|
||||
transformation:rotateTrans,
|
||||
};
|
||||
animateTo({
|
||||
duration: 500,
|
||||
|
@ -65,13 +70,15 @@ struct TestImageKnifeOptionChangedPage3 {
|
|||
}).margin({left:5}).backgroundColor(Color.Blue)
|
||||
Button("本地png")
|
||||
.onClick(()=>{
|
||||
|
||||
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: $r('app.media.pngSample'),
|
||||
mainScaleType: ScaleType.FIT_CENTER,
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
thumbSizeMultiplier:0.1,
|
||||
transformation:new RotateImageTransformation(180),
|
||||
transformation:rotateTrans,
|
||||
};
|
||||
animateTo({
|
||||
duration: 500,
|
||||
|
@ -141,13 +148,14 @@ struct TestImageKnifeOptionChangedPage3 {
|
|||
Flex({direction:FlexDirection.Row}){
|
||||
Button("网络jpg")
|
||||
.onClick(()=>{
|
||||
let rotateTrans:BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
|
||||
placeholderSrc: $r('app.media.icon_loading'),
|
||||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
displayProgress:true,
|
||||
thumbSizeMultiplier:0.1,
|
||||
transformation:new RotateImageTransformation(180)
|
||||
transformation:rotateTrans
|
||||
};
|
||||
}).margin({left:5}).backgroundColor(Color.Blue)
|
||||
Button("网络png")
|
||||
|
@ -203,7 +211,10 @@ struct TestImageKnifeOptionChangedPage3 {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -21,14 +21,18 @@ import {
|
|||
SketchFilterTransformation,
|
||||
ScaleTypeHelper,
|
||||
IDrawLifeCycle,
|
||||
ScaleType
|
||||
ScaleType,
|
||||
ImageKnifeGlobal,
|
||||
BaseTransform
|
||||
} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker';
|
||||
import image from '@ohos.multimedia.image';
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct TestImageKnifeOptionChangedPage4 {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?: worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
|
@ -37,7 +41,7 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
|
||||
thumbSizeMultiplier: 0.1,
|
||||
drawLifeCycle:this.createViewLifeCycle()
|
||||
drawLifeCycle: this.createViewLifeCycle()
|
||||
};
|
||||
private mTimerId: number = 0
|
||||
|
||||
|
@ -47,6 +51,7 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
Flex({ direction: FlexDirection.Row }) {
|
||||
Button("网络jpg")
|
||||
.onClick(() => {
|
||||
let rotateTrans: BaseTransform<image.PixelMap> = new RotateImageTransformation(180)
|
||||
this.imageKnifeOption1 = {
|
||||
loadSrc: "https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB",
|
||||
|
||||
|
@ -54,8 +59,8 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
errorholderSrc: $r('app.media.icon_failed'),
|
||||
|
||||
thumbSizeMultiplier: 0.1,
|
||||
transformation: new RotateImageTransformation(180),
|
||||
drawLifeCycle:this.createViewLifeCycle()
|
||||
transformation: rotateTrans,
|
||||
drawLifeCycle: this.createViewLifeCycle()
|
||||
};
|
||||
}).margin({ left: 5 }).backgroundColor(Color.Blue)
|
||||
Button("网络png")
|
||||
|
@ -68,10 +73,11 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
|
||||
thumbSizeMultiplier: 0.1,
|
||||
transformations: [new RotateImageTransformation(180)],
|
||||
drawLifeCycle:this.createViewLifeCycle()
|
||||
drawLifeCycle: this.createViewLifeCycle()
|
||||
};
|
||||
}).margin({ left: 5 }).backgroundColor(Color.Blue)
|
||||
}.margin({ top: 15 })
|
||||
|
||||
Flex({ direction: FlexDirection.Row }) {
|
||||
Button("网络bmp")
|
||||
.onClick(() => {
|
||||
|
@ -83,7 +89,7 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
|
||||
thumbSizeMultiplier: 0.1,
|
||||
transformations: [new GrayscaleTransformation()],
|
||||
drawLifeCycle:this.createViewLifeCycle()
|
||||
drawLifeCycle: this.createViewLifeCycle()
|
||||
};
|
||||
}).margin({ left: 5 }).backgroundColor(Color.Blue)
|
||||
Button("网络webp")
|
||||
|
@ -96,7 +102,7 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
|
||||
thumbSizeMultiplier: 0.1,
|
||||
transformations: [new SketchFilterTransformation()],
|
||||
drawLifeCycle:this.createViewLifeCycle()
|
||||
drawLifeCycle: this.createViewLifeCycle()
|
||||
};
|
||||
}).margin({ left: 5 }).backgroundColor(Color.Blue)
|
||||
}.margin({ top: 15 })
|
||||
|
@ -118,42 +124,52 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
||||
aboutToDisappear() {
|
||||
if (this.globalGifWorker) {
|
||||
this.globalGifWorker.terminate();
|
||||
}
|
||||
}
|
||||
|
||||
drawMainAnimate(index, context, scaleType, imagePixelMap, widthPixel, heightPixel, compWidth, compHeight) {
|
||||
console.log('drawMainAnimate index = '+index)
|
||||
drawMainAnimate_index: number = 0;
|
||||
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)
|
||||
context.save()
|
||||
context.beginPath();
|
||||
let clipScale = (this.drawMainAnimate_index / 30.0)
|
||||
this.drawMainAnimate_context?.save()
|
||||
this.drawMainAnimate_context?.beginPath();
|
||||
let path2d = new Path2D()
|
||||
let maxRadius = Math.sqrt(compWidth / 2 * compWidth / 2 + compHeight / 2 * compHeight / 2)
|
||||
path2d.arc(compWidth / 2, compHeight / 2, maxRadius * clipScale, 0, Math.PI * 2)
|
||||
context.clip(path2d)
|
||||
context.save()
|
||||
ScaleTypeHelper.drawImageWithScaleType(context, scaleType, imagePixelMap, px2vp(widthPixel), px2vp(heightPixel), compWidth, compHeight,0,0)
|
||||
context.restore();
|
||||
context.restore();
|
||||
if(index<30){
|
||||
index++
|
||||
let nextFunc = this.drawMainAnimate.bind(this,index, context, scaleType, imagePixelMap, widthPixel, heightPixel, compWidth, compHeight)
|
||||
// @ts-ignore
|
||||
this.mTimerId = setTimeout(nextFunc, 1000/30.0)
|
||||
}else{
|
||||
let maxRadius = Math.sqrt(this.drawMainAnimate_compWidth / 2 * this.drawMainAnimate_compWidth / 2 + this.drawMainAnimate_compHeight / 2 * this.drawMainAnimate_compHeight / 2)
|
||||
path2d.arc(this.drawMainAnimate_compWidth / 2, this.drawMainAnimate_compHeight / 2, maxRadius * clipScale, 0, Math.PI * 2)
|
||||
this.drawMainAnimate_context?.clip(path2d)
|
||||
this.drawMainAnimate_context?.save()
|
||||
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)
|
||||
this.drawMainAnimate_context?.restore();
|
||||
this.drawMainAnimate_context?.restore();
|
||||
if (this.drawMainAnimate_index < 30) {
|
||||
this.drawMainAnimate_index++
|
||||
let nextFunc = this.drawMainAnimate
|
||||
|
||||
this.mTimerId = setTimeout(nextFunc, 1000 / 30.0)
|
||||
} else {
|
||||
// 不做处理
|
||||
}
|
||||
}
|
||||
private stopAnimate(){
|
||||
if(this.mTimerId > 0){
|
||||
|
||||
private stopAnimate() {
|
||||
if (this.mTimerId > 0) {
|
||||
clearTimeout(this.mTimerId)
|
||||
this.mTimerId = 0
|
||||
}else{
|
||||
} else {
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -162,16 +178,16 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
let viewLifeCycle: IDrawLifeCycle = {
|
||||
// 展示占位图
|
||||
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
this.stopAnimate()
|
||||
return false;
|
||||
},
|
||||
// 展示加载进度
|
||||
displayProgress: (context: CanvasRenderingContext2D, progress: number, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
this.stopAnimate()
|
||||
context.save();
|
||||
context.clearRect(0,0,compWidth,compHeight)
|
||||
context.clearRect(0, 0, compWidth, compHeight)
|
||||
let pi = Math.PI * 2 / 100; //pi 讲圆的周长划分为100份
|
||||
let rate = progress - 25;
|
||||
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) => {
|
||||
// @ts-ignore
|
||||
|
||||
this.stopAnimate()
|
||||
return false;
|
||||
},
|
||||
|
@ -221,14 +237,24 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
this.stopAnimate()
|
||||
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
|
||||
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.mTimerId = setTimeout(func, 1000/30.0)
|
||||
|
||||
this.drawMainAnimate_index = 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!')
|
||||
})
|
||||
|
@ -239,14 +265,14 @@ struct TestImageKnifeOptionChangedPage4 {
|
|||
|
||||
// 展示重试图层
|
||||
displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
this.stopAnimate()
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示失败占位图
|
||||
displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
this.stopAnimate()
|
||||
return false;
|
||||
}
|
||||
|
|
|
@ -16,7 +16,9 @@ import {
|
|||
GrayscaleTransformation,
|
||||
ImageKnifeComponent,
|
||||
ImageKnifeData,
|
||||
ImageKnifeGlobal,
|
||||
ImageKnifeOption,
|
||||
ImageKnife,
|
||||
RotateImageTransformation,
|
||||
SketchFilterTransformation,
|
||||
ScaleTypeHelper,
|
||||
|
@ -24,12 +26,11 @@ import {
|
|||
ScaleType,
|
||||
ImageKnifeDrawFactory
|
||||
} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import worker from '@ohos.worker';
|
||||
@Entry
|
||||
@Component
|
||||
struct TestImageKnifeOptionChangedPage5 {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
|
@ -100,7 +101,10 @@ struct TestImageKnifeOptionChangedPage5 {
|
|||
type: 'classic',
|
||||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
let imageKnife:ImageKnife|undefined = ImageKnifeGlobal.getInstance().getImageKnife()
|
||||
if(imageKnife != undefined) {
|
||||
imageKnife.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
@ -109,7 +113,7 @@ struct TestImageKnifeOptionChangedPage5 {
|
|||
}
|
||||
|
||||
private choiceViewLifeCycle(type:DrawType): IDrawLifeCycle {
|
||||
let viewLifeCycle = undefined;
|
||||
let viewLifeCycle:IDrawLifeCycle|undefined = undefined;
|
||||
switch(type){
|
||||
case DrawType.Oval:
|
||||
viewLifeCycle = ImageKnifeDrawFactory.createOvalLifeCycle(5,"#ff00ff")
|
||||
|
@ -122,7 +126,7 @@ struct TestImageKnifeOptionChangedPage5 {
|
|||
viewLifeCycle = {
|
||||
// 展示占位图
|
||||
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
// 展示加载进度
|
||||
|
@ -131,20 +135,20 @@ struct TestImageKnifeOptionChangedPage5 {
|
|||
},
|
||||
// 展示缩略图
|
||||
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示主图
|
||||
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
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
|
||||
console.log('imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType)
|
||||
context.save();
|
||||
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();
|
||||
console.log('TestImageKnifeOptionChangedPage4 drawMainSource end!')
|
||||
})
|
||||
|
|
|
@ -13,15 +13,17 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
import {ImageKnifeComponent} from '@ohos/imageknife'
|
||||
import {ImageKnifeData} from '@ohos/imageknife'
|
||||
import {ImageKnifeOption} from '@ohos/imageknife'
|
||||
import {RequestOption} from '@ohos/imageknife'
|
||||
import ArkWorker from '@ohos.worker'
|
||||
import {ImageKnifeGlobal } from '@ohos/imageknife'
|
||||
import worker from '@ohos.worker'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct TestPreloadPage {
|
||||
private globalGifWorker:any = undefined
|
||||
private globalGifWorker?:worker.ThreadWorker = undefined
|
||||
@State imageKnifeOption1: ImageKnifeOption =
|
||||
{
|
||||
loadSrc: $r('app.media.jpgSample'),
|
||||
|
@ -82,15 +84,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.gifSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载本地资源gif 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源gif成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -116,15 +118,15 @@ struct TestPreloadPage {
|
|||
request.load($r('app.media.gifSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.dontAnimate()
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err ) {
|
||||
console.log('预加载本地资源gif静态 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源gif静态成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -151,15 +153,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源gif 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -183,15 +185,15 @@ struct TestPreloadPage {
|
|||
request.load('https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.dontAnimate()
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源gif静态 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源gif静态成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -222,15 +224,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.svgSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err ) {
|
||||
console.log('预加载本地资源svg 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源svg成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -261,15 +263,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('http://124.222.187.78/download/test.svg')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源gif 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源gif成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -302,15 +304,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.jpgSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载本地资源webp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源webp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -341,15 +343,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('https://hbimg.huabanimg.com/95a6d37a39aa0b70d48fa18dc7df8309e2e0e8e85571e-x4hhks_fw658/format/webp')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源webp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源webp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -380,15 +382,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.bmpSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载本地资源bmp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源bmp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -419,15 +421,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('https://img-blog.csdn.net/20140514114029140')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
console.log('预加载网络资源bmp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源bmp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -458,15 +460,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.pngSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载本地资源png 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源png成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -497,15 +499,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('https://img-blog.csdnimg.cn/20191215043500229.png')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源bmp 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源bmp成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -536,15 +538,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load($r('app.media.jpgSample'))
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载本地资源jpg 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载本地资源jpg成功! imageKnifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -575,15 +577,15 @@ struct TestPreloadPage {
|
|||
let request = new RequestOption();
|
||||
request.load('https://hbimg.huabanimg.com/cc6af25f8d782d3cf3122bef4e61571378271145735e9-vEVggB')
|
||||
.setImageViewSize({ width: 300, height: 300 })
|
||||
.addListener((err, data) => {
|
||||
if (err && err.length > 0) {
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
if (err) {
|
||||
console.log('预加载网络资源jpg 出现错误! err=' + err)
|
||||
} else {
|
||||
console.log('预加载网络资源jpg成功! imageknifedata=' + JSON.stringify(data))
|
||||
}
|
||||
return false;
|
||||
})
|
||||
globalThis.ImageKnife.preload(request);
|
||||
}})
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.preload(request);
|
||||
})
|
||||
.margin({ left: 15 })
|
||||
.backgroundColor(Color.Grey)
|
||||
|
@ -620,7 +622,7 @@ struct TestPreloadPage {
|
|||
name: 'ImageKnifeParseGIF'
|
||||
})
|
||||
// gif解析在子线程,请在页面构建后创建worker,注入imageknife
|
||||
globalThis.ImageKnife.setGifWorker(this.globalGifWorker)
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.setGifWorker(this.globalGifWorker)
|
||||
}
|
||||
aboutToDisappear(){
|
||||
if(this.globalGifWorker){
|
||||
|
|
|
@ -12,8 +12,8 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { ImageKnifeComponent } from '@ohos/imageknife/src/main/ets/components/imageknife/ImageKnifeComponent'
|
||||
import { ImageKnifeOption } from '@ohos/imageknife/src/main/ets/components/imageknife/ImageKnifeOption'
|
||||
import { ImageKnifeComponent } from '@ohos/imageknife'
|
||||
import { ImageKnifeOption } from '@ohos/imageknife'
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { RequestOption } from '@ohos/imageknife'
|
||||
import { RequestOption,ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
import { CropCircleTransformation } from '@ohos/imageknife'
|
||||
import { RoundedCornersTransformation } from '@ohos/imageknife'
|
||||
import {
|
||||
|
@ -32,8 +32,8 @@ import { BlurTransformation } from '@ohos/imageknife'
|
|||
import { PixelationFilterTransformation } from '@ohos/imageknife'
|
||||
import { MaskTransformation } from '@ohos/imageknife'
|
||||
import { SwirlFilterTransformation } from '@ohos/imageknife'
|
||||
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import {ImageKnifeData} from '@ohos/imageknife'
|
||||
/**
|
||||
* PixelMap transform 示例
|
||||
*/
|
||||
|
@ -45,28 +45,28 @@ let mUrl = $r('app.media.pngSample');
|
|||
@Component
|
||||
struct TransformPixelMapPage {
|
||||
@State url: string = "";
|
||||
@State mCropPixelMap: PixelMap = undefined;
|
||||
@State mRoundPixelMap: PixelMap = undefined;
|
||||
@State mCirclePixelMap: PixelMap = undefined;
|
||||
@State mCircleBorderPixelMap: PixelMap = undefined;
|
||||
@State mRotatePixelMap: PixelMap = undefined;
|
||||
@State mSquarePixelMap: PixelMap = undefined;
|
||||
@State mClipTopPixelMap: PixelMap = undefined;
|
||||
@State mClipCenterPixelMap: PixelMap = undefined;
|
||||
@State mClipBottomPixelMap: PixelMap = undefined;
|
||||
@State mGrayscalePixelMap: PixelMap = undefined;
|
||||
@State mBrightnessPixelMap: PixelMap = undefined;
|
||||
@State mContrastPixelMap: PixelMap = undefined;
|
||||
@State mInvertPixelMap: PixelMap = undefined;
|
||||
@State mSepiaPixelMap: PixelMap = undefined;
|
||||
@State mSketchPixelMap: PixelMap = undefined;
|
||||
@State mBlurPixelMap: PixelMap = undefined;
|
||||
@State mPixelPixelMap: PixelMap = undefined;
|
||||
@State mSwirlPixelMap: PixelMap = undefined;
|
||||
@State mMaskPixelMap: PixelMap = undefined;
|
||||
@State mKuwaharaPixelMap: PixelMap = undefined;
|
||||
@State mToonPixelMap: PixelMap = undefined;
|
||||
@State mVignettePixelMap: PixelMap = undefined;
|
||||
@State mCropPixelMap?: PixelMap = undefined;
|
||||
@State mRoundPixelMap?: PixelMap = undefined;
|
||||
@State mCirclePixelMap?: PixelMap = undefined;
|
||||
@State mCircleBorderPixelMap?: PixelMap = undefined;
|
||||
@State mRotatePixelMap?: PixelMap = undefined;
|
||||
@State mSquarePixelMap?: PixelMap = undefined;
|
||||
@State mClipTopPixelMap?: PixelMap = undefined;
|
||||
@State mClipCenterPixelMap?: PixelMap = undefined;
|
||||
@State mClipBottomPixelMap?: PixelMap = undefined;
|
||||
@State mGrayscalePixelMap?: PixelMap = undefined;
|
||||
@State mBrightnessPixelMap?: PixelMap = undefined;
|
||||
@State mContrastPixelMap?: PixelMap = undefined;
|
||||
@State mInvertPixelMap?: PixelMap = undefined;
|
||||
@State mSepiaPixelMap?: PixelMap = undefined;
|
||||
@State mSketchPixelMap?: PixelMap = undefined;
|
||||
@State mBlurPixelMap?: PixelMap = undefined;
|
||||
@State mPixelPixelMap?: PixelMap = undefined;
|
||||
@State mSwirlPixelMap?: PixelMap = undefined;
|
||||
@State mMaskPixelMap?: PixelMap = undefined;
|
||||
@State mKuwaharaPixelMap?: PixelMap = undefined;
|
||||
@State mToonPixelMap?: PixelMap = undefined;
|
||||
@State mVignettePixelMap?: PixelMap = undefined;
|
||||
|
||||
build() {
|
||||
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
|
||||
|
@ -545,67 +545,49 @@ struct TransformPixelMapPage {
|
|||
* centerCrop
|
||||
*/
|
||||
centerCrop() {
|
||||
var imageKnifeOption = new RequestOption();
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load($r('app.media.jpgSample'))
|
||||
// imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
this.mCropPixelMap = result;
|
||||
setTimeout(() => {
|
||||
let result2 = undefined;
|
||||
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mCropPixelMap = result2;
|
||||
}, 100)
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(100), height: vp2px(100) })
|
||||
.skipMemoryCache(true)
|
||||
.centerCrop();
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
* centerInside
|
||||
*/
|
||||
centerInside() {
|
||||
var imageKnifeOption = new RequestOption();
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load($r('app.media.Back'))
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
this.mCropPixelMap = result;
|
||||
setTimeout(() => {
|
||||
let result2 = undefined;
|
||||
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mCropPixelMap = result2;
|
||||
}, 100)
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(100), height: vp2px(100) })
|
||||
.skipMemoryCache(true)
|
||||
.centerInside();
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
* centerInside
|
||||
*/
|
||||
fitCenter() {
|
||||
var imageKnifeOption = new RequestOption()
|
||||
let imageKnifeOption = new RequestOption()
|
||||
imageKnifeOption.load($r('app.media.Back'))
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
this.mCropPixelMap = result;
|
||||
setTimeout(() => {
|
||||
let result2 = undefined;
|
||||
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mCropPixelMap = result2;
|
||||
}, 100)
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
this.mCropPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(100), height: vp2px(100) })
|
||||
.skipMemoryCache(true)
|
||||
.fitCenter();
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
/**
|
||||
* 圆角设置
|
||||
|
@ -613,18 +595,12 @@ struct TransformPixelMapPage {
|
|||
roundedCornersTransformation(top_left: number,
|
||||
bottom_left: number, top_right: number, bottom_right: number) {
|
||||
|
||||
var imageKnifeOption = new RequestOption();
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
this.mRoundPixelMap = result;
|
||||
setTimeout(() => {
|
||||
let result2 = undefined;
|
||||
result2 = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mRoundPixelMap = result2;
|
||||
}, 100)
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
this.mRoundPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(100), height: vp2px(100) })
|
||||
.skipMemoryCache(true)
|
||||
.roundedCorners({
|
||||
|
@ -633,7 +609,7 @@ struct TransformPixelMapPage {
|
|||
bottom_left: bottom_left,
|
||||
bottom_right: bottom_right
|
||||
})
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -642,16 +618,16 @@ struct TransformPixelMapPage {
|
|||
circleTransformation() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mCirclePixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mCirclePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.cropCircle()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -659,20 +635,20 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
circleBorderTransformation(border: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var circleTransformation = new CropCircleWithBorderTransformation(border,
|
||||
let circleTransformation = new CropCircleWithBorderTransformation(border,
|
||||
{ r_color: 255, g_color: 204, b_color: 204 });
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mCircleBorderPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mCircleBorderPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.cropCircleWithBorder(border,
|
||||
{ r_color: 255, g_color: 204, b_color: 204 })
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -680,18 +656,18 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
transformRotate(angled: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new RotateImageTransformation(angled);
|
||||
let transformation = new RotateImageTransformation(angled);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mRotatePixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mRotatePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.rotateImage(angled)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -699,18 +675,18 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
transformSquare() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new CropSquareTransformation();
|
||||
let transformation = new CropSquareTransformation();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mSquarePixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mSquarePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.cropSquare()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -718,26 +694,26 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
clipPixelMap(width: number, height: number, cropType: CropType) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new CropTransformation(width, height, cropType);
|
||||
let transformation = new CropTransformation(width, height, cropType);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
let result:PixelMap|undefined = undefined;
|
||||
if (cropType == CropType.TOP) {
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
result = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
this.mClipTopPixelMap = result;
|
||||
} else if (cropType == CropType.CENTER) {
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
result = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
this.mClipCenterPixelMap = result;
|
||||
} else if (cropType == CropType.BOTTOM) {
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
result = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
this.mClipBottomPixelMap = result;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: width, height: height })
|
||||
.skipMemoryCache(true)
|
||||
.crop(width, height, cropType)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -746,19 +722,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
grayscalePixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new GrayscaleTransformation();
|
||||
let transformation = new GrayscaleTransformation();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mGrayscalePixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mGrayscalePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.grayscale()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -767,19 +743,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
brightnessPixelMap(brightness: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new BrightnessFilterTransformation(brightness);
|
||||
let transformation = new BrightnessFilterTransformation(brightness);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mBrightnessPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mBrightnessPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.brightnessFilter(brightness)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -788,19 +764,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
contrastPixelMap(contrast: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new ContrastFilterTransformation(contrast);
|
||||
let transformation = new ContrastFilterTransformation(contrast);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mContrastPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mContrastPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.contrastFilter(contrast)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -809,19 +785,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
invertPixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new InvertFilterTransformation();
|
||||
let transformation = new InvertFilterTransformation();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mInvertPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mInvertPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.invertFilter()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -830,19 +806,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
sepiaPixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new SepiaFilterTransformation();
|
||||
let transformation = new SepiaFilterTransformation();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mSepiaPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mSepiaPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.sepiaFilter()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -851,19 +827,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
sketchPixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new SketchFilterTransformation();
|
||||
let transformation = new SketchFilterTransformation();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mSketchPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mSketchPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.sketchFilter()
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -872,19 +848,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
blurHandlePixelMap(radius: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new BlurTransformation(radius);
|
||||
let transformation = new BlurTransformation(radius);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mBlurPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mBlurPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.blur(radius)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
/**
|
||||
|
@ -892,19 +868,19 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
pixelHandlePixelMap(pixel: number) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new PixelationFilterTransformation(pixel);
|
||||
let transformation = new PixelationFilterTransformation(pixel);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mPixelPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mPixelPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.pixelationFilter(pixel)
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -913,20 +889,20 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
swirlHandlePixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new SwirlFilterTransformation(80);
|
||||
let transformation = new SwirlFilterTransformation(80);
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mSwirlPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mSwirlPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.swirlFilter(80)
|
||||
// .diskCacheStrategy(new NONE())
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
/**
|
||||
|
@ -934,20 +910,20 @@ struct TransformPixelMapPage {
|
|||
*/
|
||||
maskHandlePixelMap(maskResource: Resource) {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
var transformation = new MaskTransformation(maskResource);
|
||||
let transformation = new MaskTransformation(maskResource);
|
||||
// imageKnifeOption.load($r('app.media.photo6'))
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mMaskPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mMaskPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.mask(maskResource)
|
||||
// .diskCacheStrategy(new NONE())
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -957,18 +933,18 @@ struct TransformPixelMapPage {
|
|||
kuwaharaHandlePixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mKuwaharaPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mKuwaharaPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.kuwaharaFilter(20.0)
|
||||
// .diskCacheStrategy(new NONE())
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -978,18 +954,18 @@ struct TransformPixelMapPage {
|
|||
toonHandlePixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mToonPixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mToonPixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.toonFilter(0.2, 50.0);
|
||||
// .diskCacheStrategy(new NONE())
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
|
||||
|
@ -999,20 +975,20 @@ struct TransformPixelMapPage {
|
|||
vignetteHandlePixelMap() {
|
||||
let imageKnifeOption = new RequestOption();
|
||||
imageKnifeOption.load(mUrl)
|
||||
.addListener((err, data) => {
|
||||
let result = undefined;
|
||||
result = data.drawPixelMap.imagePixelMap as PixelMap;
|
||||
this.mVignettePixelMap = result;
|
||||
.addListener({callback:(err:BusinessError|string, data:ImageKnifeData) => {
|
||||
|
||||
this.mVignettePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
|
||||
|
||||
return false;
|
||||
})
|
||||
}})
|
||||
.setImageViewSize({ width: vp2px(200), height: vp2px(200) })
|
||||
.skipMemoryCache(true)
|
||||
.enableGPU()
|
||||
.vignetteFilter([0.5, 0.5], [0.0, 0.0, 0.0], [0.3, 0.5])
|
||||
// .diskCacheStrategy(new NONE())
|
||||
ImageKnife.call(imageKnifeOption);
|
||||
ImageKnife?.call(imageKnifeOption);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
var ImageKnife = globalThis.ImageKnife
|
||||
let ImageKnife = ImageKnifeGlobal.getInstance().getImageKnife();
|
|
@ -19,25 +19,25 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
|
|||
export default function abilityTest() {
|
||||
describe('ActsAbilityTest', 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach( ()=> {
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll( ()=> {
|
||||
// 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.
|
||||
})
|
||||
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.
|
||||
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
|
||||
let a = 'abc'
|
||||
|
|
|
@ -14,41 +14,41 @@
|
|||
*/
|
||||
import hilog from '@ohos.hilog';
|
||||
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() {
|
||||
describe('ImageKnifeTest', 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach( ()=> {
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll( ()=> {
|
||||
// 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.
|
||||
})
|
||||
|
||||
|
||||
it('TestGlobalImageKnife',0, function () {
|
||||
globalThis.ImageKnife = ImageKnife.with(globalThis.TestAbilityContext)
|
||||
expect(globalThis.ImageKnife).not().assertUndefined()
|
||||
it('TestGlobalImageKnife',0, ()=> {
|
||||
let global:ImageKnifeGlobal = ImageKnife.with(ImageKnifeGlobal.getInstance().getHapContext())
|
||||
expect(global.getImageKnife()).not().assertUndefined()
|
||||
})
|
||||
|
||||
|
||||
it('TestGlobalDefaultLifeCycle',1, function () {
|
||||
globalThis.ImageKnife = ImageKnife.with(globalThis.TestAbilityContext)
|
||||
globalThis.ImageKnife.setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
|
||||
let globalLifeCycle = globalThis.ImageKnife.getDefaultLifeCycle();
|
||||
it('TestGlobalDefaultLifeCycle',1, ()=> {
|
||||
ImageKnife.with(ImageKnifeGlobal.getInstance().getHapContext())
|
||||
(ImageKnifeGlobal.getInstance().getImageKnife()).setDefaultLifeCycle(ImageKnifeDrawFactory.createProgressLifeCycle("#10a5ff", 0.5))
|
||||
let globalLifeCycle = (ImageKnifeGlobal.getInstance().getImageKnife()).getDefaultLifeCycle();
|
||||
expect(globalLifeCycle).not().assertUndefined()
|
||||
})
|
||||
|
||||
|
|
|
@ -17,27 +17,27 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
|
|||
import {LogUtil} from '@ohos/imageknife'
|
||||
|
||||
export default function LogUtilTest() {
|
||||
describe('LogUtilTest', function () {
|
||||
describe('LogUtilTest', ()=> {
|
||||
// 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach( ()=> {
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll( ()=> {
|
||||
// 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.
|
||||
})
|
||||
it('TestLogUtilLevel',0, function () {
|
||||
it('TestLogUtilLevel',0, ()=> {
|
||||
|
||||
console.log("tag:LogUtil LogUtil.mLogLevel="+LogUtil.mLogLevel);
|
||||
LogUtil.mLogLevel = LogUtil.OFF;
|
||||
|
|
|
@ -17,35 +17,35 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
|
|||
import {LruCache} from '@ohos/imageknife' // DiskLruCache用例由DiskLruCache三方库提供
|
||||
|
||||
export default function lruCacheTest() {
|
||||
describe('lruCacheTest', function () {
|
||||
describe('lruCacheTest', ()=> {
|
||||
// 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach( ()=> {
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll( ()=> {
|
||||
// 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.
|
||||
})
|
||||
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.
|
||||
let memoryCache = new LruCache<string, any>(100);
|
||||
let memoryCache = new LruCache<string, string>(100);
|
||||
expect(memoryCache.size).assertEqual(0);
|
||||
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.
|
||||
let memoryCache = new LruCache<string, any>(5);
|
||||
let memoryCache = new LruCache<string, string>(5);
|
||||
memoryCache.put("1","1");
|
||||
memoryCache.put("2","2");
|
||||
memoryCache.put("3","3");
|
||||
|
@ -57,9 +57,9 @@ export default function lruCacheTest() {
|
|||
let result = memoryCache.get("1")
|
||||
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.
|
||||
let memoryCache = new LruCache<string, any>(5);
|
||||
let memoryCache = new LruCache<string, string>(5);
|
||||
memoryCache.put("1","1");
|
||||
memoryCache.put("2","2");
|
||||
memoryCache.put("3","3");
|
||||
|
@ -71,9 +71,9 @@ export default function lruCacheTest() {
|
|||
let result = memoryCache.get("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.
|
||||
let memoryCache = new LruCache<string, any>(5);
|
||||
let memoryCache = new LruCache<string, string>(5);
|
||||
memoryCache.put("1","1");
|
||||
memoryCache.put("2","2");
|
||||
memoryCache.put("3","3");
|
||||
|
@ -82,17 +82,24 @@ export default function lruCacheTest() {
|
|||
|
||||
memoryCache.get("1");
|
||||
memoryCache.get("2");
|
||||
|
||||
memoryCache.foreachLruCache(function (value, key, index) {
|
||||
if(index == 0){
|
||||
expect(key).assertEqual("2")
|
||||
expect(value).assertEqual("2")
|
||||
let count:number = 1
|
||||
let callback =(key:string,value:string)=>{
|
||||
if(count == 5){
|
||||
expect(key).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, function () {
|
||||
it('testLruCacheRemove',4, ()=> {
|
||||
// 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("2","2");
|
||||
memoryCache.put("3","3");
|
||||
|
@ -104,16 +111,23 @@ export default function lruCacheTest() {
|
|||
|
||||
memoryCache.remove("2");
|
||||
|
||||
memoryCache.foreachLruCache(function (value, key, index) {
|
||||
if(index == 0){
|
||||
expect(key).assertEqual("1")
|
||||
expect(value).assertEqual("1")
|
||||
let count:number = 1
|
||||
let callback =(key:string,value:string)=>{
|
||||
if(count == 4){
|
||||
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, function () {
|
||||
it('testLruCacheResize',5, ()=> {
|
||||
// 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("2","2");
|
||||
memoryCache.put("3","3");
|
||||
|
|
|
@ -18,43 +18,43 @@ import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from
|
|||
import {RequestOption} from '@ohos/imageknife'
|
||||
|
||||
export default function RequestOptionTest() {
|
||||
describe('RequestOptionTest', function () {
|
||||
describe('RequestOptionTest', ()=> {
|
||||
// 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach( ()=> {
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll( ()=> {
|
||||
// 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.
|
||||
})
|
||||
it('TestRequestOption',0, function () {
|
||||
it('TestRequestOption',0, ()=> {
|
||||
let option = new RequestOption();
|
||||
expect(option.requestListeners.length == 0).assertTrue()
|
||||
})
|
||||
it('TestConfigLoadSrc',1, function () {
|
||||
it('TestConfigLoadSrc',1, ()=> {
|
||||
let option = new RequestOption();
|
||||
expect(option.loadSrc).assertEqual(undefined)
|
||||
expect(option.loadSrc).assertEqual('')
|
||||
option.loadSrc = $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();
|
||||
option.loadSrc = $r('app.media.icon')
|
||||
option.setImageViewSize({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();
|
||||
expect(option.strategy.getName()).assertEqual('AUTOMATIC')
|
||||
|
||||
|
|
|
@ -39,46 +39,46 @@ import {
|
|||
} from '@ohos/imageknife'
|
||||
|
||||
export default function Transform() {
|
||||
describe('Transform', function () {
|
||||
describe('Transform', ()=>{
|
||||
// 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.
|
||||
// This API supports only one parameter: preset action function.
|
||||
})
|
||||
beforeEach(function () {
|
||||
beforeEach(()=>{
|
||||
// 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**.
|
||||
// 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.
|
||||
// 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.
|
||||
})
|
||||
afterAll(function () {
|
||||
afterAll(()=>{
|
||||
// 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.
|
||||
})
|
||||
it('TestBlurTransformation', 0, function () {
|
||||
it('TestBlurTransformation', 0, ()=>{
|
||||
let blur = new BlurTransformation(15);
|
||||
expect(blur.getName()).assertEqual('BlurTransformation _mRadius:15')
|
||||
})
|
||||
it('TestBrightnessFilterTransformation', 1, function () {
|
||||
it('TestBrightnessFilterTransformation', 1, ()=>{
|
||||
let bright = new BrightnessFilterTransformation(20);
|
||||
expect(bright.getName()).assertEqual("BrightnessFilterTransformation:20")
|
||||
})
|
||||
it('TestContrastFilterTransformation', 2, function () {
|
||||
it('TestContrastFilterTransformation', 2, ()=>{
|
||||
let constrast = new ContrastFilterTransformation(30);
|
||||
expect(constrast.getName()).assertEqual("ContrastFilterTransformation:30")
|
||||
})
|
||||
it('TestCropCircleTransformation', 3, function () {
|
||||
it('TestCropCircleTransformation', 3, ()=>{
|
||||
let cropCircle = new CropCircleTransformation();
|
||||
expect(cropCircle.getName()).assertContain("CropCircleTransformation")
|
||||
expect(cropCircle.getName()).assertContain(";mCenterX:")
|
||||
expect(cropCircle.getName()).assertContain(";mCenterY:")
|
||||
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 });
|
||||
expect(CropCircleWithBorder.getName()).assertContain("CropCircleTransformation")
|
||||
expect(CropCircleWithBorder.getName()).assertContain(";mCenterX:")
|
||||
|
@ -89,63 +89,63 @@ export default function Transform() {
|
|||
expect(CropCircleWithBorder.getName()).assertContain(";mGColor:")
|
||||
expect(CropCircleWithBorder.getName()).assertContain(";mBColor:")
|
||||
})
|
||||
it('TestCropSquareTransformation', 5, function () {
|
||||
it('TestCropSquareTransformation', 5, ()=>{
|
||||
let CropSquare = new CropSquareTransformation();
|
||||
expect(CropSquare.getName()).assertContain("CropSquareTransformation")
|
||||
})
|
||||
it('TestCropTransformation', 6, function () {
|
||||
it('TestCropTransformation', 6, ()=>{
|
||||
let crop = new CropTransformation(10,10,CropType.CENTER);
|
||||
expect(crop.getName()).assertContain("CropCircleTransformation"+ ";mWidth:10" + ";mHeight:10" + ";mCropType:1" )
|
||||
})
|
||||
it('TestGrayscaleTransformation', 7, function () {
|
||||
it('TestGrayscaleTransformation', 7, ()=>{
|
||||
let grayscale = new GrayscaleTransformation();
|
||||
expect(grayscale.getName()).assertContain("GrayscaleTransformation" )
|
||||
})
|
||||
it('TestInvertFilterTransformation', 8, function () {
|
||||
it('TestInvertFilterTransformation', 8, ()=>{
|
||||
let invert = new InvertFilterTransformation();
|
||||
expect(invert.getName()).assertContain("InvertFilterTransformation" )
|
||||
})
|
||||
it('TestPixelationFilterTransformation', 9, function () {
|
||||
it('TestPixelationFilterTransformation', 9, ()=>{
|
||||
let pixelation = new PixelationFilterTransformation();
|
||||
expect(pixelation.getName()).assertContain("PixelationFilterTransformation" )
|
||||
})
|
||||
it('TestRotateImageTransformation', 10, function () {
|
||||
it('TestRotateImageTransformation', 10, ()=>{
|
||||
let rotateImage = new RotateImageTransformation(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});
|
||||
expect(roundConer.getName()).assertContain("RoundedCornersTransformation" + ";mTop_left:" + 5
|
||||
+ ";mTop_right:" + 5
|
||||
+ ";mBottom_left:" + 5
|
||||
+ ";mBottom_right:" + 5)
|
||||
})
|
||||
it('TestSepiaFilterTransformation', 12, function () {
|
||||
it('TestSepiaFilterTransformation', 12, ()=>{
|
||||
let speia = new SepiaFilterTransformation();
|
||||
expect(speia.getName()).assertContain("SepiaFilterTransformation")
|
||||
})
|
||||
it('TestSketchFilterTransformation', 13, function () {
|
||||
it('TestSketchFilterTransformation', 13, ()=>{
|
||||
let Sketch = new SketchFilterTransformation();
|
||||
expect(Sketch.getName()).assertContain("SketchFilterTransformation")
|
||||
})
|
||||
it('TestMaskTransformation', 14, function () {
|
||||
it('TestMaskTransformation', 14, ()=>{
|
||||
let mask = new MaskTransformation($r('app.media.icon'));
|
||||
expect(mask.getName()).assertContain("MaskTransformation")
|
||||
})
|
||||
it('TestSwirlFilterTransformation', 15, function () {
|
||||
it('TestSwirlFilterTransformation', 15, ()=>{
|
||||
let swirl = new SwirlFilterTransformation(10,180,[10,10]);
|
||||
expect(swirl.getName()).assertContain("SwirlFilterTransformation")
|
||||
})
|
||||
it('TestKuwaharaFilterTransform', 16, function () {
|
||||
it('TestKuwaharaFilterTransform', 16, ()=>{
|
||||
let kuwahara = new KuwaharaFilterTransform(10);
|
||||
expect(kuwahara.getName()).assertContain("KuwaharaFilterTransform _mRadius:10")
|
||||
})
|
||||
it('TestToonFilterTransform', 17, function () {
|
||||
it('TestToonFilterTransform', 17, ()=>{
|
||||
let toon = new ToonFilterTransform(10);
|
||||
expect(toon.getName()).assertContain("ToonFilterTransform threshold:")
|
||||
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]);
|
||||
expect(vignette.getName()).assertContain("VignetteFilterTransform centerPoint:")
|
||||
expect(vignette.getName()).assertContain(";vignetteColor:")
|
||||
|
|
|
@ -18,7 +18,7 @@ import hilog from '@ohos.hilog';
|
|||
import { Hypium } from '@ohos/hypium';
|
||||
import testsuite from '../test/List.test';
|
||||
import window from '@ohos.window';
|
||||
|
||||
import {ImageKnife,ImageKnifeDrawFactory,ImageKnifeGlobal} from '@ohos/imageknife'
|
||||
export default class TestAbility extends UIAbility {
|
||||
onCreate(want, launchParam) {
|
||||
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
|
||||
|
@ -30,7 +30,8 @@ export default class TestAbility extends UIAbility {
|
|||
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
|
||||
hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!');
|
||||
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
|
||||
globalThis.TestAbilityContext = this.context.createModuleContext("entry_test")
|
||||
// 初始化xts的ImageKnife
|
||||
ImageKnife.with(this.context.createModuleContext("entry_test"));
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
|
|
|
@ -18,110 +18,111 @@
|
|||
* cache
|
||||
*/
|
||||
|
||||
export * from './src/main/ets/components/cache/FileUtils'
|
||||
export * from './src/main/ets/components/cache/Base64'
|
||||
export * from './src/main/ets/components/cache/LruCache'
|
||||
export * from './src/main/ets/components/cache/diskstrategy/enum/ALL'
|
||||
export * from './src/main/ets/components/cache/diskstrategy/enum/AUTOMATIC'
|
||||
export * from './src/main/ets/components/cache/diskstrategy/enum/DATA'
|
||||
export * from './src/main/ets/components/cache/diskstrategy/enum/NONE'
|
||||
export * from './src/main/ets/components/cache/diskstrategy/enum/RESOURCE'
|
||||
export type {EngineKeyInterface} from './src/main/ets/components/cache/key/EngineKeyInterface'
|
||||
export * from './src/main/ets/components/cache/key/EngineKeyFactories'
|
||||
export { FileUtils } from './src/main/ets/components/cache/FileUtils'
|
||||
export { Base64 } from './src/main/ets/components/cache/Base64'
|
||||
export { LruCache } from './src/main/ets/components/cache/LruCache'
|
||||
export { DiskStrategy } from './src/main/ets/components/cache/diskstrategy/DiskStrategy'
|
||||
export { ALL } from './src/main/ets/components/cache/diskstrategy/enum/ALL'
|
||||
export { AUTOMATIC } from './src/main/ets/components/cache/diskstrategy/enum/AUTOMATIC'
|
||||
export { DATA } from './src/main/ets/components/cache/diskstrategy/enum/DATA'
|
||||
export { NONE } from './src/main/ets/components/cache/diskstrategy/enum/NONE'
|
||||
export { RESOURCE } from './src/main/ets/components/cache/diskstrategy/enum/RESOURCE'
|
||||
export { EngineKeyInterface } from './src/main/ets/components/cache/key/EngineKeyInterface'
|
||||
export { EngineKeyFactories } from './src/main/ets/components/cache/key/EngineKeyFactories'
|
||||
|
||||
/**
|
||||
* compress
|
||||
*/
|
||||
export * from './src/main/ets/components/imageknife/compress/CompressBuilder'
|
||||
export type {OnCompressListener} from './src/main/ets/components/imageknife/compress/listener/OnCompressListener'
|
||||
export type {OnRenameListener} from './src/main/ets/components/imageknife/compress/listener/OnRenameListener'
|
||||
export type {CompressDataListener} from './src/main/ets/components/imageknife/compress/listener/CompressDataListener'
|
||||
export * from './src/main/ets/components/imageknife/compress/listener/CompressionPredicate'
|
||||
export * from './src/main/ets/components/imageknife/compress/provider/CompressAdapter'
|
||||
export * from './src/main/ets/components/imageknife/compress/provider/CompressProvider'
|
||||
export * from './src/main/ets/components/imageknife/compress/provider/DataStringPathProvider'
|
||||
export * from './src/main/ets/components/imageknife/compress/provider/RecourseProvider'
|
||||
export { CompressBuilder } from './src/main/ets/components/imageknife/compress/CompressBuilder'
|
||||
export { OnCompressListener } from './src/main/ets/components/imageknife/compress/listener/OnCompressListener'
|
||||
export { OnRenameListener } from './src/main/ets/components/imageknife/compress/listener/OnRenameListener'
|
||||
export { CompressDataListener } from './src/main/ets/components/imageknife/compress/listener/CompressDataListener'
|
||||
export { CompressionPredicate } from './src/main/ets/components/imageknife/compress/listener/CompressionPredicate'
|
||||
export { CompressAdapter } from './src/main/ets/components/imageknife/compress/provider/CompressAdapter'
|
||||
export { CompressProvider } from './src/main/ets/components/imageknife/compress/provider/CompressProvider'
|
||||
export { DataStringPathProvider } from './src/main/ets/components/imageknife/compress/provider/DataStringPathProvider'
|
||||
export { RecourseProvider } from './src/main/ets/components/imageknife/compress/provider/RecourseProvider'
|
||||
|
||||
/**
|
||||
* crop
|
||||
*/
|
||||
export * from './src/main/ets/components/imageknife/crop/Crop'
|
||||
export * from './src/main/ets/components/imageknife/crop/CropImage'
|
||||
export * from './src/main/ets/components/imageknife/crop/CropOptions'
|
||||
export {default as PixelMapCrop} from './src/main/ets/components/imageknife/crop/PixelMapCrop'
|
||||
export * from './src/main/ets/components/imageknife/crop/CropCallback'
|
||||
|
||||
export { CropImage } from './src/main/ets/components/imageknife/crop/CropImage'
|
||||
export { CropOptions } from './src/main/ets/components/imageknife/crop/CropOptions'
|
||||
export { PixelMapCrop,Options } from './src/main/ets/components/imageknife/crop/PixelMapCrop'
|
||||
export { CropCallback } from './src/main/ets/components/imageknife/crop/CropCallback'
|
||||
|
||||
/**
|
||||
* transform
|
||||
*/
|
||||
export type {BaseTransform} from './src/main/ets/components/imageknife/transform/BaseTransform'
|
||||
export * from './src/main/ets/components/imageknife/transform/BlurTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/BrightnessFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/ContrastFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/CropCircleTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/CropSquareTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/CropTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/GrayscaleTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/InvertFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/PixelationFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/RotateImageTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/RoundedCornersTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/SepiaFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/SketchFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/MaskTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/SwirlFilterTransformation'
|
||||
export * from './src/main/ets/components/imageknife/transform/KuwaharaFilterTransform'
|
||||
export * from './src/main/ets/components/imageknife/transform/ToonFilterTransform'
|
||||
export * from './src/main/ets/components/imageknife/transform/VignetteFilterTransform'
|
||||
export * from './src/main/ets/components/imageknife/transform/TransformUtils'
|
||||
export * from './src/main/ets/components/imageknife/transform/TransformType'
|
||||
export * from './src/main/ets/components/imageknife/transform/pixelmap/CenterCrop'
|
||||
export * from './src/main/ets/components/imageknife/transform/pixelmap/CenterInside'
|
||||
export * from './src/main/ets/components/imageknife/transform/pixelmap/FitCenter'
|
||||
export { BaseTransform } from './src/main/ets/components/imageknife/transform/BaseTransform'
|
||||
export { BlurTransformation } from './src/main/ets/components/imageknife/transform/BlurTransformation'
|
||||
export { BrightnessFilterTransformation } from './src/main/ets/components/imageknife/transform/BrightnessFilterTransformation'
|
||||
export { ContrastFilterTransformation } from './src/main/ets/components/imageknife/transform/ContrastFilterTransformation'
|
||||
export { CropCircleTransformation } from './src/main/ets/components/imageknife/transform/CropCircleTransformation'
|
||||
export { CropCircleWithBorderTransformation,rgbColor } from './src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation'
|
||||
export { CropSquareTransformation } from './src/main/ets/components/imageknife/transform/CropSquareTransformation'
|
||||
export { CropTransformation,CropType } from './src/main/ets/components/imageknife/transform/CropTransformation'
|
||||
export { GrayscaleTransformation } from './src/main/ets/components/imageknife/transform/GrayscaleTransformation'
|
||||
export { InvertFilterTransformation } from './src/main/ets/components/imageknife/transform/InvertFilterTransformation'
|
||||
export { PixelationFilterTransformation } from './src/main/ets/components/imageknife/transform/PixelationFilterTransformation'
|
||||
export { RotateImageTransformation } from './src/main/ets/components/imageknife/transform/RotateImageTransformation'
|
||||
export { RoundedCornersTransformation,RoundCorner } from './src/main/ets/components/imageknife/transform/RoundedCornersTransformation'
|
||||
export { SepiaFilterTransformation } from './src/main/ets/components/imageknife/transform/SepiaFilterTransformation'
|
||||
export { SketchFilterTransformation } from './src/main/ets/components/imageknife/transform/SketchFilterTransformation'
|
||||
export { MaskTransformation } from './src/main/ets/components/imageknife/transform/MaskTransformation'
|
||||
export { SwirlFilterTransformation } from './src/main/ets/components/imageknife/transform/SwirlFilterTransformation'
|
||||
export { KuwaharaFilterTransform } from './src/main/ets/components/imageknife/transform/KuwaharaFilterTransform'
|
||||
export { ToonFilterTransform } from './src/main/ets/components/imageknife/transform/ToonFilterTransform'
|
||||
export { VignetteFilterTransform } from './src/main/ets/components/imageknife/transform/VignetteFilterTransform'
|
||||
export { TransformUtils } from './src/main/ets/components/imageknife/transform/TransformUtils'
|
||||
export { TransformType } from './src/main/ets/components/imageknife/transform/TransformType'
|
||||
export { CenterCrop } from './src/main/ets/components/imageknife/transform/pixelmap/CenterCrop'
|
||||
export { CenterInside } from './src/main/ets/components/imageknife/transform/pixelmap/CenterInside'
|
||||
export { FitCenter } from './src/main/ets/components/imageknife/transform/pixelmap/FitCenter'
|
||||
|
||||
/**
|
||||
* 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 * from './src/main/ets/components/3rd_party/upng/UPNG'
|
||||
export { UPNG } from './src/main/ets/components/3rd_party/upng/UPNG'
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* ImageKnife
|
||||
*/
|
||||
export * from './src/main/ets/components/imageknife/ImageKnife'
|
||||
export * from './src/main/ets/components/imageknife/RequestOption'
|
||||
export * from './src/main/ets/components/imageknife/ImageKnifeComponent'
|
||||
export * from './src/main/ets/components/imageknife/ImageKnifeDrawFactory'
|
||||
export * from './src/main/ets/components/imageknife/ImageKnifeOption'
|
||||
export * from './src/main/ets/components/imageknife/ImageKnifeData'
|
||||
export type {IAllCacheInfoCallback} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback'
|
||||
export type {AllCacheInfo} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback'
|
||||
export type {IParseImage} from './src/main/ets/components/imageknife/interface/IParseImage'
|
||||
export type {IDataFetch} from './src/main/ets/components/imageknife/networkmanage/IDataFetch'
|
||||
export type {ICache} from './src/main/ets/components/imageknife/requestmanage/ICache'
|
||||
export * from './src/main/ets/components/imageknife/utils/FileTypeUtil'
|
||||
export * from './src/main/ets/components/imageknife/utils/ParseImageUtil'
|
||||
export { ImageKnife } from './src/main/ets/components/imageknife/ImageKnife'
|
||||
export { ImageKnifeGlobal } from './src/main/ets/components/imageknife/ImageKnifeGlobal'
|
||||
export {RequestOption,Size} from './src/main/ets/components/imageknife/RequestOption'
|
||||
export { ImageKnifeComponent, ScaleType, ScaleTypeHelper } from './src/main/ets/components/imageknife/ImageKnifeComponent'
|
||||
export { ImageKnifeDrawFactory } from './src/main/ets/components/imageknife/ImageKnifeDrawFactory'
|
||||
export {ImageKnifeOption,CropCircleWithBorder,Crop,GifOptions,TransformOptions} from './src/main/ets/components/imageknife/ImageKnifeOption'
|
||||
export { ImageKnifeData } from './src/main/ets/components/imageknife/ImageKnifeData'
|
||||
export {IAllCacheInfoCallback,AllCacheInfo,ResourceCacheInfo,MemoryCacheInfo,DataCacheInfo} from './src/main/ets/components/imageknife/interface/IAllCacheInfoCallback'
|
||||
export {IParseImage} from './src/main/ets/components/imageknife/interface/IParseImage'
|
||||
export {IDataFetch} from './src/main/ets/components/imageknife/networkmanage/IDataFetch'
|
||||
export {ICache} from './src/main/ets/components/imageknife/requestmanage/ICache'
|
||||
export { FileTypeUtil } from './src/main/ets/components/imageknife/utils/FileTypeUtil'
|
||||
export { ParseImageUtil } from './src/main/ets/components/imageknife/utils/ParseImageUtil'
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
export * from './src/main/ets/components/imageknife/utils/gif/GIFParseImpl'
|
||||
export * from './src/main/ets/components/imageknife/utils/gif/GIFFrame'
|
||||
export { GIFParseImpl } from './src/main/ets/components/imageknife/utils/gif/GIFParseImpl'
|
||||
export { GIFFrame } from './src/main/ets/components/imageknife/utils/gif/GIFFrame'
|
||||
// 能力增强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'
|
|
@ -14,7 +14,7 @@
|
|||
"main": "index.ets",
|
||||
"repository": "https://gitee.com/openharmony-tpc/ImageKnife",
|
||||
"type": "module",
|
||||
"version": "2.0.5-rc.0",
|
||||
"version": "2.1.0",
|
||||
"dependencies": {
|
||||
"@ohos/disklrucache": "^2.0.0",
|
||||
"@ohos/svg": "^2.0.0",
|
||||
|
|
|
@ -18,24 +18,24 @@ export class Base64 {
|
|||
private static sInstance: Base64;
|
||||
|
||||
public static getInstance(): Base64{
|
||||
if (!this.sInstance) {
|
||||
this.sInstance = new Base64();
|
||||
if (!Base64.sInstance) {
|
||||
Base64.sInstance = new Base64();
|
||||
}
|
||||
return this.sInstance;
|
||||
return Base64.sInstance;
|
||||
}
|
||||
|
||||
private constructor() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
encode(arraybuffer: ArrayBuffer): string {
|
||||
let bytes = new Uint8Array(arraybuffer),
|
||||
i,
|
||||
len = bytes.length,
|
||||
base64 = '';
|
||||
let i:number = 0
|
||||
for (i = 0; i < len; i += 3) {
|
||||
base64 += this.chars[bytes[i] >> 2];
|
||||
base64 += this.chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
|
||||
|
@ -53,12 +53,12 @@ export class Base64 {
|
|||
decode(base64: string): ArrayBuffer{
|
||||
let bufferLength = base64.length * 0.75,
|
||||
len = base64.length,
|
||||
i,
|
||||
p = 0,
|
||||
encoded1,
|
||||
encoded2,
|
||||
encoded3,
|
||||
encoded4;
|
||||
p = 0;
|
||||
let i:number = 0;
|
||||
let encoded1:number = 0;
|
||||
let encoded2:number = 0;
|
||||
let encoded3:number = 0;
|
||||
let encoded4:number = 0;
|
||||
|
||||
if (base64[base64.length - 1] === '=') {
|
||||
bufferLength--;
|
||||
|
|
|
@ -38,7 +38,7 @@ export class CustomMap <K, V> {
|
|||
if (key == null || value == null) {
|
||||
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)) {
|
||||
this.map.delete(key)
|
||||
}
|
||||
|
@ -70,7 +70,7 @@ export class CustomMap <K, V> {
|
|||
return this.map.size;
|
||||
}
|
||||
// 遍历Map,执行处理函数. 回调函数 function(key,value,index){..}
|
||||
each(fn) {
|
||||
each(fn: (value: V, key: K, map: Map<K, V>) => void) {
|
||||
this.map.forEach(fn)
|
||||
}
|
||||
// 清除键值对
|
||||
|
|
|
@ -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()
|
||||
}
|
||||
}
|
|
@ -14,20 +14,20 @@
|
|||
*/
|
||||
|
||||
import fs from '@ohos.file.fs';
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export class FileUtils {
|
||||
base64Str: string = ''
|
||||
private static sInstance: FileUtils;
|
||||
|
||||
public static getInstance(): FileUtils {
|
||||
if (!this.sInstance) {
|
||||
this.sInstance = new FileUtils();
|
||||
if (!FileUtils.sInstance) {
|
||||
FileUtils.sInstance = new FileUtils();
|
||||
}
|
||||
return this.sInstance;
|
||||
return FileUtils.sInstance;
|
||||
}
|
||||
|
||||
private constructor() {
|
||||
console.error("FileUtils - FileUtils constructor")
|
||||
console.log("FileUtils - FileUtils constructor")
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -50,7 +50,7 @@ export class FileUtils {
|
|||
fs.unlinkSync(path);
|
||||
}
|
||||
} 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) {
|
||||
fs.unlink(path).then(()=>{
|
||||
resolve();
|
||||
}).catch(err=>{
|
||||
}).catch( (err:BusinessError)=>{
|
||||
reject(err)
|
||||
})
|
||||
}
|
||||
}).catch(err=>{
|
||||
}).catch((err:BusinessError)=>{
|
||||
reject(err);
|
||||
})
|
||||
})
|
||||
|
@ -89,7 +89,7 @@ export class FileUtils {
|
|||
* 异步删除文件目录 必须保证文件夹里面没有文件
|
||||
* @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)) {
|
||||
fs.rmdir(path)
|
||||
.then(deleteComplete).catch(deleteError);
|
||||
|
@ -209,10 +209,10 @@ export class FileUtils {
|
|||
// 关闭文件
|
||||
fs.closeSync(file);
|
||||
resolve(buf);
|
||||
}).catch(err=>{
|
||||
}).catch((err:BusinessError)=>{
|
||||
reject(err);
|
||||
})
|
||||
}).catch(err=>{
|
||||
}).catch((err:BusinessError)=>{
|
||||
reject(err);
|
||||
})
|
||||
|
||||
|
@ -235,7 +235,9 @@ export class FileUtils {
|
|||
let ss = fs.createStreamSync(path, "r+");
|
||||
ss.readSync(buf)
|
||||
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) {
|
||||
console.log("FileUtils - readFilePic " + e)
|
||||
return ""
|
||||
|
@ -307,33 +309,18 @@ export class FileUtils {
|
|||
* string 转 Uint8Array
|
||||
* @param str 输入String
|
||||
*/
|
||||
stringToUint8Array(str): Uint8Array {
|
||||
var arr = [];
|
||||
for (var i = 0, j = str.length; i < j; ++i) {
|
||||
stringToUint8Array(str:string): Uint8Array {
|
||||
let arr:Array<number> = new Array<number>();
|
||||
for (let i = 0, j = str.length; i < j; ++i) {
|
||||
arr.push(str.charCodeAt(i));
|
||||
}
|
||||
var tmpUint8Array = new Uint8Array(arr);
|
||||
let tmpUint8Array = new Uint8Array(arr);
|
||||
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 {
|
||||
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
|
||||
}
|
||||
}
|
||||
|
||||
export interface AsyncCallback<T> {
|
||||
(err: string, data: T): void;
|
||||
}
|
|
@ -30,7 +30,7 @@ export class LruCache <K, V> {
|
|||
if (key == null || value == null) {
|
||||
throw new Error('key or value is invalid ');
|
||||
}
|
||||
var pre = this.map.get(key)
|
||||
let pre = this.map.get(key)
|
||||
if (pre == null) {
|
||||
this.size++
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ export class LruCache <K, V> {
|
|||
if (key == null) {
|
||||
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)) {
|
||||
this.size--
|
||||
}
|
||||
|
@ -51,11 +51,11 @@ export class LruCache <K, V> {
|
|||
}
|
||||
|
||||
// 获取键为key的value
|
||||
get(key: K): V {
|
||||
get(key: K): V|undefined {
|
||||
if (key == null) {
|
||||
throw new Error('key is null,checking the parameter');
|
||||
}
|
||||
var preValue = this.map.get(key)
|
||||
let preValue = this.map.get(key)
|
||||
if (preValue != null) {
|
||||
this.entryRemoved(key, preValue, preValue)
|
||||
}
|
||||
|
@ -69,7 +69,7 @@ export class LruCache <K, V> {
|
|||
* preValue 对应key键的旧value值
|
||||
* value 对应key键的新value值
|
||||
*/
|
||||
entryRemoved(key: K, preValue: V, value: V) {
|
||||
entryRemoved(key: K, preValue: V | undefined, value: V | undefined) {
|
||||
if (preValue != null) {
|
||||
this.map.remove(key)
|
||||
}
|
||||
|
@ -89,7 +89,7 @@ export class LruCache <K, V> {
|
|||
if (this.size <= tempsize || this.map.isEmpty()) {
|
||||
break
|
||||
}
|
||||
var delkey = this.map.getFirstKey()
|
||||
let delkey = this.map.getFirstKey()
|
||||
this.map.remove(delkey)
|
||||
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;
|
||||
})
|
||||
return printResult;
|
||||
}
|
||||
|
||||
foreachLruCache(fn){
|
||||
foreachLruCache(fn:(value: V, key: K, map: Map<K, V>) => void){
|
||||
this.map.each(fn);
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -26,24 +26,25 @@ import {RequestManager} from "../imageknife/requestmanage/RequestManager"
|
|||
import {NONE} from "../cache/diskstrategy/enum/NONE"
|
||||
import {FileTypeUtil} from '../imageknife/utils/FileTypeUtil'
|
||||
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 type {IResourceFetch} from '../imageknife/resourcemanage/IResourceFetch'
|
||||
import {IResourceFetch} from '../imageknife/resourcemanage/IResourceFetch'
|
||||
import {ImageKnifeData,ImageKnifeType} from '../imageknife/ImageKnifeData'
|
||||
import {FileUtils} from '../cache/FileUtils'
|
||||
import {FileReader} from '../cache/FileReader'
|
||||
import {ImageKnifeGlobal} from '../imageknife/ImageKnifeGlobal'
|
||||
import image from "@ohos.multimedia.image"
|
||||
import {CompressBuilder} from "../imageknife/compress/CompressBuilder"
|
||||
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
|
||||
import {LogUtil} from '../imageknife/utils/LogUtil'
|
||||
import worker from '@ohos.worker'
|
||||
import common from '@ohos.app.ability.common'
|
||||
|
||||
export class ImageKnife {
|
||||
static readonly SEPARATOR: string = '/'
|
||||
private imageKnifeContext;
|
||||
private memoryCache: LruCache<string, any>;
|
||||
|
||||
private memoryCache: LruCache<string, ImageKnifeData>;
|
||||
private diskMemoryCache: DiskLruCache;
|
||||
private dataFetch: IDataFetch;
|
||||
private resourceFetch: IResourceFetch;
|
||||
private resourceFetch: IResourceFetch<ArrayBuffer>;
|
||||
private filesPath: string = ""; // data/data/包名/files目录
|
||||
|
||||
|
||||
|
@ -54,24 +55,25 @@ export class ImageKnife {
|
|||
private diskCacheFolder: string = "ImageKnifeDiskCache"
|
||||
|
||||
|
||||
private defaultListener: AsyncCallback<ImageKnifeData>; // 全局监听器
|
||||
private defaultListener: AsyncCallback<ImageKnifeData> = {
|
||||
callback:(err: string, data: ImageKnifeData)=>{return false}
|
||||
}; // 全局监听器
|
||||
|
||||
// gifWorker
|
||||
private gifWorker;
|
||||
private gifWorker: worker.ThreadWorker|undefined = undefined;
|
||||
|
||||
private defaultLifeCycle: IDrawLifeCycle;
|
||||
private defaultLifeCycle: IDrawLifeCycle|undefined = undefined;
|
||||
|
||||
// 开发者可配置全局缓存
|
||||
private engineKeyImpl: EngineKeyInterface;
|
||||
|
||||
private constructor(imgCtx) {
|
||||
this.imageKnifeContext = imgCtx;
|
||||
private constructor() {
|
||||
|
||||
// 构造方法传入size 为保存文件个数
|
||||
this.memoryCache = new LruCache<string, any>(100);
|
||||
this.memoryCache = new LruCache<string, ImageKnifeData>(100);
|
||||
|
||||
// 创建disk缓存 传入的size 为多少比特 比如20KB 传入20*1024
|
||||
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext);
|
||||
this.diskMemoryCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext());
|
||||
|
||||
// 创建网络下载能力
|
||||
this.dataFetch = new DownloadClient();
|
||||
|
@ -80,7 +82,7 @@ export class ImageKnife {
|
|||
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.pendingRequest = new Array();
|
||||
|
@ -91,15 +93,24 @@ export class ImageKnife {
|
|||
this.engineKeyImpl = new EngineKeyFactories();
|
||||
}
|
||||
|
||||
getMemoryCache(): LruCache<string, any>{
|
||||
getMemoryCache(): LruCache<string, ImageKnifeData>{
|
||||
return this.memoryCache;
|
||||
}
|
||||
|
||||
public static with(context): ImageKnife{
|
||||
if (!this.sInstance) {
|
||||
this.sInstance = new ImageKnife(context);
|
||||
public static with(context:Object): ImageKnifeGlobal{
|
||||
// 存入hapContext;
|
||||
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{
|
||||
|
@ -115,10 +126,10 @@ export class ImageKnife {
|
|||
}
|
||||
|
||||
getImageKnifeContext() {
|
||||
return this.imageKnifeContext;
|
||||
return ImageKnifeGlobal.getInstance().getHapContext();
|
||||
}
|
||||
|
||||
setMemoryCache(lrucache: LruCache<string, any>) {
|
||||
setMemoryCache(lrucache: LruCache<string, ImageKnifeData>) {
|
||||
this.memoryCache = lrucache;
|
||||
}
|
||||
|
||||
|
@ -126,7 +137,7 @@ export class ImageKnife {
|
|||
return this.defaultListener;
|
||||
}
|
||||
|
||||
setGifWorker(worker){
|
||||
setGifWorker(worker:worker.ThreadWorker){
|
||||
this.gifWorker = worker
|
||||
}
|
||||
getGifWorker(){
|
||||
|
@ -158,10 +169,10 @@ export class ImageKnife {
|
|||
// 替代原来的LruCache
|
||||
public replaceLruCache(size:number){
|
||||
if(this.memoryCache.map.size() <= 0) {
|
||||
this.memoryCache = new LruCache<string, any>(size);
|
||||
this.memoryCache = new LruCache<string, ImageKnifeData>(size);
|
||||
}else{
|
||||
let newLruCache = new LruCache<string, any>(size);
|
||||
this.memoryCache.foreachLruCache(function (value, key, map) {
|
||||
let newLruCache = new LruCache<string, ImageKnifeData>(size);
|
||||
this.memoryCache.foreachLruCache( (value:ImageKnifeData, key:string, map:Object)=> {
|
||||
newLruCache.put(key, value);
|
||||
})
|
||||
this.memoryCache = newLruCache;
|
||||
|
@ -175,10 +186,10 @@ export class ImageKnife {
|
|||
// 替代原来的DiskLruCache
|
||||
public replaceDiskLruCache(size:number) {
|
||||
if (this.diskMemoryCache.getCacheMap().size() <= 0) {
|
||||
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext, size);
|
||||
this.diskMemoryCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext(), size);
|
||||
} else {
|
||||
let newDiskLruCache = DiskLruCache.create(this.imageKnifeContext, size);
|
||||
this.diskMemoryCache.foreachDiskLruCache(function (value, key, map) {
|
||||
let newDiskLruCache = DiskLruCache.create(ImageKnifeGlobal.getInstance().getHapContext(), size);
|
||||
this.diskMemoryCache.foreachDiskLruCache( (value:string|ArrayBuffer, key:string, map:Object)=> {
|
||||
newDiskLruCache.set(key, value);
|
||||
})
|
||||
this.diskMemoryCache = newDiskLruCache;
|
||||
|
@ -186,7 +197,7 @@ export class ImageKnife {
|
|||
}
|
||||
|
||||
// 预加载 resource资源一级缓存,string资源实现二级缓存
|
||||
preload(request: RequestOption) {
|
||||
preload(request: RequestOption):void {
|
||||
// 每个request 公共信息补充
|
||||
request.setFilesPath(this.filesPath);
|
||||
|
||||
|
@ -194,7 +205,7 @@ export class ImageKnife {
|
|||
}
|
||||
|
||||
// 正常加载
|
||||
call(request: RequestOption) {
|
||||
call(request: RequestOption):void {
|
||||
// 添加全局监听
|
||||
if(this.defaultListener) {
|
||||
request.addListener(this.defaultListener)
|
||||
|
@ -220,10 +231,10 @@ export class ImageKnife {
|
|||
}
|
||||
|
||||
loadResources(request: RequestOption) {
|
||||
let factories;
|
||||
let cacheKey;
|
||||
let transferKey;
|
||||
let dataKey;
|
||||
let factories:EngineKeyInterface;
|
||||
let cacheKey:string;
|
||||
let transferKey:string;
|
||||
let dataKey:string;
|
||||
if(this.engineKeyImpl){
|
||||
factories = this.engineKeyImpl;
|
||||
}else {
|
||||
|
@ -324,7 +335,7 @@ export class ImageKnife {
|
|||
|
||||
|
||||
// 加载下一个key的请求
|
||||
loadNextPending(request) {
|
||||
loadNextPending(request:RequestOption) {
|
||||
// 首先寻找被移除key相同的request
|
||||
let index = -1;
|
||||
for (let i = 0; i < this.pendingRequest.length; i++) {
|
||||
|
@ -415,7 +426,7 @@ export class ImageKnife {
|
|||
return false;
|
||||
}
|
||||
|
||||
parseSource(request: RequestOption) {
|
||||
parseSource(request: RequestOption):void {
|
||||
if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, request.loadSrc as PixelMap)
|
||||
request.loadComplete(imageKnifeData);
|
||||
|
|
|
@ -14,13 +14,14 @@
|
|||
*/
|
||||
|
||||
import { ImageKnifeOption } from '../imageknife/ImageKnifeOption'
|
||||
import { ImageKnifeGlobal } from '../imageknife/ImageKnifeGlobal'
|
||||
import { TransformType } from '../imageknife/transform/TransformType'
|
||||
import { RequestOption } from '../imageknife/RequestOption'
|
||||
import { RequestOption, Size } from '../imageknife/RequestOption'
|
||||
import { ImageKnifeData } from '../imageknife/ImageKnifeData'
|
||||
import { GIFFrame } from '../imageknife/utils/gif/GIFFrame'
|
||||
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
|
||||
import { LogUtil } from '../imageknife/utils/LogUtil'
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
|
||||
@Component
|
||||
export struct ImageKnifeComponent {
|
||||
|
@ -78,7 +79,8 @@ export struct ImageKnifeComponent {
|
|||
}
|
||||
private canvasHasReady: 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() {
|
||||
Canvas(this.context)
|
||||
|
@ -104,11 +106,12 @@ export struct ImageKnifeComponent {
|
|||
this.canvasHasReady = true;
|
||||
if (this.onReadyNext) {
|
||||
LogUtil.log('ImageKnifeComponent onReadyNext is running!')
|
||||
this.onReadyNext()
|
||||
this.onReadyNext(this.onReadyNextData)
|
||||
this.onReadyNext = undefined;
|
||||
this.onReadyNextData = undefined
|
||||
}
|
||||
})
|
||||
.onClick((event: ClickEvent) => {
|
||||
.onClick((event?: ClickEvent) => {
|
||||
// 需要将点击事件回传
|
||||
if (this.imageKnifeOption.onClick) {
|
||||
this.imageKnifeOption.onClick(event)
|
||||
|
@ -152,24 +155,26 @@ export struct ImageKnifeComponent {
|
|||
* 待onReady执行的时候执行
|
||||
* @param nextFunction 下一个方法
|
||||
*/
|
||||
runNextFunction(nextFunction: () => void) {
|
||||
runNextFunction(nextFunction: (data:ImageKnifeData|number|undefined) => void,data:ImageKnifeData|number|undefined) {
|
||||
if (!this.canvasHasReady) {
|
||||
// canvas未初始化完成
|
||||
this.onReadyNext = nextFunction;
|
||||
this.onReadyNextData = data;
|
||||
} else {
|
||||
nextFunction();
|
||||
nextFunction(data);
|
||||
}
|
||||
}
|
||||
|
||||
configNecessary(request: RequestOption) {
|
||||
request.load(this.imageKnifeOption.loadSrc)
|
||||
.addListener((err, data) => {
|
||||
.addListener({ callback: (err:BusinessError|string, data:ImageKnifeData) => {
|
||||
LogUtil.log('ImageKnifeComponent request.load callback')
|
||||
this.runNextFunction(this.displayMainSource.bind(this, data));
|
||||
this.runNextFunction(this.displayMainSource,data);
|
||||
return false;
|
||||
}
|
||||
})
|
||||
|
||||
let realSize = {
|
||||
let realSize:Size = {
|
||||
width: this.currentWidth,
|
||||
height: this.currentHeight
|
||||
}
|
||||
|
@ -196,23 +201,23 @@ export struct ImageKnifeComponent {
|
|||
|
||||
configDisplay(request: RequestOption) {
|
||||
if (this.imageKnifeOption.placeholderSrc) {
|
||||
request.placeholder(this.imageKnifeOption.placeholderSrc, (data) => {
|
||||
request.placeholder(this.imageKnifeOption.placeholderSrc, {asyncSuccess:(data:ImageKnifeData) => {
|
||||
LogUtil.log('ImageKnifeComponent request.placeholder callback')
|
||||
this.runNextFunction(this.displayPlaceholder.bind(this, data))
|
||||
|
||||
this.runNextFunction(this.displayPlaceholder,data)
|
||||
}
|
||||
})
|
||||
}
|
||||
if (this.imageKnifeOption.thumbSizeMultiplier) {
|
||||
request.thumbnail(this.imageKnifeOption.thumbSizeMultiplier, (data) => {
|
||||
request.thumbnail(this.imageKnifeOption.thumbSizeMultiplier, {asyncSuccess:(data:ImageKnifeData) => {
|
||||
LogUtil.log('ImageKnifeComponent request.thumbnail callback')
|
||||
this.runNextFunction(this.displayThumbSizeMultiplier.bind(this, data))
|
||||
}, this.imageKnifeOption.thumbSizeDelay)
|
||||
this.runNextFunction(this.displayThumbSizeMultiplier,data)
|
||||
}}, this.imageKnifeOption.thumbSizeDelay)
|
||||
}
|
||||
if (this.imageKnifeOption.errorholderSrc) {
|
||||
request.errorholder(this.imageKnifeOption.errorholderSrc, (data) => {
|
||||
request.errorholder(this.imageKnifeOption.errorholderSrc, {asyncSuccess:(data:ImageKnifeData) => {
|
||||
LogUtil.log('ImageKnifeComponent request.errorholder callback')
|
||||
this.runNextFunction(this.displayErrorholder.bind(this, data))
|
||||
})
|
||||
this.runNextFunction(this.displayErrorholder,data)
|
||||
}})
|
||||
}
|
||||
|
||||
if (this.imageKnifeOption.transform) {
|
||||
|
@ -230,19 +235,19 @@ export struct ImageKnifeComponent {
|
|||
|
||||
|
||||
if (this.imageKnifeOption.displayProgress) {
|
||||
request.addProgressListener((percentValue: number) => {
|
||||
request.addProgressListener({asyncSuccess:(percentValue: number) => {
|
||||
// 如果进度条百分比 未展示大小,展示其动画
|
||||
LogUtil.log('ImageKnifeComponent request.addProgressListener callback')
|
||||
this.runNextFunction(this.displayProgress.bind(this, percentValue))
|
||||
})
|
||||
this.runNextFunction(this.displayProgress,percentValue)
|
||||
}})
|
||||
}
|
||||
|
||||
if (this.imageKnifeOption.retryholderSrc) {
|
||||
request.retryholder(this.imageKnifeOption.retryholderSrc, (data) => {
|
||||
request.retryholder(this.imageKnifeOption.retryholderSrc,{asyncSuccess: (data:ImageKnifeData) => {
|
||||
LogUtil.log('ImageKnifeComponent request.retryholder callback')
|
||||
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.configDisplay(request);
|
||||
this.configRenderGpu(request);
|
||||
globalThis.ImageKnife.call(request);
|
||||
if(ImageKnifeGlobal.getInstance().getImageKnife()!=undefined) {
|
||||
ImageKnifeGlobal.getInstance().getImageKnife()?.call(request);
|
||||
}
|
||||
}
|
||||
|
||||
displayPlaceholder(data: ImageKnifeData) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayPlaceholder', this.context, data, this.imageKnifeOption,
|
||||
displayPlaceholder = (data: ImageKnifeData|number|undefined)=> {
|
||||
if(data == undefined || typeof data == 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayPlaceholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayPlaceholder', this.context, data, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayPlaceholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayPlaceholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if(this.defaultLifeCycle.displayPlaceholder != undefined) {
|
||||
this.defaultLifeCycle.displayPlaceholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
displayProgress(percent: number) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayProgress', this.context, percent, this.imageKnifeOption,
|
||||
displayProgress = (percent: ImageKnifeData|number|undefined)=> {
|
||||
if(typeof percent != 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayProgress', this.context, percent, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayProgress', this.context, percent, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayProgress', this.context, percent, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayProgress(this.context, percent, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if(this.defaultLifeCycle.displayProgress != undefined) {
|
||||
this.defaultLifeCycle.displayProgress(this.context, percent, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
displayThumbSizeMultiplier(data: ImageKnifeData) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
|
||||
displayThumbSizeMultiplier = (data: ImageKnifeData|number|undefined)=> {
|
||||
if(data == undefined || typeof data == 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayThumbSizeMultiplier', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayThumbSizeMultiplier(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if(this.defaultLifeCycle.displayThumbSizeMultiplier != undefined) {
|
||||
this.defaultLifeCycle.displayThumbSizeMultiplier(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
displayMainSource(data: ImageKnifeData) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayMainSource', this.context, data, this.imageKnifeOption,
|
||||
displayMainSource = (data: ImageKnifeData|number|undefined)=> {
|
||||
if(data == undefined || typeof data == 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayMainSource', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayMainSource', this.context, data, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayMainSource', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayMainSource(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if(this.defaultLifeCycle.displayMainSource != undefined) {
|
||||
this.defaultLifeCycle.displayMainSource(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
displayRetryholder(data: ImageKnifeData) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayRetryholder', this.context, data, this.imageKnifeOption,
|
||||
displayRetryholder = (data: ImageKnifeData|number|undefined)=> {
|
||||
if(data == undefined || typeof data == 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayRetryholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayRetryholder', this.context, data, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayRetryholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayRetryholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if( this.defaultLifeCycle.displayRetryholder != undefined) {
|
||||
this.defaultLifeCycle.displayRetryholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
displayErrorholder(data: ImageKnifeData) {
|
||||
if (!this.drawLifeCycleHasConsumed(this.imageKnifeOption.drawLifeCycle, 'displayErrorholder', this.context, data, this.imageKnifeOption,
|
||||
displayErrorholder = (data: ImageKnifeData|number|undefined)=> {
|
||||
if(data == undefined || typeof data == 'number'){
|
||||
return
|
||||
}
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayErrorholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
if (!this.drawLifeCycleHasConsumed(globalThis.ImageKnife.getDefaultLifeCycle(), 'displayErrorholder', this.context, data, this.imageKnifeOption,
|
||||
},this.imageKnifeOption.drawLifeCycle)) {
|
||||
if (!this.drawLifeCycleHasConsumed( 'displayErrorholder', this.context, data, this.imageKnifeOption,
|
||||
this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})) {
|
||||
this.defaultLifeCycle.displayErrorholder(this.context, data, this.imageKnifeOption, this.currentWidth, this.currentHeight, (gifTimeId) => {
|
||||
this.setGifTimeId(gifTimeId)
|
||||
})
|
||||
},(ImageKnifeGlobal.getInstance().getImageKnife())?.getDefaultLifeCycle())) {
|
||||
if(this.defaultLifeCycle.displayErrorholder != undefined) {
|
||||
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) {
|
||||
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)
|
||||
let scaleType = (typeof imageKnifeOption.placeholderScaleType == 'number') ? imageKnifeOption.placeholderScaleType : ScaleType.FIT_CENTER
|
||||
context.save();
|
||||
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();
|
||||
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) {
|
||||
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)
|
||||
let scaleType = (typeof imageKnifeOption.thumbSizeMultiplierScaleType == 'number') ? imageKnifeOption.thumbSizeMultiplierScaleType : ScaleType.FIT_CENTER
|
||||
context.save();
|
||||
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();
|
||||
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) {
|
||||
LogUtil.log('ImageKnifeComponent default drawMainSource start!')
|
||||
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
|
||||
LogUtil.log('ImageKnifeComponent imageinfo width =' + imageInfo.size.width + ' height=' + imageInfo.size.height + 'scaleType=' + scaleType)
|
||||
context.save();
|
||||
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();
|
||||
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) {
|
||||
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)
|
||||
let scaleType = (typeof imageKnifeOption.retryholderScaleType == 'number') ? imageKnifeOption.retryholderScaleType : ScaleType.FIT_CENTER
|
||||
context.save();
|
||||
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();
|
||||
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) {
|
||||
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)
|
||||
let scaleType = (typeof imageKnifeOption.errorholderSrcScaleType == 'number') ? imageKnifeOption.errorholderSrcScaleType : ScaleType.FIT_CENTER
|
||||
context.save();
|
||||
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();
|
||||
LogUtil.log('ImageKnifeComponent default drawErrorholder end!')
|
||||
})
|
||||
}
|
||||
|
||||
requestAddTransform(request: RequestOption) {
|
||||
if (TransformType.BlurTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.blur(this.imageKnifeOption.transform.blur)
|
||||
} else if (TransformType.BrightnessFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.brightnessFilter(this.imageKnifeOption.transform.brightnessFilter)
|
||||
} else if (TransformType.ContrastFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.contrastFilter(this.imageKnifeOption.transform.contrastFilter)
|
||||
} else if (TransformType.CropCircleTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
if (TransformType.BlurTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.blur(this.imageKnifeOption.transform?.blur)
|
||||
} else if (TransformType.BrightnessFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.brightnessFilter(this.imageKnifeOption.transform?.brightnessFilter)
|
||||
} else if (TransformType.ContrastFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.contrastFilter(this.imageKnifeOption.transform?.contrastFilter)
|
||||
} else if (TransformType.CropCircleTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.cropCircle()
|
||||
} else if (TransformType.CropCircleWithBorderTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.cropCircleWithBorder(this.imageKnifeOption.transform.cropCircleWithBorder.border, this.imageKnifeOption.transform.cropCircleWithBorder.obj)
|
||||
} else if (TransformType.CropSquareTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.CropCircleWithBorderTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.cropCircleWithBorder(this.imageKnifeOption.transform?.cropCircleWithBorder?.border, this.imageKnifeOption.transform?.cropCircleWithBorder?.obj)
|
||||
} else if (TransformType.CropSquareTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.cropSquare()
|
||||
} 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)
|
||||
} else if (TransformType.GrayscaleTransformation == 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)
|
||||
} else if (TransformType.GrayscaleTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.grayscale()
|
||||
} else if (TransformType.InvertFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.InvertFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.invertFilter()
|
||||
} else if (TransformType.MaskTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.mask(this.imageKnifeOption.transform.mask)
|
||||
} else if (TransformType.PixelationFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.pixelationFilter(this.imageKnifeOption.transform.pixelationFilter)
|
||||
} else if (TransformType.RotateImageTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.rotateImage(this.imageKnifeOption.transform.rotateImage)
|
||||
} else if (TransformType.RoundedCornersTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.roundedCorners(this.imageKnifeOption.transform.roundedCorners)
|
||||
} else if (TransformType.SepiaFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.MaskTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.mask(this.imageKnifeOption.transform?.mask)
|
||||
} else if (TransformType.PixelationFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.pixelationFilter(this.imageKnifeOption.transform?.pixelationFilter)
|
||||
} else if (TransformType.RotateImageTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.rotateImage(this.imageKnifeOption.transform?.rotateImage)
|
||||
} else if (TransformType.RoundedCornersTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.roundedCorners(this.imageKnifeOption.transform?.roundedCorners)
|
||||
} else if (TransformType.SepiaFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.sepiaFilter()
|
||||
} else if (TransformType.SketchFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.SketchFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.sketchFilter()
|
||||
} else if (TransformType.SwirlFilterTransformation == this.imageKnifeOption.transform.transformType) {
|
||||
request.swirlFilter(this.imageKnifeOption.transform.swirlFilter)
|
||||
} else if (TransformType.CenterCrop == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.SwirlFilterTransformation == this.imageKnifeOption.transform?.transformType) {
|
||||
request.swirlFilter(this.imageKnifeOption.transform?.swirlFilter)
|
||||
} else if (TransformType.CenterCrop == this.imageKnifeOption.transform?.transformType) {
|
||||
request.centerCrop()
|
||||
} else if (TransformType.CenterInside == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.CenterInside == this.imageKnifeOption.transform?.transformType) {
|
||||
request.centerInside()
|
||||
} else if (TransformType.FitCenter == this.imageKnifeOption.transform.transformType) {
|
||||
} else if (TransformType.FitCenter == this.imageKnifeOption.transform?.transformType) {
|
||||
request.fitCenter()
|
||||
}
|
||||
}
|
||||
|
@ -560,17 +597,17 @@ export struct ImageKnifeComponent {
|
|||
this.gifTimerId = timeId;
|
||||
}
|
||||
|
||||
private drawLifeCycleHasConsumed<K, T>(drawLifeCycle: IDrawLifeCycle, methodName: string,
|
||||
context: CanvasRenderingContext2D, data: K, imageKnifeOption: T, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void
|
||||
) {
|
||||
if (drawLifeCycle && drawLifeCycle[methodName]) {
|
||||
return drawLifeCycle[methodName](context, data, imageKnifeOption, compWidth, compHeight, setGifTimeId)
|
||||
private drawLifeCycleHasConsumed<K, T>( methodName: string,
|
||||
context: CanvasRenderingContext2D, data: K, imageKnifeOption: T, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void,drawLifeCycle?: IDrawLifeCycle
|
||||
):boolean {
|
||||
if (drawLifeCycle && (drawLifeCycle as Record<string,Function>)[methodName]) {
|
||||
return (drawLifeCycle as Record<string,Function>)[methodName](context, data, imageKnifeOption, compWidth, compHeight, setGifTimeId)
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
if (imageKnifeOption.gif && (typeof (imageKnifeOption.gif.seekTo) == 'number') && imageKnifeOption.gif.seekTo >= 0) {
|
||||
this.autoPlay = false;
|
||||
|
@ -579,7 +616,14 @@ export struct ImageKnifeComponent {
|
|||
} else {
|
||||
this.autoPlay = true
|
||||
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非第一帧数据可能是不全的,这里采用逐帧渲染的方式来绘制保证图像的完整性
|
||||
*/
|
||||
private drawSeekToFrame(frames: GIFFrame[], context: CanvasRenderingContext2D, compWidth: number, compHeight: number) {
|
||||
for (let i = 0; i < this.imageKnifeOption.gif.seekTo; i++) {
|
||||
this.drawFrame(frames, i, context, compWidth, compHeight);
|
||||
if(this.imageKnifeOption.gif != undefined && this.imageKnifeOption.gif.seekTo != undefined) {
|
||||
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) {
|
||||
LogUtil.log('ImageKnifeComponent renderFrames frames length =' + frames.length)
|
||||
renderFrames_frames: GIFFrame[] | undefined = undefined
|
||||
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();
|
||||
if (index === 0) {
|
||||
if (this.renderFrames_index === 0) {
|
||||
// 如果是第一帧,我们只从开始渲染前记录时间
|
||||
this.startGifLoopTime = start;
|
||||
}
|
||||
// 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动图只有一帧的情况下,不进行后面代码的逐帧绘制循环
|
||||
if (frames.length <= 1) {
|
||||
if (this.renderFrames_frames != undefined && this.renderFrames_frames.length <= 1) {
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -620,9 +672,12 @@ export struct ImageKnifeComponent {
|
|||
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) {
|
||||
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));
|
||||
|
@ -634,21 +689,23 @@ export struct ImageKnifeComponent {
|
|||
// 整个gif累计的时长;
|
||||
this.gifLoopDuration += loopStayTime;
|
||||
// 返回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.gifLoopDuration = 0;
|
||||
}
|
||||
// update the frame index
|
||||
index++
|
||||
if (index >= frames.length) {
|
||||
index = 0;
|
||||
this.renderFrames_index++
|
||||
if (this.renderFrames_frames != undefined && this.renderFrames_index >= this.renderFrames_frames.length) {
|
||||
this.renderFrames_index = 0;
|
||||
}
|
||||
// @ts-ignore
|
||||
this.gifTimerId = setTimeout(this.renderFrames.bind(this, frames, index, context, compWidth, compHeight), delayTime)
|
||||
this.gifTimerId = setTimeout(this.renderFrames, 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
|
||||
let frame = frames[index];
|
||||
if (!frame || !context) {
|
||||
|
@ -676,7 +733,8 @@ export struct ImageKnifeComponent {
|
|||
disposal = preFrame.disposalType
|
||||
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
|
@ -731,7 +789,7 @@ export enum ScaleType {
|
|||
|
||||
|
||||
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 scaleH = compHeight / imageHeight
|
||||
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)
|
||||
let dx = 0
|
||||
let dy = 0
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
let dx:number = 0
|
||||
let dy:number = 0
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
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)
|
||||
|
||||
let dx = (compWidth - imageWidth * minScale) / (minScale * 1.0);
|
||||
let dy = (compHeight - imageHeight * minScale) / (minScale * 1.0);
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
let dx:number = (compWidth - imageWidth * minScale) / (minScale * 1.0);
|
||||
let dy:number = (compHeight - imageHeight * minScale) / (minScale * 1.0);
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
if(source!= undefined) {
|
||||
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)
|
||||
let dx = (compWidth - imageWidth * minScale) / (minScale * 2.0);
|
||||
let dy = (compHeight - imageHeight * minScale) / (minScale * 2.0);
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
let dx:number = (compWidth - imageWidth * minScale) / (minScale * 2.0);
|
||||
let dy:number = (compHeight - imageHeight * minScale) / (minScale * 2.0);
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
if(source!= undefined) {
|
||||
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) {
|
||||
let dx = (compWidth - imageWidth) / 2.0;
|
||||
let dy = (compHeight - imageHeight) / 2.0;
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
static drawCenter(context: CanvasRenderingContext2D, source: PixelMap | undefined, imageWidth: number, imageHeight: number, compWidth: number, compHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
|
||||
let dx:number = (compWidth - imageWidth) / 2.0;
|
||||
let dy:number = (compHeight - imageHeight) / 2.0;
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
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)
|
||||
let dx = (compWidth - imageWidth * maxScale) / (maxScale * 2.0);
|
||||
let dy = (compHeight - imageHeight * maxScale) / (maxScale * 2.0);
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
let dx:number = (compWidth - imageWidth * maxScale) / (maxScale * 2.0);
|
||||
let dy:number = (compHeight - imageHeight * maxScale) / (maxScale * 2.0);
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
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)
|
||||
let dx = 0;
|
||||
let dy = 0;
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
let dx:number = 0;
|
||||
let dy:number = 0;
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
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) {
|
||||
ScaleTypeHelper.drawFitCenter(context, source, minScale, imageWidth, imageHeight, compWidth, compHeight, imageOffsetX, imageOffsetY)
|
||||
} else {
|
||||
|
@ -833,13 +901,15 @@ export class ScaleTypeHelper {
|
|||
}
|
||||
}
|
||||
|
||||
static drawNone(context: CanvasRenderingContext2D, source: PixelMap | ImageBitmap, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
|
||||
let dx = 0;
|
||||
let dy = 0;
|
||||
let dw = imageWidth;
|
||||
let dh = imageHeight;
|
||||
context.drawImage(source, dx + imageOffsetX, dy + imageOffsetY)
|
||||
}
|
||||
static drawNone(context: CanvasRenderingContext2D, source: PixelMap | undefined, imageWidth: number, imageHeight: number, imageOffsetX?: number, imageOffsetY?: number) {
|
||||
let dx:number = 0;
|
||||
let dy:number = 0;
|
||||
let dw:number = imageWidth;
|
||||
let dh:number = imageHeight;
|
||||
if(source!= undefined) {
|
||||
context.drawImage(source, dx + (imageOffsetX != undefined ? imageOffsetX : 0), dy + (imageOffsetY != undefined ? imageOffsetY : 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -22,19 +22,19 @@ export enum ImageKnifeType {
|
|||
}
|
||||
|
||||
export class DrawPixelMap {
|
||||
imagePixelMap: PixelMap
|
||||
imagePixelMap: PixelMap | undefined = undefined
|
||||
}
|
||||
|
||||
export class DrawString {
|
||||
imageString: string
|
||||
imageString: string | undefined = undefined
|
||||
}
|
||||
|
||||
export class DrawResource {
|
||||
imageResource: Resource
|
||||
imageResource: Resource | undefined = undefined
|
||||
}
|
||||
|
||||
export class DrawGIFFrame {
|
||||
imageGIFFrames: GIFFrame[]
|
||||
imageGIFFrames: GIFFrame[] | undefined = undefined
|
||||
}
|
||||
|
||||
export class ImageKnifeData {
|
||||
|
@ -47,11 +47,11 @@ export class ImageKnifeData {
|
|||
|
||||
waitSaveDisk = false;
|
||||
|
||||
imageKnifeType: ImageKnifeType;
|
||||
drawPixelMap: DrawPixelMap;
|
||||
drawGIFFrame: DrawGIFFrame;
|
||||
drawResource: DrawResource;
|
||||
drawString: DrawString;
|
||||
imageKnifeType: ImageKnifeType | undefined = undefined;
|
||||
drawPixelMap: DrawPixelMap | undefined = undefined;
|
||||
drawGIFFrame: DrawGIFFrame | undefined = undefined;
|
||||
drawResource: DrawResource | undefined = undefined;
|
||||
drawString: DrawString | undefined = undefined;
|
||||
|
||||
static createImagePixelMap(type: ImageKnifeType, value: PixelMap) {
|
||||
let data = new ImageKnifeData();
|
||||
|
|
|
@ -26,10 +26,10 @@ export class ImageKnifeDrawFactory{
|
|||
* @param colorString 例如 "#FF00FF"
|
||||
*/
|
||||
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) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
// 展示加载进度
|
||||
|
@ -38,29 +38,29 @@ export class ImageKnifeDrawFactory{
|
|||
},
|
||||
// 展示缩略图
|
||||
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示主图
|
||||
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
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
|
||||
|
||||
context.clearRect(0,0,compWidth,compHeight)
|
||||
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();
|
||||
|
||||
// 使用 destination-in 裁剪出椭圆
|
||||
context.save();
|
||||
context.globalCompositeOperation = 'destination-in'
|
||||
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.fill()
|
||||
context.restore();
|
||||
|
@ -72,7 +72,7 @@ export class ImageKnifeDrawFactory{
|
|||
context.lineWidth = borderWidth;
|
||||
context.globalCompositeOperation = 'source-over'
|
||||
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.stroke()
|
||||
context.restore();
|
||||
|
@ -108,7 +108,7 @@ export class ImageKnifeDrawFactory{
|
|||
* @param imageOffsetY
|
||||
* @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) {
|
||||
let scaleW = compWidth / imageWidth
|
||||
let scaleH = compHeight / imageHeight
|
||||
|
@ -189,10 +189,10 @@ export class ImageKnifeDrawFactory{
|
|||
* @param connerRadius 圆角半径
|
||||
*/
|
||||
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) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
// 展示加载进度
|
||||
|
@ -201,15 +201,15 @@ export class ImageKnifeDrawFactory{
|
|||
},
|
||||
// 展示缩略图
|
||||
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示主图
|
||||
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
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
|
||||
|
||||
context.clearRect(0,0,compWidth,compHeight)
|
||||
|
@ -217,13 +217,13 @@ export class ImageKnifeDrawFactory{
|
|||
|
||||
// 绘制适配后的图像
|
||||
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();
|
||||
|
||||
// 通过 destination-in 裁剪出圆角
|
||||
context.save();
|
||||
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.restore();
|
||||
if(borderWidth > 0){
|
||||
|
@ -232,7 +232,7 @@ export class ImageKnifeDrawFactory{
|
|||
context.strokeStyle = colorString
|
||||
context.lineWidth = borderWidth
|
||||
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.restore();
|
||||
}
|
||||
|
@ -268,7 +268,7 @@ export class ImageKnifeDrawFactory{
|
|||
* @param borderWidth
|
||||
* @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) {
|
||||
let scaleW = compWidth / imageWidth
|
||||
let scaleH = compHeight / imageHeight
|
||||
|
@ -284,21 +284,21 @@ export class ImageKnifeDrawFactory{
|
|||
y1 = borderWidth/2
|
||||
w1 = imageWidth * minScale - borderWidth;
|
||||
h1 = imageHeight * minScale - borderWidth;
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.FIT_END:
|
||||
x1 = compWidth - imageWidth * minScale + borderWidth / 2
|
||||
y1 = compHeight - imageHeight * minScale + borderWidth / 2
|
||||
w1 = imageWidth * minScale - borderWidth;
|
||||
h1 = imageHeight * minScale - borderWidth;
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.FIT_CENTER:
|
||||
x1 = (compWidth - imageWidth * minScale) / 2 + borderWidth / 2
|
||||
y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2
|
||||
w1 = imageWidth * minScale - borderWidth
|
||||
h1 = imageHeight * minScale - borderWidth
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.CENTER:
|
||||
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;
|
||||
h1 = Math.min(compHeight, imageHeight) - borderWidth;
|
||||
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.CENTER_CROP:
|
||||
x1 = borderWidth/2
|
||||
|
@ -315,7 +315,7 @@ export class ImageKnifeDrawFactory{
|
|||
|
||||
w1 = compWidth - borderWidth;
|
||||
h1 = compHeight - borderWidth;
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.FIT_XY:
|
||||
x1 = borderWidth/2
|
||||
|
@ -323,7 +323,7 @@ export class ImageKnifeDrawFactory{
|
|||
|
||||
w1 = compWidth - borderWidth;
|
||||
h1 = compHeight - borderWidth;
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break
|
||||
case ScaleType.CENTER_INSIDE:
|
||||
if(minScale < 1){ // FIT_CENTER
|
||||
|
@ -331,7 +331,7 @@ export class ImageKnifeDrawFactory{
|
|||
y1 = (compHeight - imageHeight * minScale) / 2 + borderWidth / 2
|
||||
w1 = imageWidth * minScale - borderWidth
|
||||
h1 = imageHeight * minScale - borderWidth
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
}else{ // CENTER
|
||||
x1 = Math.max(0,(compWidth - Math.min(compWidth, imageWidth)))/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;
|
||||
h1 = Math.min(compHeight, imageHeight) - borderWidth;
|
||||
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
}
|
||||
|
||||
break;
|
||||
|
@ -351,7 +351,7 @@ export class ImageKnifeDrawFactory{
|
|||
w1 = Math.min(compWidth, imageWidth) - borderWidth;
|
||||
h1 = Math.min(compHeight, imageHeight) - borderWidth;
|
||||
|
||||
this.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
ImageKnifeDrawFactory.roundRect(context, x1, y1, w1, h1, cornerRadius)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -390,36 +390,36 @@ export class ImageKnifeDrawFactory{
|
|||
let viewLifeCycle: IDrawLifeCycle = {
|
||||
// 展示占位图
|
||||
displayPlaceholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
// 展示加载进度
|
||||
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;
|
||||
},
|
||||
// 展示缩略图
|
||||
displayThumbSizeMultiplier: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示主图
|
||||
displayMainSource: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示重试图层
|
||||
displayRetryholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
// 展示失败占位图
|
||||
displayErrorholder: (context: CanvasRenderingContext2D, data: ImageKnifeData, imageKnifeOption: ImageKnifeOption, compWidth: number, compHeight: number, setGifTimeId?: (timeId: number) => void) => {
|
||||
// @ts-ignore
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -22,12 +22,44 @@ import { CropType } from '../imageknife/transform/CropTransformation'
|
|||
import { AllCacheInfo, IAllCacheInfoCallback } from '../imageknife/interface/IAllCacheInfoCallback'
|
||||
import { IDrawLifeCycle } from '../imageknife/interface/IDrawLifeCycle'
|
||||
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
|
||||
export class ImageKnifeOption {
|
||||
|
||||
// 主图资源
|
||||
loadSrc: string | PixelMap | Resource;
|
||||
loadSrc: string | PixelMap | Resource = '';
|
||||
mainScaleType?: ScaleType = ScaleType.FIT_CENTER
|
||||
|
||||
enableGpu?:boolean = true;
|
||||
|
@ -77,43 +109,11 @@ export class ImageKnifeOption {
|
|||
// 设置点击事件回调
|
||||
onClick?:(event?: ClickEvent) => void
|
||||
|
||||
gif?: {
|
||||
loopFinish?: (loopTime?) => void
|
||||
speedFactory?: number
|
||||
seekTo?: number
|
||||
}
|
||||
gif?: GifOptions = undefined;
|
||||
|
||||
|
||||
// 变换相关 不推荐使用该接口 建议直接使用transformation transformations这2个接口实现
|
||||
transform?: {
|
||||
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
|
||||
}
|
||||
transform?:TransformOptions = undefined
|
||||
transformation?: BaseTransform<PixelMap>;
|
||||
transformations?: Array<BaseTransform<PixelMap>>;
|
||||
|
||||
|
|
|
@ -14,9 +14,9 @@
|
|||
*/
|
||||
|
||||
import { DiskStrategy } from "../cache/diskstrategy/DiskStrategy"
|
||||
import type { AsyncCallback } from "../imageknife/interface/AsyncCallback"
|
||||
import type { AsyncSuccess } from "../imageknife/interface/AsyncSuccess"
|
||||
import type { IAllCacheInfoCallback } from "../imageknife/interface/IAllCacheInfoCallback"
|
||||
import { AsyncCallback } from "../imageknife/interface/AsyncCallback"
|
||||
import { AsyncSuccess } from "../imageknife/interface/AsyncSuccess"
|
||||
import { IAllCacheInfoCallback } from "../imageknife/interface/IAllCacheInfoCallback"
|
||||
import { AUTOMATIC } from "../cache/diskstrategy/enum/AUTOMATIC"
|
||||
import { BaseTransform } from "../imageknife/transform/BaseTransform"
|
||||
import { RotateImageTransformation } from "../imageknife/transform/RotateImageTransformation"
|
||||
|
@ -24,11 +24,11 @@ import { ImageKnifeData } from "../imageknife/ImageKnifeData"
|
|||
import { CenterCrop } from '../imageknife/transform/pixelmap/CenterCrop'
|
||||
import { CenterInside } from '../imageknife/transform/pixelmap/CenterInside'
|
||||
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 { CropCircleWithBorderTransformation } from '../imageknife/transform/CropCircleWithBorderTransformation'
|
||||
import { CropCircleWithBorderTransformation, rgbColor } from '../imageknife/transform/CropCircleWithBorderTransformation'
|
||||
import { CropSquareTransformation } from '../imageknife/transform/CropSquareTransformation'
|
||||
import { CropTransformation } 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 { VignetteFilterTransform } from '../imageknife/transform/VignetteFilterTransform'
|
||||
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 {
|
||||
loadSrc: string | PixelMap | Resource;
|
||||
loadSrc: string | PixelMap | Resource = '';
|
||||
strategy: DiskStrategy = new AUTOMATIC();
|
||||
dontAnimateFlag = false;
|
||||
placeholderSrc: PixelMap | Resource;
|
||||
placeholderFunc: AsyncSuccess<ImageKnifeData>;
|
||||
errorholderSrc: PixelMap | Resource;
|
||||
errorholderFunc: AsyncSuccess<ImageKnifeData>;
|
||||
errorholderData: ImageKnifeData;
|
||||
thumbSizeMultiplier: number;
|
||||
placeholderSrc: PixelMap | Resource | undefined = undefined;
|
||||
placeholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
|
||||
errorholderSrc: PixelMap | Resource | undefined = undefined;
|
||||
errorholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
|
||||
errorholderData: ImageKnifeData | undefined = undefined;;
|
||||
thumbSizeMultiplier: number = 0;
|
||||
|
||||
// 如果存在缩略图,则主图延时1s加载
|
||||
thumbDelayTime: number = 1000
|
||||
thumbHolderFunc: AsyncSuccess<ImageKnifeData>;
|
||||
requestListeners: Array<AsyncCallback<ImageKnifeData>>;
|
||||
thumbHolderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
|
||||
requestListeners: Array<AsyncCallback<ImageKnifeData>> | undefined = undefined;
|
||||
|
||||
// 进度条
|
||||
progressFunc: AsyncSuccess<number>;
|
||||
progressFunc: AsyncSuccess<number> | undefined = undefined;
|
||||
|
||||
// 重试图层
|
||||
retryholderSrc: PixelMap | Resource;
|
||||
retryholderFunc: AsyncSuccess<ImageKnifeData>
|
||||
retryholderData: ImageKnifeData
|
||||
size: {
|
||||
width: number,
|
||||
height: number
|
||||
} = { width: -1, height: -1 };
|
||||
retryholderSrc: PixelMap | Resource | undefined = undefined;
|
||||
retryholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
|
||||
retryholderData: ImageKnifeData | undefined = undefined;
|
||||
size:Size= { width: -1, height: -1 };
|
||||
|
||||
// 网络下载数据回调
|
||||
allCacheInfoCallback: IAllCacheInfoCallback;
|
||||
allCacheInfoCallback: IAllCacheInfoCallback | undefined = undefined;
|
||||
onlyRetrieveFromCache: boolean = false;
|
||||
isCacheable: boolean = true;
|
||||
|
||||
|
@ -118,10 +120,7 @@ export class RequestOption {
|
|||
/**
|
||||
* set image Component size
|
||||
*/
|
||||
setImageViewSize(imageSize: {
|
||||
width: number,
|
||||
height: number
|
||||
}) {
|
||||
setImageViewSize(imageSize:Size) {
|
||||
this.size.width = imageSize.width;
|
||||
this.size.height = imageSize.height;
|
||||
return this;
|
||||
|
@ -192,7 +191,9 @@ export class RequestOption {
|
|||
}
|
||||
|
||||
addListener(func: AsyncCallback<ImageKnifeData>) {
|
||||
this.requestListeners.push(func);
|
||||
if(this.requestListeners != undefined) {
|
||||
this.requestListeners?.push(func);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -210,7 +211,10 @@ export class RequestOption {
|
|||
this.onlyRetrieveFromCache = flag;
|
||||
}
|
||||
|
||||
rotateImage(degreesToRotate: number) {
|
||||
rotateImage(degreesToRotate: number|undefined) {
|
||||
if(degreesToRotate == undefined){
|
||||
return
|
||||
}
|
||||
let rotateImage = new RotateImageTransformation(degreesToRotate);
|
||||
this.transformations.push(rotateImage);
|
||||
return this;
|
||||
|
@ -231,12 +235,10 @@ export class RequestOption {
|
|||
return this;
|
||||
}
|
||||
|
||||
roundedCorners(obj: {
|
||||
top_left: number,
|
||||
top_right: number,
|
||||
bottom_left: number,
|
||||
bottom_right: number
|
||||
}) {
|
||||
roundedCorners(obj: RoundCorner|undefined) {
|
||||
if(obj == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new RoundedCornersTransformation({
|
||||
top_left: obj.top_left,
|
||||
top_right: obj.top_right,
|
||||
|
@ -253,11 +255,10 @@ export class RequestOption {
|
|||
return this;
|
||||
}
|
||||
|
||||
cropCircleWithBorder(border: number, obj: {
|
||||
r_color: number,
|
||||
g_color: number,
|
||||
b_color: number
|
||||
}) {
|
||||
cropCircleWithBorder(border: number|undefined, obj: rgbColor|undefined) {
|
||||
if(border == undefined || obj == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new CropCircleWithBorderTransformation(border, obj)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
|
@ -269,7 +270,10 @@ export class RequestOption {
|
|||
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)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
|
@ -281,13 +285,19 @@ export class RequestOption {
|
|||
return this;
|
||||
}
|
||||
|
||||
brightnessFilter(brightness: number) {
|
||||
brightnessFilter(brightness: number|undefined) {
|
||||
if(brightness == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new BrightnessFilterTransformation(brightness)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
}
|
||||
|
||||
contrastFilter(contrast: number) {
|
||||
contrastFilter(contrast: number|undefined) {
|
||||
if(contrast == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new ContrastFilterTransformation(contrast)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
|
@ -311,43 +321,64 @@ export class RequestOption {
|
|||
return this;
|
||||
}
|
||||
|
||||
blur(radius: number) {
|
||||
blur(radius: number|undefined) {
|
||||
if(radius == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new BlurTransformation(radius)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
}
|
||||
|
||||
pixelationFilter(pixel: number) {
|
||||
pixelationFilter(pixel: number|undefined) {
|
||||
if(pixel == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new PixelationFilterTransformation(pixel)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
}
|
||||
|
||||
swirlFilter(degree: number) {
|
||||
swirlFilter(degree: number|undefined) {
|
||||
if(degree == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new SwirlFilterTransformation(degree)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
}
|
||||
|
||||
mask(maskResource: Resource) {
|
||||
mask(maskResource: Resource|undefined) {
|
||||
if(maskResource == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new MaskTransformation(maskResource)
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
}
|
||||
|
||||
kuwaharaFilter(radius: number) {
|
||||
kuwaharaFilter(radius: number|undefined) {
|
||||
if(radius == undefined){
|
||||
return
|
||||
}
|
||||
let transformation = new KuwaharaFilterTransform(radius);
|
||||
this.transformations.push(transformation);
|
||||
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);
|
||||
this.transformations.push(transformation);
|
||||
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);
|
||||
this.transformations.push(transformation);
|
||||
return this;
|
||||
|
@ -369,66 +400,77 @@ export class RequestOption {
|
|||
}
|
||||
|
||||
// 占位图解析成功
|
||||
placeholderOnComplete(imageKnifeData: ImageKnifeData) {
|
||||
placeholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
|
||||
LogUtil.log("placeholderOnComplete has called!");
|
||||
LogUtil.log("Main Image is Ready:" + this.loadMainReady);
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
// 缩略图解析成功
|
||||
thumbholderOnComplete(imageKnifeData: ImageKnifeData) {
|
||||
thumbholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
|
||||
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)
|
||||
}
|
||||
|
||||
// 加载失败 占位图解析成功
|
||||
errorholderOnComplete(imageKnifeData: ImageKnifeData) {
|
||||
errorholderOnComplete = (imageKnifeData: ImageKnifeData)=> {
|
||||
// 如果有错误占位图 先解析并保存在RequestOption中 等到加载失败时候进行调用
|
||||
this.errorholderData = imageKnifeData;
|
||||
if (this.loadErrorReady) {
|
||||
this.errorholderFunc(imageKnifeData)
|
||||
if(this.errorholderFunc != undefined) {
|
||||
this.errorholderFunc.asyncSuccess(imageKnifeData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//加载失败 占位图解析失败
|
||||
errorholderOnError(error) {
|
||||
errorholderOnError = (error:BusinessError|string)=> {
|
||||
LogUtil.log("失败占位图解析失败 error =" + error)
|
||||
}
|
||||
|
||||
retryholderOnComplete(imageKnifeData: ImageKnifeData) {
|
||||
retryholderOnComplete = (imageKnifeData: ImageKnifeData)=>{
|
||||
this.retryholderData = imageKnifeData;
|
||||
if (this.loadRetryReady) {
|
||||
this.retryholderFunc(imageKnifeData)
|
||||
if(this.retryholderFunc != undefined) {
|
||||
this.retryholderFunc?.asyncSuccess(imageKnifeData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
retryholderOnError(error) {
|
||||
retryholderOnError = (error:BusinessError|string)=>{
|
||||
LogUtil.log("重试占位图解析失败 error =" + error)
|
||||
}
|
||||
|
||||
loadComplete(imageKnifeData: ImageKnifeData) {
|
||||
loadComplete = (imageKnifeData: ImageKnifeData)=>{
|
||||
this.loadMainReady = true;
|
||||
// 三级缓存数据加载成功
|
||||
for (let requestListener of this.requestListeners) {
|
||||
var ret = requestListener("", imageKnifeData);
|
||||
if (ret) {
|
||||
break;
|
||||
if(this.requestListeners != undefined) {
|
||||
for (let i = 0;i < this.requestListeners.length; i++) {
|
||||
let requestListener = this.requestListeners[i];
|
||||
let boolInterception = requestListener.callback("", imageKnifeData);
|
||||
if (boolInterception) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -436,36 +478,46 @@ export class RequestOption {
|
|||
// 等落盘结束后主动调用#removeCurrentAndSearchNext方法
|
||||
}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(){
|
||||
globalThis.ImageKnife.removeRunning(this);
|
||||
removeCurrentAndSearchNext =()=>{
|
||||
if(ImageKnifeGlobal.getInstance().getImageKnife() != undefined) {
|
||||
(ImageKnifeGlobal.getInstance().getImageKnife())?.removeRunning(this);
|
||||
}
|
||||
}
|
||||
|
||||
loadError(err) {
|
||||
loadError = (err:BusinessError|string)=>{
|
||||
LogUtil.log("loadError:" + err);
|
||||
//失败占位图展示规则
|
||||
if (this.retryholderFunc) {
|
||||
// 重试图层优先于加载失败展示
|
||||
this.loadRetryReady = true;
|
||||
if (this.retryholderData != null) {
|
||||
this.retryholderFunc(this.retryholderData)
|
||||
this.retryholderFunc.asyncSuccess(this.retryholderData)
|
||||
}
|
||||
} else {
|
||||
// 失败图层标记,如果已经有数据直接展示失败图层
|
||||
this.loadErrorReady = true;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -22,16 +22,24 @@ import {DataStringPathProvider} from '../compress/provider/DataStringPathProvide
|
|||
import {RecourseProvider} from '../compress/provider/RecourseProvider'
|
||||
import { Engine } from '../compress/Engine'
|
||||
import { ImageKnife } from '../ImageKnife'
|
||||
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
|
||||
import common from '@ohos.app.ability.common';
|
||||
|
||||
export class CompressBuilder {
|
||||
private _mTargetDir: string;
|
||||
private _mTargetDir: string = '';
|
||||
private _mLeastCompressSize: number= 100; //KB
|
||||
private _mRenameListener: OnRenameListener;
|
||||
private _mCompressListener: OnCompressListener;
|
||||
private _mCompressionPredicate: CompressionPredicate
|
||||
private _mStreamProviders: Array<CompressAdapter>;
|
||||
private _mFocusAlpha: boolean;
|
||||
private _outFilePath: string;
|
||||
private _mRenameListener: OnRenameListener = {reName:()=>{return ''}};
|
||||
private _mCompressListener: OnCompressListener={
|
||||
start:()=> {},
|
||||
onSuccess:(p: PixelMap|null|undefined, path: string)=> {},
|
||||
onError:(s: string)=> {}
|
||||
};
|
||||
private _mCompressionPredicate: CompressionPredicate ={
|
||||
apply:(path: string)=> { return false }
|
||||
}
|
||||
private _mStreamProviders: Array<CompressAdapter> = new Array<CompressAdapter>();
|
||||
private _mFocusAlpha: boolean = false;
|
||||
private _outFilePath: string = '';
|
||||
constructor() {
|
||||
this._mStreamProviders = new Array();
|
||||
}
|
||||
|
@ -54,14 +62,14 @@ export class CompressBuilder {
|
|||
public setTargetDir(targetDir: string): CompressBuilder {
|
||||
this._mTargetDir = targetDir;
|
||||
if (this._mTargetDir) {
|
||||
var timestamp = (new Date()).valueOf();
|
||||
let timestamp = (new Date()).valueOf();
|
||||
this._outFilePath = this._mTargetDir + "/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
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];
|
||||
if (typeof element === "string") {
|
||||
this.loadString(element);
|
||||
|
@ -106,9 +114,9 @@ export class CompressBuilder {
|
|||
|
||||
public async get():Promise<string> {
|
||||
if (!this._mTargetDir) {
|
||||
let context = globalThis.ImageKnife.getImageKnifeContext();
|
||||
let context= (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext);
|
||||
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";
|
||||
let result = await this.startAsyncCompress();
|
||||
return result;
|
||||
|
@ -119,15 +127,15 @@ export class CompressBuilder {
|
|||
}
|
||||
|
||||
private async startAsyncCompress():Promise<string> {
|
||||
let compressPromise = new Promise((resolve, reject) => {
|
||||
let compressPromise:Promise<string> = new Promise((resolve, reject) => {
|
||||
|
||||
let compressListener: OnCompressListener = {
|
||||
start() {
|
||||
start:()=>{
|
||||
},
|
||||
onScuccess(p: PixelMap, path: string) {
|
||||
onSuccess:(p: PixelMap|undefined|null, path: string)=> {
|
||||
resolve(path);
|
||||
},
|
||||
onError(s: string) {
|
||||
onError:(s: string)=> {
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -138,7 +146,7 @@ export class CompressBuilder {
|
|||
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 isOpenfilter = false;
|
||||
if (this._mCompressionPredicate) {
|
||||
|
@ -171,11 +179,11 @@ export class CompressBuilder {
|
|||
return;
|
||||
}
|
||||
if (this._mRenameListener) {
|
||||
var name = this._mRenameListener.reName();
|
||||
let name = this._mRenameListener.reName();
|
||||
if (this._outFilePath && name) {
|
||||
var start = this._outFilePath.lastIndexOf("/") + 1
|
||||
var end = this._outFilePath.length;
|
||||
var replaceStr = this._outFilePath.substring(start, end);
|
||||
let start = this._outFilePath.lastIndexOf("/") + 1
|
||||
let end = this._outFilePath.length;
|
||||
let replaceStr = this._outFilePath.substring(start, end);
|
||||
this._outFilePath = this._outFilePath.replace(replaceStr, name);
|
||||
}
|
||||
}
|
||||
|
@ -183,7 +191,7 @@ export class CompressBuilder {
|
|||
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 isOpenfilter = false;
|
||||
if (this._mCompressionPredicate) {
|
||||
|
@ -194,15 +202,15 @@ export class CompressBuilder {
|
|||
this._mCompressListener, this._mCompressionPredicate).compress();
|
||||
} else {
|
||||
if (this._mCompressListener) {
|
||||
this._mCompressListener.onScuccess(null, element.getRecoursePath());
|
||||
this._mCompressListener.onSuccess(null, element.getRecoursePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getImageCacheFile() {
|
||||
let context = globalThis.ImageKnife.getImageKnifeContext();
|
||||
var timestamp = (new Date()).valueOf();
|
||||
let context = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext)
|
||||
let timestamp = (new Date()).valueOf();
|
||||
this._outFilePath = context.filesDir + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
|
||||
this.startCompress();
|
||||
}
|
||||
|
|
|
@ -13,14 +13,15 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import {OnCompressListener} from '../compress/listener/OnCompressListener'
|
||||
import {CompressionPredicate} from '../compress/listener/CompressionPredicate'
|
||||
import {CompressAdapter} from "../compress/provider/CompressAdapter"
|
||||
import {DataStringPathProvider} from '../compress/provider/DataStringPathProvider'
|
||||
import {RecourseProvider} from '../compress/provider/RecourseProvider'
|
||||
import {FileUtils} from '../../cache/FileUtils'
|
||||
import { OnCompressListener } from '../compress/listener/OnCompressListener'
|
||||
import { CompressionPredicate } from '../compress/listener/CompressionPredicate'
|
||||
import { CompressAdapter } from "../compress/provider/CompressAdapter"
|
||||
import { DataStringPathProvider } from '../compress/provider/DataStringPathProvider'
|
||||
import { RecourseProvider } from '../compress/provider/RecourseProvider'
|
||||
import { FileUtils } from '../../cache/FileUtils'
|
||||
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 {
|
||||
private mFocusAlpha: boolean;
|
||||
|
@ -48,10 +49,10 @@ export class Engine {
|
|||
srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
|
||||
srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;
|
||||
|
||||
var longSide = Math.max(srcWidth, srcHeight);
|
||||
var shortSide = Math.min(srcWidth, srcHeight);
|
||||
let longSide = Math.max(srcWidth, srcHeight);
|
||||
let shortSide = Math.min(srcWidth, srcHeight);
|
||||
|
||||
var scale = shortSide / longSide;
|
||||
let scale = shortSide / longSide;
|
||||
if (scale <= 1 && scale > 0.5625) {
|
||||
if (longSide < 1664) {
|
||||
return 1;
|
||||
|
@ -72,7 +73,7 @@ export class Engine {
|
|||
compress() {
|
||||
if (this.mCompressAdapter instanceof DataStringPathProvider) {
|
||||
// file
|
||||
this.mCompressAdapter.openInternal((buffer) => {
|
||||
this.mCompressAdapter.openInternal({ compressDataListener: (buffer: ArrayBuffer) => {
|
||||
if (!buffer) {
|
||||
if (this.mCompressListener) {
|
||||
this.mCompressListener.onError("file read fail,and date is empty")
|
||||
|
@ -83,36 +84,36 @@ export class Engine {
|
|||
return;
|
||||
}
|
||||
|
||||
var imageResource = image.createImageSource(buffer as any);
|
||||
let imageResource: image.ImageSource = image.createImageSource(buffer);
|
||||
imageResource.getImageInfo()
|
||||
.then(info => {
|
||||
var height = info.size.height;
|
||||
var width = info.size.width;
|
||||
var computeSize = this.computeSize(width, height);
|
||||
console.info("Engine compress computeSize:" + computeSize);
|
||||
let options = {
|
||||
editable: true,
|
||||
sampleSize: computeSize,
|
||||
desiredPixelFormat: image.PixelMapFormat.RGB_565,
|
||||
}
|
||||
imageResource.createPixelMap(options)
|
||||
.then(bitmap => {
|
||||
let height = info.size.height;
|
||||
let width = info.size.width;
|
||||
let computeSize = this.computeSize(width, height);
|
||||
console.info("Engine compress computeSize:" + computeSize);
|
||||
let options: image.DecodingOptions = {
|
||||
editable: true,
|
||||
sampleSize: computeSize,
|
||||
desiredPixelFormat: image.PixelMapFormat.RGB_565,
|
||||
}
|
||||
imageResource.createPixelMap(options)
|
||||
.then(bitmap => {
|
||||
|
||||
})
|
||||
.catch((error: BusinessError) => {
|
||||
this.mCompressListener.onError("ptah createPixelMap fail,because error:" + JSON.stringify(error as BusinessError))
|
||||
})
|
||||
|
||||
|
||||
})
|
||||
.catch(error => {
|
||||
this.mCompressListener.onError("ptah createPixelMap fail,because error:" + JSON.stringify(error))
|
||||
.catch((error: BusinessError) => {
|
||||
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) {
|
||||
// resource
|
||||
this.mCompressAdapter.openInternal((buffer) => {
|
||||
this.mCompressAdapter.openInternal({ compressDataListener: (buffer: ArrayBuffer) => {
|
||||
if (!buffer) {
|
||||
if (this.mCompressListener) {
|
||||
this.mCompressListener.onError("resource read fail,and date is empty")
|
||||
|
@ -122,86 +123,78 @@ export class Engine {
|
|||
if (!this.checkNeedCompress(buffer)) {
|
||||
return;
|
||||
}
|
||||
var imageResource = image.createImageSource(buffer as any);
|
||||
let imageResource: image.ImageSource = image.createImageSource(buffer);
|
||||
imageResource.getImageInfo()
|
||||
.then(info => {
|
||||
var height = info.size.height;
|
||||
var width = info.size.width;
|
||||
var computeSize = this.computeSize(width, height);
|
||||
let packer = {
|
||||
format: ["image/jpeg"],
|
||||
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 height = info.size.height;
|
||||
let width = info.size.width;
|
||||
let computeSize = this.computeSize(width, height);
|
||||
let packer: image.PackingOption = {
|
||||
format: "image/jpeg",
|
||||
quality: computeSize,
|
||||
}
|
||||
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 undefined ="+ (compressBuffer == undefined) );
|
||||
let dirPath = this.mPath.substring(0, this.mPath.lastIndexOf("/") + 1);
|
||||
var isDirectory = this.checkDirExist(dirPath);
|
||||
if (isDirectory) {
|
||||
this.saveFile(this.mPath, compressBuffer);
|
||||
this.handResult(compressBuffer, this.mPath);
|
||||
} else {
|
||||
fileio.mkdir(dirPath)
|
||||
.then(() => {
|
||||
console.log("compressBuffer is null =" + (compressBuffer == null));
|
||||
console.log("compressBuffer is undefined =" + (compressBuffer == undefined));
|
||||
let dirPath = this.mPath.substring(0, this.mPath.lastIndexOf("/") + 1);
|
||||
let isDirectory = this.checkDirExist(dirPath);
|
||||
if (isDirectory) {
|
||||
this.saveFile(this.mPath, compressBuffer);
|
||||
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) {
|
||||
var imageRes = image.createImageSource(buffer as any);
|
||||
let a={
|
||||
let imageRes:image.ImageSource = image.createImageSource(buffer);
|
||||
let a:image.DecodingOptions = {
|
||||
editable: true,
|
||||
}
|
||||
imageRes.createPixelMap(a)
|
||||
.then(bitmap => {
|
||||
if (this.mCompressListener) {
|
||||
this.mCompressListener.onScuccess(bitmap, path);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (this.mCompressListener) {
|
||||
this.mCompressListener.onError("buffer generated pixelMap fail,because error:" + JSON.stringify(error))
|
||||
}
|
||||
})
|
||||
if (this.mCompressListener) {
|
||||
this.mCompressListener.onSuccess(bitmap, path);
|
||||
}
|
||||
})
|
||||
.catch((error:BusinessError) => {
|
||||
if (this.mCompressListener) {
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
var length = buf.byteLength / 1024;
|
||||
let length = buf.byteLength / 1024;
|
||||
return length > this._mLeastCompressSize;
|
||||
}
|
||||
|
||||
private saveFile(path: string, content: ArrayBuffer) {
|
||||
FileUtils.getInstance().writeFile(path,content);
|
||||
FileUtils.getInstance().writeFile(path, content);
|
||||
}
|
||||
|
||||
private checkDirExist(dirPath: string): boolean{
|
||||
var isExist;
|
||||
try {
|
||||
fileio.accessSync(dirPath, 0)
|
||||
isExist = true;
|
||||
} catch (e) {
|
||||
//不符合条件则进入
|
||||
isExist = false;
|
||||
}
|
||||
private checkDirExist(dirPath: string): boolean {
|
||||
let isExist:boolean = fs.accessSync(dirPath);
|
||||
return isExist;
|
||||
}
|
||||
}
|
|
@ -14,5 +14,5 @@
|
|||
*/
|
||||
|
||||
export interface CompressDataListener<T> {
|
||||
(t: T);
|
||||
compressDataListener:(t: T)=>void;
|
||||
}
|
|
@ -17,5 +17,5 @@
|
|||
* filter out unsupported
|
||||
*/
|
||||
export interface CompressionPredicate {
|
||||
apply(path: string): boolean;
|
||||
apply:(path: string)=>boolean;
|
||||
}
|
|
@ -19,13 +19,13 @@ export interface OnCompressListener {
|
|||
/**
|
||||
* compress start
|
||||
*/
|
||||
start();
|
||||
start:()=>void;
|
||||
/**
|
||||
* compress success
|
||||
*/
|
||||
onScuccess(p: PixelMap, path: string);
|
||||
onSuccess:(p: PixelMap|undefined|null, path: string)=>void;
|
||||
/**
|
||||
* compress fail
|
||||
*/
|
||||
onError(s: string);
|
||||
onError:(s: string)=>void;
|
||||
}
|
|
@ -17,5 +17,5 @@
|
|||
* rename listener
|
||||
*/
|
||||
export interface OnRenameListener {
|
||||
reName():string;
|
||||
reName:()=>string;
|
||||
}
|
|
@ -17,8 +17,8 @@ import {CompressProvider} from "../provider/CompressProvider"
|
|||
import {CompressDataListener} from "../listener/CompressDataListener"
|
||||
|
||||
export abstract class CompressAdapter implements CompressProvider {
|
||||
mData: ArrayBuffer;
|
||||
mPath: string;
|
||||
mData: ArrayBuffer = new ArrayBuffer(0);
|
||||
mPath: string = '';
|
||||
|
||||
close() {
|
||||
}
|
||||
|
@ -35,9 +35,9 @@ export abstract class CompressAdapter implements CompressProvider {
|
|||
|
||||
abstract getRecoursePath(): string;
|
||||
|
||||
abstract getPixelMapFormat(): PixelMapFormat;
|
||||
abstract getPixelMapFormat(): PixelMapFormat | undefined;
|
||||
|
||||
getFormat(s: string): PixelMapFormat{
|
||||
getFormat(s: string): PixelMapFormat | undefined{
|
||||
if (!s) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
|
@ -31,14 +31,14 @@ export class DataStringPathProvider extends CompressAdapter {
|
|||
if (!this.mPath) {
|
||||
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;
|
||||
if (callback) {
|
||||
callback(buffer);
|
||||
callback.compressDataListener(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
getPixelMapFormat(): PixelMapFormat{
|
||||
getPixelMapFormat(): PixelMapFormat|undefined{
|
||||
if (!this.mPath) {
|
||||
return PixelMapFormat.NONE;
|
||||
}
|
||||
|
|
|
@ -13,27 +13,30 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import {CompressAdapter, PixelMapFormat} from "../provider/CompressAdapter"
|
||||
import {CompressDataListener} from "../listener/CompressDataListener"
|
||||
import {FileTypeUtil} from '../../../imageknife/utils/FileTypeUtil'
|
||||
import { CompressAdapter, PixelMapFormat } from "../provider/CompressAdapter"
|
||||
import { CompressDataListener } from "../listener/CompressDataListener"
|
||||
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 {
|
||||
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 _mResourceData: Resource;
|
||||
private _mPixelMapHeader: string;
|
||||
private _mResourceData?: Resource = undefined;
|
||||
private _mPixelMapHeader: string = '';
|
||||
|
||||
constructor(s: Resource) {
|
||||
super()
|
||||
this._mResourceData = s;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
getRecoursePath(): string{
|
||||
getRecoursePath(): string {
|
||||
return this.mPath;
|
||||
}
|
||||
|
||||
|
@ -42,21 +45,22 @@ export class RecourseProvider extends CompressAdapter {
|
|||
if (!this._mResourceData) {
|
||||
throw Error("compress resource is empty");
|
||||
}
|
||||
globalThis.ImageKnife.getImageKnifeContext().resourceManager
|
||||
.getMedia(this._mResourceData.id)
|
||||
((ImageKnifeGlobal.getInstance()
|
||||
.getHapContext() as Record<string, Object>).resourceManager as resourceManager.ResourceManager)
|
||||
.getMediaContent(this._mResourceData.id)
|
||||
.then(data => {
|
||||
let buffer = this.uint8ArrayToBuffer(data);
|
||||
let fileTypeUtil = new FileTypeUtil()
|
||||
this._mPixelMapHeader = fileTypeUtil.getFileType(buffer);
|
||||
callback(buffer);
|
||||
callback.compressDataListener(buffer);
|
||||
})
|
||||
.catch(err => {
|
||||
console.log("RecourseProvider openInternal err" + JSON.stringify(err));
|
||||
.catch((err: BusinessError) => {
|
||||
console.log("RecourseProvider openInternal err" + JSON.stringify(err as BusinessError));
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
getPixelMapFormat(): PixelMapFormat{
|
||||
getPixelMapFormat(): PixelMapFormat|undefined{
|
||||
if (!this._mPixelMapHeader) {
|
||||
return PixelMapFormat.NONE;
|
||||
}
|
||||
|
@ -66,14 +70,14 @@ export class RecourseProvider extends CompressAdapter {
|
|||
* data decode
|
||||
*/
|
||||
decode(base64: string, callback: CompressDataListener<ArrayBuffer>) {
|
||||
let bufferLength = base64.length,
|
||||
len = base64.length,
|
||||
i,
|
||||
p = 0,
|
||||
encoded1,
|
||||
encoded2,
|
||||
encoded3,
|
||||
encoded4;
|
||||
let bufferLength: number = base64.length;
|
||||
let len: number = base64.length;
|
||||
let i: number = 0;
|
||||
let p: number = 0;
|
||||
let encoded1: number = 0;
|
||||
let encoded2: number = 0;
|
||||
let encoded3: number = 0;
|
||||
let encoded4: number = 0;
|
||||
|
||||
if (base64[base64.length - 1] === '=') {
|
||||
bufferLength--;
|
||||
|
@ -98,7 +102,7 @@ export class RecourseProvider extends CompressAdapter {
|
|||
}
|
||||
this.mData = arraybuffer;
|
||||
if (callback) {
|
||||
callback(arraybuffer);
|
||||
callback.compressDataListener(arraybuffer);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -15,37 +15,39 @@
|
|||
|
||||
import { CropCallback } from './CropCallback'
|
||||
import image from "@ohos.multimedia.image"
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
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) {
|
||||
console.log("Crop buf is empty");
|
||||
if (func) {
|
||||
func("Crop buf is empty", null);
|
||||
func.cropCallback("Crop buf is empty", null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var imageSource = image.createImageSource(buf as any);
|
||||
getPixelMapSize(imageSource, (error, size: {
|
||||
width: number,
|
||||
height: number
|
||||
}) => {
|
||||
let imageSource:image.ImageSource = image.createImageSource(buf);
|
||||
let crop:CropCallback<CropSize|null> = { cropCallback: (error:BusinessError|string, size: CropSize|null) => {
|
||||
if (!size) {
|
||||
func(error, null)
|
||||
func?.cropCallback(error, null)
|
||||
return;
|
||||
}
|
||||
var pixelMapWidth = size.width;
|
||||
var pixelMapHeight = size.height;
|
||||
let pixelMapWidth = size.width;
|
||||
let pixelMapHeight = size.height;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
var options = {
|
||||
let options: image.DecodingOptions = {
|
||||
editable: true,
|
||||
rotate: 0,
|
||||
desiredSize: {
|
||||
|
@ -58,58 +60,57 @@ export namespace Crop {
|
|||
},
|
||||
}
|
||||
imageSource.createPixelMap(options)
|
||||
.then((data) => {
|
||||
.then((data:PixelMap) => {
|
||||
if (colorRatio && colorRatio <= 1) {
|
||||
colorRatioPixelMap(data, pixelMapWidth, pixelMapHeight, colorRatio, func);
|
||||
} else {
|
||||
func("", data);
|
||||
func?.cropCallback("", data);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
func(e, null);
|
||||
.catch((e:BusinessError) => {
|
||||
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) {
|
||||
func("colorRatio pixelMap is null", null);
|
||||
func?.cropCallback("colorRatio pixelMap is null", null);
|
||||
return;
|
||||
}
|
||||
if (colorRatio > 1) {
|
||||
throw new Error("the colorRatio must be <= 1");
|
||||
}
|
||||
var buffer = new ArrayBuffer(width * height * 5);
|
||||
var bytes = new Uint8Array(buffer);
|
||||
var buffer1B = new ArrayBuffer(width * height * 5);
|
||||
var bytes1B = new Uint8Array(buffer1B);
|
||||
let buffer = new ArrayBuffer(width * height * 5);
|
||||
let bytes = new Uint8Array(buffer);
|
||||
let buffer1B = new ArrayBuffer(width * height * 5);
|
||||
let bytes1B = new Uint8Array(buffer1B);
|
||||
|
||||
let readPromise = data.readPixelsToBuffer(buffer)
|
||||
let readPromise:Promise<void> = data.readPixelsToBuffer(buffer)
|
||||
await readPromise;
|
||||
for (let i = 0;i < bytes.length; i++) {
|
||||
bytes1B[i] = bytes[i] * colorRatio;
|
||||
}
|
||||
let writePromise = data.writeBufferToPixels(buffer1B)
|
||||
let writePromise:Promise<void> = data.writeBufferToPixels(buffer1B)
|
||||
await writePromise;
|
||||
func("", data);
|
||||
func?.cropCallback("", data);
|
||||
}
|
||||
|
||||
|
||||
var getPixelMapSize = (imageSource: any, func: CropCallback<{
|
||||
width: number,
|
||||
height: number
|
||||
}>)=> {
|
||||
let getPixelMapSize = (imageSource: image.ImageSource, func: CropCallback<CropSize|null>)=> {
|
||||
if (!imageSource) {
|
||||
return;
|
||||
}
|
||||
imageSource.getImageInfo((err, value) => {
|
||||
if (err) {
|
||||
func(err, null)
|
||||
func.cropCallback(err, null)
|
||||
return;
|
||||
}
|
||||
var pWidth = value.size.width;
|
||||
var pHeight = value.size.height;
|
||||
func('', { width: pWidth, height: pHeight });
|
||||
let pWidth = value.size.width;
|
||||
let pHeight = value.size.height;
|
||||
func.cropCallback('', { width: pWidth, height: pHeight });
|
||||
})
|
||||
}
|
||||
}
|
|
@ -12,6 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export interface CropCallback<T> {
|
||||
(err, data: T)
|
||||
cropCallback:(err:BusinessError|string, data: T)=>void
|
||||
}
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import {CropOptions} from "../crop/CropOptions";
|
||||
import {CropOptions,Size} from "../crop/CropOptions";
|
||||
|
||||
@Component
|
||||
export struct CropImage {
|
||||
|
@ -35,10 +35,15 @@ export struct CropImage {
|
|||
})
|
||||
.scale({ x: this._scale, y: this._scale, z: 1.0 })
|
||||
.gesture(GestureGroup(GestureMode.Parallel,
|
||||
RotationGesture({ fingers: 1 }).onActionUpdate(event => {
|
||||
this._rotate = event.angle;
|
||||
}), PinchGesture({ fingers: 2 }).onActionUpdate(event => {
|
||||
this._scale = event.scale;
|
||||
RotationGesture({ fingers: 1 }).onActionUpdate((event?: GestureEvent) => {
|
||||
if(event != undefined) {
|
||||
this._rotate = event.angle;
|
||||
}
|
||||
}), PinchGesture({ fingers: 2 }).onActionUpdate((event?: GestureEvent) => {
|
||||
if(event != undefined) {
|
||||
this._scale = event.scale;
|
||||
}
|
||||
|
||||
})
|
||||
).onCancel(() => {
|
||||
console.log("CropImage gesture cancel");
|
||||
|
|
|
@ -12,11 +12,12 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export class CropOptions {
|
||||
src: string | PixelMap | Resource;
|
||||
size: {
|
||||
width: number,
|
||||
height: number;
|
||||
}
|
||||
export interface Size{
|
||||
width: number,
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface CropOptions {
|
||||
src: string | PixelMap | Resource;
|
||||
size: Size
|
||||
}
|
|
@ -15,11 +15,11 @@
|
|||
import image from "@ohos.multimedia.image"
|
||||
import { Crop } from './Crop'
|
||||
import { CropCallback } from './CropCallback'
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
@Component
|
||||
struct PixelMapCrop {
|
||||
@Watch('watchOptions') @Link options: PixelMapCrop.Options;
|
||||
@Watch('watchCropTap') @Prop cropTap: boolean;
|
||||
export struct PixelMapCrop {
|
||||
@Watch('watchOptions') @Link options: Options;
|
||||
@Watch('watchCropTap') @Prop cropTap: boolean = false;
|
||||
@State bWidth: number = 0;
|
||||
@State bHeight: number = 0;
|
||||
@State cWidth: number = 0;
|
||||
|
@ -305,59 +305,60 @@ struct PixelMapCrop {
|
|||
// .backgroundColor('#33000000')
|
||||
.onReady(() => {
|
||||
})
|
||||
.onTouch((event: TouchEvent) => {
|
||||
if (event.type === TouchType.Down) {
|
||||
// 手指按下
|
||||
this.downX = event.touches[0].x;
|
||||
this.downY = event.touches[0].y;
|
||||
.onTouch((event?: TouchEvent) => {
|
||||
if(event != undefined) {
|
||||
if (event.type === TouchType.Down) {
|
||||
// 手指按下
|
||||
this.downX = event.touches[0].x;
|
||||
this.downY = event.touches[0].y;
|
||||
|
||||
this.lastMoveX = event.touches[0].x;
|
||||
this.lastMoveY = event.touches[0].y;
|
||||
this.lastMoveX = event.touches[0].x;
|
||||
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;
|
||||
height: number;
|
||||
pixelMap: PixelMap;
|
||||
export class Options {
|
||||
width: number = 0;
|
||||
height: number = 0;
|
||||
pixelMap?: PixelMap = undefined;
|
||||
|
||||
// 是否需要绘制线
|
||||
hasGuideLine: boolean;
|
||||
pixelBuffer: ArrayBuffer;
|
||||
hasGuideLine: boolean = false;
|
||||
pixelBuffer: ArrayBuffer = new ArrayBuffer(0);
|
||||
// 展示pixel宽度
|
||||
pixelWidth: number;
|
||||
pixelWidth: number = 0;
|
||||
// 展示pixel高度
|
||||
pixelHeight: number;
|
||||
pixelHeight: number = 0;
|
||||
// 缩放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() {
|
||||
|
||||
}
|
||||
|
||||
// 裁剪动作
|
||||
setCropFunction(crop: (error, pixelmap, sx, sy) => void) {
|
||||
setCropFunction(crop: (error:BusinessError|string, pixelmap:PixelMap|null, sx:number, sy:number) => void) {
|
||||
this.cropFunction = crop;
|
||||
|
||||
this.cropAction = (topLeftPoint, bottomRightPoint, scaleInside) => {
|
||||
let dx = vp2px(1) * topLeftPoint[0] * 1.0 / scaleInside;
|
||||
let dy = vp2px(1) * topLeftPoint[1] * 1.0 / scaleInside;
|
||||
let sx = vp2px(1) * (bottomRightPoint[0] - topLeftPoint[0]) * 1.0 / scaleInside;
|
||||
let sy = vp2px(1) * (bottomRightPoint[1] - topLeftPoint[1]) * 1.0 / scaleInside;
|
||||
Crop.crop(this.pixelBuffer, dx, dy, sx, sy, (error, pixelmap) => {
|
||||
this.cropFunction(error, pixelmap, sx, sy)
|
||||
this.cropAction = (topLeftPoint:number[], bottomRightPoint:number[], scaleInside:number) => {
|
||||
let dx:number = vp2px(1) * topLeftPoint[0] * 1.0 / scaleInside;
|
||||
let dy:number = vp2px(1) * topLeftPoint[1] * 1.0 / scaleInside;
|
||||
let sx:number = vp2px(1) * (bottomRightPoint[0] - topLeftPoint[0]) * 1.0 / scaleInside;
|
||||
let sy:number = vp2px(1) * (bottomRightPoint[1] - topLeftPoint[1]) * 1.0 / scaleInside;
|
||||
Crop.crop(this.pixelBuffer, dx, dy, sx, sy, {
|
||||
cropCallback: (error: BusinessError | string, pixelmap: PixelMap | null) => {
|
||||
this.cropFunction(error, pixelmap, sx, sy)
|
||||
}
|
||||
}, 1);
|
||||
|
||||
}
|
||||
|
||||
return this;
|
||||
|
@ -857,7 +858,7 @@ namespace PixelMapCrop {
|
|||
//数据赋值
|
||||
this.pixelBuffer = buffer;
|
||||
|
||||
let imageSource = image.createImageSource(buffer as any);
|
||||
let imageSource:image.ImageSource = image.createImageSource(buffer);
|
||||
imageSource.getImageInfo().then((imageInfo) => {
|
||||
//获取宽高
|
||||
|
||||
|
@ -879,7 +880,7 @@ namespace PixelMapCrop {
|
|||
this.pixelWidth = imageInfo.size.width * scaleInside;
|
||||
this.pixelHeight = imageInfo.size.height * scaleInside;
|
||||
|
||||
let options = {
|
||||
let options:image.DecodingOptions = {
|
||||
editable: true,
|
||||
rotate: 0,
|
||||
desiredSize: {
|
||||
|
@ -887,7 +888,7 @@ namespace PixelMapCrop {
|
|||
height: imageInfo.size.height * scaleInside,
|
||||
}
|
||||
}
|
||||
imageSource.createPixelMap(options).then((pixelmap) => {
|
||||
imageSource.createPixelMap(options).then((pixelmap:PixelMap) => {
|
||||
this.pixelMap = pixelmap;
|
||||
if (readyCrop) {
|
||||
readyCrop();
|
||||
|
@ -898,6 +899,6 @@ namespace PixelMapCrop {
|
|||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default PixelMapCrop;
|
||||
|
||||
|
||||
|
|
|
@ -14,8 +14,8 @@
|
|||
*/
|
||||
|
||||
export class ArcPoint {
|
||||
private x: number;
|
||||
private y: number;
|
||||
private x: number = 0;
|
||||
private y: number = 0;
|
||||
|
||||
constructor(x: number, y: number) {
|
||||
this.y = y;
|
||||
|
|
|
@ -13,12 +13,12 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
export class PixelEntry {
|
||||
a: number;
|
||||
b: number;
|
||||
r: number;
|
||||
g: number;
|
||||
f: number;
|
||||
pixel: number;
|
||||
a: number = 0;
|
||||
b: number = 0;
|
||||
r: number = 0;
|
||||
g: number = 0;
|
||||
f: number = 0;
|
||||
pixel: number = 0;
|
||||
|
||||
public toString(): string {
|
||||
return "PixelEntry a:" + this.a + ";b:" + this.b + ";r:" + this.r + ";g:" + this.g + ";f:" + this.f;
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { RequestOption } from '../../imageknife/RequestOption'
|
||||
import { RequestOption,Size } from '../../imageknife/RequestOption'
|
||||
import { FileTypeUtil } from '../../imageknife/utils/FileTypeUtil'
|
||||
import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData'
|
||||
import { ParseImageUtil } from '../utils/ParseImageUtil'
|
||||
|
@ -22,8 +22,9 @@ import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
|
|||
import { ParseResClient } from '../resourcemanage/ParseResClient'
|
||||
import {LogUtil} from '../../imageknife/utils/LogUtil'
|
||||
import image from '@ohos.multimedia.image'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
|
||||
export class ErrorHolderManager {
|
||||
export class ErrorHolderManager<T> {
|
||||
private options: RequestOption;
|
||||
|
||||
constructor(option: RequestOption) {
|
||||
|
@ -31,16 +32,16 @@ export class ErrorHolderManager {
|
|||
}
|
||||
|
||||
static execute(option: RequestOption) {
|
||||
let manager = new ErrorHolderManager(option);
|
||||
return new Promise(manager.process.bind(manager))
|
||||
.then(option.errorholderOnComplete.bind(option)).catch(option.errorholderOnError.bind(option));
|
||||
let manager:ErrorHolderManager<ImageKnifeData> = new ErrorHolderManager<ImageKnifeData>(option);
|
||||
return new Promise(manager.process)
|
||||
.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);
|
||||
}
|
||||
|
||||
private displayErrorholder(onComplete, onError) {
|
||||
private displayErrorholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
|
||||
LogUtil.log("displayErrorholder")
|
||||
if ((typeof (this.options.errorholderSrc as image.PixelMap).isEditable) == 'boolean') {
|
||||
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;
|
||||
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
|
||||
let resourceFetch = new ParseResClient();
|
||||
let suc = (arraybuffer) => {
|
||||
let fileTypeUtil = new FileTypeUtil();
|
||||
let typeValue = fileTypeUtil.getFileType(arraybuffer);
|
||||
let suc = (arraybuffer:ArrayBuffer) => {
|
||||
let fileTypeUtil:FileTypeUtil = new FileTypeUtil();
|
||||
let typeValue:string = fileTypeUtil.getFileType(arraybuffer);
|
||||
switch (typeValue) {
|
||||
case SupportFormat.svg:
|
||||
this.svgProcess(onComplete, onError, arraybuffer, typeValue)
|
||||
|
@ -78,18 +79,18 @@ export class ErrorHolderManager {
|
|||
}
|
||||
}
|
||||
|
||||
private svgProcess(onComplete, onError, arraybuffer, typeValue) {
|
||||
let svgParseImpl = new SVGParseImpl()
|
||||
let size = { width: this.options.size.width, height: this.options.size.height }
|
||||
private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
|
||||
let svgParseImpl:SVGParseImpl = new SVGParseImpl()
|
||||
let size:Size = { width: this.options.size.width, height: this.options.size.height }
|
||||
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
onComplete(imageKnifeData)
|
||||
}).catch(err => {
|
||||
}).catch((err:BusinessError) => {
|
||||
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 success = (value: PixelMap) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import {RequestOption} from "../../imageknife/RequestOption"
|
||||
import {RequestOption,Size} from "../../imageknife/RequestOption"
|
||||
import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts"
|
||||
import {Base64} from "../../cache/Base64"
|
||||
import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil"
|
||||
|
@ -20,12 +20,12 @@ import {ImageKnifeData,ImageKnifeType} from "../ImageKnifeData"
|
|||
import {ParseImageUtil} from '../utils/ParseImageUtil'
|
||||
import {ParseResClient} from '../resourcemanage/ParseResClient'
|
||||
import { SupportFormat } from '../utils/FileTypeUtil'
|
||||
import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
|
||||
import { SVGParseImpl} from '../utils/svg/SVGParseImpl'
|
||||
import {LogUtil} from '../../imageknife/utils/LogUtil'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import image from "@ohos.multimedia.image"
|
||||
|
||||
export class PlaceHolderManager {
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export class PlaceHolderManager<T> {
|
||||
private options: RequestOption;
|
||||
|
||||
constructor(option: RequestOption) {
|
||||
|
@ -33,16 +33,16 @@ export class PlaceHolderManager {
|
|||
}
|
||||
|
||||
static execute(option: RequestOption) {
|
||||
let manager = new PlaceHolderManager(option);
|
||||
return new Promise(manager.process.bind(manager))
|
||||
.then(option.placeholderOnComplete.bind(option)).catch(option.placeholderOnError.bind(option));
|
||||
let manager:PlaceHolderManager<ImageKnifeData> = new PlaceHolderManager<ImageKnifeData>(option);
|
||||
return new Promise(manager.process)
|
||||
.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);
|
||||
}
|
||||
|
||||
private displayPlaceholder(onComplete, onError) {
|
||||
private displayPlaceholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void){
|
||||
LogUtil.log("displayPlaceholder")
|
||||
if ((typeof (this.options.placeholderSrc as image.PixelMap).isEditable) == 'boolean') {
|
||||
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;
|
||||
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
|
||||
let resourceFetch = new ParseResClient();
|
||||
let suc = (arraybuffer) => {
|
||||
let suc = (arraybuffer:ArrayBuffer) => {
|
||||
let fileTypeUtil = new FileTypeUtil();
|
||||
let typeValue = fileTypeUtil.getFileType(arraybuffer);
|
||||
switch (typeValue) {
|
||||
|
@ -82,19 +82,19 @@ export class PlaceHolderManager {
|
|||
|
||||
|
||||
|
||||
private svgProcess(onComplete, onError, arraybuffer, typeValue) {
|
||||
let svgParseImpl = new SVGParseImpl()
|
||||
let size = { width: this.options.size.width, height: this.options.size.height }
|
||||
private svgProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
|
||||
let svgParseImpl:SVGParseImpl = new SVGParseImpl()
|
||||
let size:Size = { width: this.options.size.width, height: this.options.size.height }
|
||||
svgParseImpl.parseSvg(arraybuffer, size).then((value: PixelMap) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
onComplete(imageKnifeData)
|
||||
}).catch(err => {
|
||||
}).catch((err:BusinessError) => {
|
||||
onError(err)
|
||||
})
|
||||
}
|
||||
|
||||
private mediaImageProcess(onComplete, onError, arraybuffer, typeValue) {
|
||||
let parseImageUtil = new ParseImageUtil()
|
||||
private mediaImageProcess(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void, arraybuffer:ArrayBuffer, typeValue:string) {
|
||||
let parseImageUtil:ParseImageUtil = new ParseImageUtil()
|
||||
let success = (value: PixelMap) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
onComplete(imageKnifeData)
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import {RequestOption} from "../../imageknife/RequestOption"
|
||||
import {RequestOption,Size} from "../../imageknife/RequestOption"
|
||||
import {ResourceTypeEts} from "../../imageknife/constants/ResourceTypeEts"
|
||||
import {Base64} from "../../cache/Base64"
|
||||
import {FileTypeUtil} from "../../imageknife/utils/FileTypeUtil"
|
||||
|
@ -24,8 +24,8 @@ import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
|
|||
import {LogUtil} from '../../imageknife/utils/LogUtil'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import image from "@ohos.multimedia.image"
|
||||
|
||||
export class RetryHolderManager {
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export class RetryHolderManager<T> {
|
||||
private options: RequestOption;
|
||||
|
||||
constructor(option: RequestOption) {
|
||||
|
@ -33,16 +33,16 @@ export class RetryHolderManager {
|
|||
}
|
||||
|
||||
static execute(option: RequestOption) {
|
||||
let manager = new RetryHolderManager(option);
|
||||
return new Promise(manager.process.bind(manager))
|
||||
.then(option.retryholderOnComplete.bind(option)).catch(option.retryholderOnError.bind(option));
|
||||
let manager:RetryHolderManager<ImageKnifeData> = new RetryHolderManager<ImageKnifeData>(option);
|
||||
return new Promise(manager.process)
|
||||
.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);
|
||||
}
|
||||
|
||||
private displayRetryholder(onComplete, onError) {
|
||||
private displayRetryholder(onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void){
|
||||
LogUtil.log("displayRetryholder")
|
||||
if ((typeof (this.options.retryholderSrc as image.PixelMap).isEditable) == 'boolean') {
|
||||
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;
|
||||
if (typeof res.id != 'undefined' && typeof res.id != 'undefined') {
|
||||
let resourceFetch = new ParseResClient();
|
||||
let suc = (arraybuffer) => {
|
||||
let suc = (arraybuffer:ArrayBuffer) => {
|
||||
let fileTypeUtil = new FileTypeUtil();
|
||||
let typeValue = fileTypeUtil.getFileType(arraybuffer);
|
||||
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 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) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
onComplete(imageKnifeData)
|
||||
}).catch(err => {
|
||||
}).catch( (err:BusinessError) => {
|
||||
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 success = (value: PixelMap) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
|
|
|
@ -14,5 +14,5 @@
|
|||
*/
|
||||
|
||||
export interface AsyncCallback<T> {
|
||||
(err: string, data: T): boolean;
|
||||
callback:(err: string, data: T)=>boolean;
|
||||
}
|
||||
|
|
|
@ -14,5 +14,5 @@
|
|||
*/
|
||||
|
||||
export interface AsyncSuccess<T> {
|
||||
(data: T);
|
||||
asyncSuccess:(data: T)=>void;
|
||||
}
|
||||
|
|
|
@ -14,5 +14,5 @@
|
|||
*/
|
||||
|
||||
export interface DataCallBack<T> {
|
||||
callback(data: T);
|
||||
callback:(data: T)=>void;
|
||||
}
|
|
@ -14,24 +14,24 @@
|
|||
*/
|
||||
|
||||
import {ImageKnifeData} from "../../imageknife/ImageKnifeData"
|
||||
|
||||
export class AllCacheInfo {
|
||||
memoryCacheInfo: {
|
||||
key: string,
|
||||
data: ImageKnifeData
|
||||
}
|
||||
|
||||
resourceCacheInfo: {
|
||||
path: string,
|
||||
key: string
|
||||
}
|
||||
|
||||
dataCacheInfo: {
|
||||
path: string,
|
||||
key: string
|
||||
}
|
||||
export interface MemoryCacheInfo{
|
||||
key: string,
|
||||
data: ImageKnifeData | undefined
|
||||
}
|
||||
export interface ResourceCacheInfo{
|
||||
path: string,
|
||||
key: string
|
||||
}
|
||||
export interface DataCacheInfo{
|
||||
path: string,
|
||||
key: string
|
||||
}
|
||||
export interface AllCacheInfo {
|
||||
memoryCacheInfo: MemoryCacheInfo | undefined
|
||||
resourceCacheInfo: ResourceCacheInfo | undefined
|
||||
dataCacheInfo: DataCacheInfo | undefined
|
||||
}
|
||||
|
||||
export interface IAllCacheInfoCallback {
|
||||
(cacheInfo: AllCacheInfo);
|
||||
callback :(cacheInfo: AllCacheInfo)=>void;
|
||||
}
|
|
@ -12,8 +12,8 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export interface IParseImage {
|
||||
parseImage(imageinfo:ArrayBuffer, onCompleteFunction, onErrorFunction);
|
||||
parseImageThumbnail(scale:number, imageinfo:ArrayBuffer, onCompleteFunction, onErrorFunction);
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export interface IParseImage<T> {
|
||||
parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
|
||||
parseImageThumbnail:(scale:number, imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
|
||||
}
|
|
@ -13,12 +13,14 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { RequestOption } from '../RequestOption'
|
||||
import { NetworkDownloadClient } from './NetworkDownloadClient'
|
||||
import { LoadLocalFileClient } from './LoadLocalFileClient'
|
||||
import { LoadDataShareFileClient } from './LoadDataShareFileClient'
|
||||
import loadRequest from '@ohos.request';
|
||||
import { ImageKnifeGlobal } from '../ImageKnifeGlobal'
|
||||
import common from '@ohos.app.ability.common'
|
||||
|
||||
// 数据加载器
|
||||
export class DownloadClient implements IDataFetch {
|
||||
|
@ -26,10 +28,13 @@ export class DownloadClient implements IDataFetch {
|
|||
private localFileClient = new LoadLocalFileClient();
|
||||
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 (request.loadSrc.startsWith(globalThis.ImageKnife.getImageKnifeContext()
|
||||
.filesDir) || request.loadSrc.startsWith(globalThis.ImageKnife.getImageKnifeContext().cacheDir)) {
|
||||
let fileDir:string = (ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).filesDir as string;
|
||||
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)
|
||||
} else if (request.loadSrc.startsWith('datashare://') || request.loadSrc.startsWith('file://')) {
|
||||
|
|
|
@ -17,5 +17,5 @@ import { RequestOption } from '../RequestOption'
|
|||
|
||||
// 资源加载接口
|
||||
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;
|
||||
}
|
|
@ -12,10 +12,10 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import type { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { RequestOption } from '../RequestOption'
|
||||
import fs from '@ohos.file.fs';
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
|
||||
export class LoadDataShareFileClient implements IDataFetch {
|
||||
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) => {
|
||||
onComplete(buf);
|
||||
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)
|
||||
})
|
||||
}).catch(err => {
|
||||
}).catch((err:BusinessError) => {
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
|
|
@ -13,10 +13,10 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { RequestOption } from '../RequestOption'
|
||||
import { FileUtils } from '../../cache/FileUtils'
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export class LoadLocalFileClient implements IDataFetch {
|
||||
loadData(request: RequestOption, onComplete: (img: ArrayBuffer) => void, onError: (err: string) => void) {
|
||||
if (typeof request.loadSrc == 'string') {
|
||||
|
@ -26,7 +26,7 @@ export class LoadLocalFileClient implements IDataFetch {
|
|||
} else {
|
||||
onComplete(fileBuffer);
|
||||
}
|
||||
}).catch(err=>{
|
||||
}).catch((err:BusinessError)=>{
|
||||
onError('LoadLocalFileClient loadLocalFileData Error Msg ='+err?.message)
|
||||
})
|
||||
|
||||
|
|
|
@ -13,13 +13,15 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { IDataFetch } from '../networkmanage/IDataFetch'
|
||||
import { RequestOption } from '../RequestOption'
|
||||
import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5'
|
||||
import { FileUtils } from '../../cache/FileUtils'
|
||||
import loadRequest from '@ohos.request';
|
||||
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 {
|
||||
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)) {
|
||||
FileUtils.getInstance().deleteFile(allpath)
|
||||
}
|
||||
var downloadConfig = {
|
||||
let downloadConfig:loadRequest.DownloadConfig = {
|
||||
url: (request.loadSrc as string),
|
||||
filePath: allpath,
|
||||
// 允许计费流量下载
|
||||
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) {
|
||||
loadTask = downloadTask;
|
||||
let loadTask:loadRequest.DownloadTask | null = downloadTask;
|
||||
|
||||
loadTask.on('progress', (receivedSize, totalSize) => {
|
||||
if (totalSize > 0) {
|
||||
// 并不是所有服务器都会返回totalSize 当没有文件大小的时候,下载进度没有百分比回调,只能知道目前下载了多少数据量
|
||||
let percent = Math.round(((receivedSize * 1.0) / (totalSize * 1.0)) * 100)
|
||||
if (request.progressFunc) {
|
||||
request.progressFunc(percent);
|
||||
request.progressFunc.asyncSuccess(percent);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@ -62,69 +64,50 @@ export class NetworkDownloadClient implements IDataFetch {
|
|||
onComplete(arraybuffer);
|
||||
FileUtils.getInstance().deleteFileAsync(downloadPath).then(()=>{
|
||||
LogUtil.log('文件名:'+downloadPath+" 文件删除成功!")
|
||||
}).catch(err=>{
|
||||
}).catch((err:BusinessError)=>{
|
||||
LogUtil.log('文件名:'+downloadPath+" 文件删除失败!")
|
||||
});
|
||||
}).catch(err=>{
|
||||
onError('NetworkDownloadClient Read File Async Error Msg='+ err?.message)
|
||||
}).catch((err:BusinessError)=>{
|
||||
onError('NetworkDownloadClient Read File Async Error Msg='+ (err as BusinessError)?.message)
|
||||
})
|
||||
|
||||
|
||||
loadTask.off('complete', () => {
|
||||
|
||||
})
|
||||
|
||||
loadTask.off('pause', () => {
|
||||
})
|
||||
|
||||
loadTask.off('remove', () => {
|
||||
})
|
||||
|
||||
loadTask.off('progress', () => {
|
||||
})
|
||||
|
||||
loadTask.off('fail', () => {
|
||||
})
|
||||
loadTask = null;
|
||||
if(loadTask != null) {
|
||||
loadTask.off('complete', () => {})
|
||||
loadTask.off('pause', () => {})
|
||||
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) => {
|
||||
onError('NetworkDownloadClient Download task fail err =' + err)
|
||||
if (loadTask) {
|
||||
loadTask.remove().then(result => {
|
||||
loadTask.off('complete', () => {
|
||||
})
|
||||
|
||||
loadTask.off('pause', () => {
|
||||
})
|
||||
|
||||
loadTask.off('remove', () => {
|
||||
})
|
||||
|
||||
loadTask.off('progress', () => {
|
||||
})
|
||||
|
||||
loadTask.off('fail', () => {
|
||||
})
|
||||
loadTask = null
|
||||
}).catch(err => {
|
||||
if (loadTask!=null) {
|
||||
loadTask.delete().then(result => {
|
||||
if(loadTask != undefined) {
|
||||
loadTask.off('complete', () => {})
|
||||
loadTask.off('pause', () => {})
|
||||
loadTask.off('remove', () => {})
|
||||
loadTask.off('progress', () => {})
|
||||
loadTask.off('fail', () => {})
|
||||
loadTask = null
|
||||
}
|
||||
}).catch((err:BusinessError) => {
|
||||
loadTask = null;
|
||||
console.log('NetworkDownloadClient Download task fail err =' + err);
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
} else {
|
||||
onError('NetworkDownloadClient downloadTask dismiss!')
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
.catch((err:BusinessError)=> {
|
||||
onError("下载子系统download错误捕获,error=" + err.message);
|
||||
})
|
||||
}
|
||||
|
|
|
@ -14,5 +14,5 @@
|
|||
*/
|
||||
|
||||
export interface PngCallback<R,T>{
|
||||
(sender:R, receover:T)
|
||||
pngCallback: (sender:R, receover:T)=>void
|
||||
}
|
|
@ -12,16 +12,16 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import {Closeable} from "/imageknife/pngj/io/Closeable"
|
||||
import {ImageInfo} from "/imageknife/pngj/entry/ImageInfo"
|
||||
import {Closeable} from "./io/Closeable"
|
||||
import {ImageInfo} from "./entry/ImageInfo"
|
||||
|
||||
export class PngReader implements Closeable {
|
||||
private static LOG_TAG: string= "PngReader";
|
||||
private static MAX_TOTAL_BYTES_READ_DEFAULT: number= 901001001;
|
||||
private static MAX_BYTES_METADATA_DEFAULT: number= 5024024;
|
||||
private static MAX_CHUNK_SIZE_SKIP: number= 2024024;
|
||||
public imgInfo: ImageInfo;
|
||||
public interlaced: boolean;
|
||||
public imgInfo: ImageInfo = new ImageInfo(0,0,0,false,false,false);
|
||||
public interlaced: boolean = false;
|
||||
|
||||
constructor(shouldCloseStream: boolean) {
|
||||
|
||||
|
|
|
@ -13,20 +13,20 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
import {UPNG} from '../../3rd_party/upng/UPNG';
|
||||
import {PngCallback} from '../pngj/PngCallback';
|
||||
import {PngCallback} from './PngCallback';
|
||||
import image from '@ohos.multimedia.image';
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import ArkWorker from '@ohos.worker'
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export class Pngj {
|
||||
readPngImageInfo(arraybuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>) {
|
||||
let imageSource = image.createImageSource(arraybuffer as any);
|
||||
readPngImageInfo(arraybuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, image.ImageInfo>) {
|
||||
let imageSource:image.ImageSource = image.createImageSource(arraybuffer);
|
||||
if (imageSource != undefined){
|
||||
imageSource.getImageInfo((err, value) => {
|
||||
imageSource.getImageInfo((err:BusinessError, value:image.ImageInfo) => {
|
||||
if (err) {
|
||||
return;
|
||||
}
|
||||
callback(arraybuffer, value);
|
||||
callback.pngCallback(arraybuffer, value);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -47,19 +47,19 @@ export class Pngj {
|
|||
*/
|
||||
readPngImage(pngBuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>) {
|
||||
var png = UPNG.decode(pngBuffer);
|
||||
callback(pngBuffer, png)
|
||||
callback.pngCallback(pngBuffer, png)
|
||||
}
|
||||
|
||||
writePngWithString(addInfo:string, pngBuffer: ArrayBuffer,callback:PngCallback<ArrayBuffer, any>) {
|
||||
var pngDecode = UPNG.decode(pngBuffer);
|
||||
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>) {
|
||||
var pngDecode = UPNG.decode(pngBuffer);
|
||||
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>) {
|
||||
|
@ -79,7 +79,7 @@ export class Pngj {
|
|||
var data = e.data;
|
||||
switch (data.type) {
|
||||
case 'readPngImageAsync':
|
||||
callback(data.receiver, data.data)
|
||||
callback.pngCallback(data.receiver, data.data)
|
||||
break;
|
||||
default:
|
||||
break
|
||||
|
@ -107,7 +107,7 @@ export class Pngj {
|
|||
var data = e.data;
|
||||
switch (data.type) {
|
||||
case 'writePngWithStringAsync':
|
||||
callback(data.receiver, data.data)
|
||||
callback.pngCallback(data.receiver, data.data)
|
||||
break;
|
||||
default:
|
||||
break
|
||||
|
@ -137,7 +137,7 @@ export class Pngj {
|
|||
var data = e.data;
|
||||
switch (data.type) {
|
||||
case 'writePngAsync':
|
||||
callback(data.receiver, data.data)
|
||||
callback.pngCallback(data.receiver, data.data)
|
||||
break;
|
||||
default:
|
||||
break
|
|
@ -162,7 +162,7 @@ export class ImageInfo {
|
|||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
var other = obj;
|
||||
let other = obj;
|
||||
if (this.alpha != other.alpha)
|
||||
return false;
|
||||
if (this.bitDepth != other.bitDepth)
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type { ICache } from "../requestmanage/ICache"
|
||||
import { ICache } from "../requestmanage/ICache"
|
||||
import { DiskLruCache } from "@ohos/disklrucache"
|
||||
|
||||
export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
|
||||
|
@ -47,7 +47,7 @@ export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
|
|||
|
||||
removeValue(key: string): ArrayBuffer{
|
||||
// Disk暂无实现
|
||||
return;
|
||||
return new ArrayBuffer(0);
|
||||
}
|
||||
|
||||
clear() {
|
||||
|
|
|
@ -18,11 +18,11 @@ export interface ICache<K, V> {
|
|||
// 缓存类型
|
||||
getName(): string
|
||||
|
||||
getValue(key: K): V;
|
||||
getValue(key: K): V|undefined;
|
||||
|
||||
putValue(key: K, value: V);
|
||||
|
||||
removeValue(key: K): V;
|
||||
removeValue(key: K): V|undefined;
|
||||
|
||||
clear();
|
||||
|
||||
|
|
|
@ -13,7 +13,7 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type {ICache} from "../requestmanage/ICache"
|
||||
import {ICache} from "../requestmanage/ICache"
|
||||
import {LruCache} from "../../cache/LruCache"
|
||||
|
||||
export class MemoryCacheProxy <K, V> implements ICache<K, V> {
|
||||
|
@ -28,7 +28,7 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
|
|||
return "Level1MemoryCache"
|
||||
}
|
||||
|
||||
getValue(key: K): V{
|
||||
getValue(key: K): V|undefined{
|
||||
return this.mLruCache.get(key);
|
||||
}
|
||||
|
||||
|
@ -36,7 +36,7 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
|
|||
this.mLruCache.put(key, value);
|
||||
}
|
||||
|
||||
removeValue(key: K): V{
|
||||
removeValue(key: K): V|undefined{
|
||||
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) {
|
||||
return null;
|
||||
|
|
|
@ -13,28 +13,26 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { RequestOption } from '../../imageknife/RequestOption'
|
||||
import { RequestOption,Size } from '../../imageknife/RequestOption'
|
||||
import { DiskLruCache } from '@ohos/disklrucache'
|
||||
import { LruCache } from '../../cache/LruCache'
|
||||
import { SparkMD5 } from '../../3rd_party/sparkmd5/spark-md5'
|
||||
import { MemoryCacheProxy } from '../requestmanage/MemoryCacheProxy'
|
||||
import { DiskCacheProxy } from '../requestmanage/DiskCacheProxy'
|
||||
import { FileTypeUtil } from '../utils/FileTypeUtil'
|
||||
import type { IDataFetch } from '../../imageknife/networkmanage/IDataFetch'
|
||||
import type { IResourceFetch } from '../../imageknife/resourcemanage/IResourceFetch'
|
||||
import { IDataFetch } from '../../imageknife/networkmanage/IDataFetch'
|
||||
import { IResourceFetch } from '../../imageknife/resourcemanage/IResourceFetch'
|
||||
import { ImageKnifeData, ImageKnifeType } from '../ImageKnifeData'
|
||||
import { AllCacheInfo } from '../../imageknife/interface/IAllCacheInfoCallback'
|
||||
import { ParseImageUtil } from '../utils/ParseImageUtil'
|
||||
import type { IParseImage } from '../interface/IParseImage'
|
||||
import { IParseImage } from '../interface/IParseImage'
|
||||
import image from '@ohos.multimedia.image'
|
||||
import { SVGParseImpl } from '../utils/svg/SVGParseImpl'
|
||||
import { GIFParseImpl } from '../utils/gif/GIFParseImpl'
|
||||
import { GIFFrame } from '../utils/gif/GIFFrame'
|
||||
import { LogUtil } from '../../imageknife/utils/LogUtil'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
|
||||
export interface AsyncString {
|
||||
(data: string): void;
|
||||
}
|
||||
|
||||
export enum Stage {
|
||||
|
||||
|
@ -64,13 +62,13 @@ export enum RunReason {
|
|||
export class RequestManager {
|
||||
private TAG: string = "RequestManager";
|
||||
private options: RequestOption;
|
||||
private mMemoryCacheProxy: MemoryCacheProxy<string, any>;
|
||||
private mMemoryCacheProxy: MemoryCacheProxy<string, ImageKnifeData>;
|
||||
private mDiskCacheProxy: DiskCacheProxy;
|
||||
private mIDataFetch: IDataFetch;
|
||||
private mIResourceFetch: IResourceFetch;
|
||||
private mParseImageUtil: IParseImage;
|
||||
private mIResourceFetch: IResourceFetch<ArrayBuffer>;
|
||||
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;
|
||||
|
||||
// 缓存部分
|
||||
|
@ -87,23 +85,27 @@ export class RequestManager {
|
|||
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")
|
||||
let manager = new RequestManager(option, memoryCache1, diskMemoryCache1, dataFetch, resourceFetch);
|
||||
return new Promise<PixelMap>(manager.process.bind(manager))
|
||||
.then(option.loadComplete.bind(option))
|
||||
.then(manager.loadCompleteAfter.bind(manager))
|
||||
.catch(option.loadError.bind(option));
|
||||
return new Promise<ImageKnifeData>(manager.process)
|
||||
.then(option.loadComplete)
|
||||
.then(manager.loadCompleteAfter)
|
||||
.catch(option.loadError);
|
||||
}
|
||||
|
||||
loadCompleteAfter() {
|
||||
loadCompleteAfter =()=>{
|
||||
try { // 内部消化问题
|
||||
LogUtil.log("loadCompleteAfter!")
|
||||
if (this.options.allCacheInfoCallback) {
|
||||
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);
|
||||
allCacheInfo.memoryCacheInfo = {
|
||||
key: this.options.generateCacheKey,
|
||||
|
@ -121,7 +123,7 @@ export class RequestManager {
|
|||
key: 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) {
|
||||
LogUtil.log("after err =" + err)
|
||||
|
@ -133,12 +135,12 @@ export class RequestManager {
|
|||
private mStage: Stage = Stage.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 !");
|
||||
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")
|
||||
if (runReason == RunReason.INITIALIZE) {
|
||||
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")
|
||||
if (current == Stage.RESOURCE_CACHE) {
|
||||
this.loadDiskFromTransform(request, onComplete, onError);
|
||||
|
@ -185,8 +187,8 @@ export class RequestManager {
|
|||
}
|
||||
|
||||
// 加载网络资源
|
||||
private loadSourceFromNetwork(request: RequestOption, onComplete, onError) {
|
||||
let success = (arraybuffer) => {
|
||||
private loadSourceFromNetwork(request: RequestOption, onComplete:(value:ImageKnifeData)=>void|PromiseLike<ImageKnifeData>, onError:(reason?:BusinessError|string)=>void) {
|
||||
let success = (arraybuffer:ArrayBuffer) => {
|
||||
this.downloadSuccess(arraybuffer, onComplete, onError)
|
||||
}
|
||||
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")
|
||||
// 本地解析后进行一级缓存
|
||||
let success = (arrayBuffer) => {
|
||||
let success = (arrayBuffer:ArrayBuffer) => {
|
||||
// 使用媒体子系统 ImageSource解析文件 获取PixelMap
|
||||
let fileTypeUtil = new FileTypeUtil();
|
||||
let typeValue = fileTypeUtil.getFileType(arrayBuffer)
|
||||
|
@ -217,7 +219,7 @@ export class RequestManager {
|
|||
})
|
||||
} else {
|
||||
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
|
||||
if (pixelMap) {
|
||||
|
||||
|
@ -227,7 +229,7 @@ export class RequestManager {
|
|||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
}
|
||||
else {
|
||||
let success = (value: PixelMap) => {
|
||||
|
@ -242,7 +244,7 @@ export class RequestManager {
|
|||
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")
|
||||
let cached = this.mDiskCacheProxy.getValue(request.generateDataKey)
|
||||
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")
|
||||
let cached = this.mDiskCacheProxy.getValue(request.generateResourceKey)
|
||||
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")
|
||||
if ((typeof (request.loadSrc as image.PixelMap).isEditable) == 'boolean') {
|
||||
// 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")
|
||||
// 一级缓存 内存获取
|
||||
let cache = this.mMemoryCacheProxy.loadMemoryCache(this.options.generateCacheKey, this.options.isCacheable);
|
||||
|
@ -297,7 +299,7 @@ export class RequestManager {
|
|||
}
|
||||
|
||||
// 解析磁盘文件变成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组件
|
||||
let fileTypeUtil = new FileTypeUtil();
|
||||
let typeValue = fileTypeUtil.getFileType(source);
|
||||
|
@ -314,23 +316,23 @@ export class RequestManager {
|
|||
} else {
|
||||
if (this.options.transformations[0]) {
|
||||
if (this.options.thumbSizeMultiplier) {
|
||||
let thumbOption = new RequestOption();
|
||||
let thumbOption:RequestOption = new RequestOption();
|
||||
thumbOption.setImageViewSize({
|
||||
width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width),
|
||||
height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height)
|
||||
})
|
||||
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options);
|
||||
let thumbError = this.options.thumbholderOnError.bind(this.options);
|
||||
this.options.transformations[0].transform(source, thumbOption, (error, pixelMap: PixelMap) => {
|
||||
let thumbCallback = this.options.thumbholderOnComplete;
|
||||
let thumbError = this.options.thumbholderOnError;
|
||||
this.options.transformations[0].transform(source, thumbOption,{asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
|
||||
if (pixelMap) {
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
|
||||
thumbCallback(imageKnifeData);
|
||||
} else {
|
||||
thumbError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
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) {
|
||||
// 保存一份变换后的图片PixelMap到MemoryCache
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
|
||||
|
@ -339,11 +341,11 @@ export class RequestManager {
|
|||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
},this.options.thumbDelayTime);
|
||||
}
|
||||
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) {
|
||||
// 保存一份变换后的图片PixelMap到MemoryCache
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
|
||||
|
@ -352,13 +354,13 @@ export class RequestManager {
|
|||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
}
|
||||
} else {
|
||||
// thumbnail 缩略图部分
|
||||
if (request.thumbSizeMultiplier) {
|
||||
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options);
|
||||
let thumbError = this.options.thumbholderOnError.bind(this.options);
|
||||
let thumbCallback = this.options.thumbholderOnComplete
|
||||
let thumbError = this.options.thumbholderOnError
|
||||
let thumbSuccess = (value: PixelMap) => {
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
|
||||
thumbCallback(imageKnifeData);
|
||||
|
@ -386,13 +388,13 @@ export class RequestManager {
|
|||
}
|
||||
|
||||
// 解析磁盘变换后文件变成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 typeValue = fileTypeUtil.getFileType(source);
|
||||
// thumbnail 缩略图部分
|
||||
if (request.thumbSizeMultiplier) {
|
||||
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options);
|
||||
let thumbError = this.options.thumbholderOnError.bind(this.options);
|
||||
let thumbCallback = this.options.thumbholderOnComplete
|
||||
let thumbError = this.options.thumbholderOnError
|
||||
let thumbSuccess = (value: PixelMap) => {
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
|
||||
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.');
|
||||
|
||||
if(source == null || source == undefined || source.byteLength <= 0){
|
||||
|
@ -447,8 +449,8 @@ export class RequestManager {
|
|||
.then(async (arraybuffer: ArrayBuffer)=>{
|
||||
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
|
||||
})
|
||||
.catch(err=>{
|
||||
LogUtil.log('download file is ='+ImageKnifeData.GIF+'and save diskLruCache error ='+ err)
|
||||
.catch( (err:BusinessError)=>{
|
||||
LogUtil.log('download file is ='+ImageKnifeData.GIF+'and save diskLruCache error ='+ (err as BusinessError))
|
||||
})
|
||||
}else if(ImageKnifeData.SVG == filetype){
|
||||
// 处理svg
|
||||
|
@ -461,8 +463,8 @@ export class RequestManager {
|
|||
.then(async (arraybuffer: ArrayBuffer)=>{
|
||||
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
|
||||
})
|
||||
.catch(err=>{
|
||||
LogUtil.log('download file is ='+ImageKnifeData.SVG+'and save diskLruCache error ='+ err)
|
||||
.catch((err:BusinessError)=>{
|
||||
LogUtil.log('download file is ='+ImageKnifeData.SVG+'and save diskLruCache error ='+ (err as BusinessError))
|
||||
})
|
||||
} else {
|
||||
// 进行变换
|
||||
|
@ -471,19 +473,19 @@ export class RequestManager {
|
|||
if (this.options.thumbSizeMultiplier) {
|
||||
this.thumbnailProcess(source, filetype, onComplete, onError);
|
||||
} 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) {
|
||||
this.saveCacheAndDisk(pixelMap, filetype, onComplete, source);
|
||||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
}
|
||||
} else {
|
||||
// thumbnail 缩略图部分
|
||||
if (this.options.thumbSizeMultiplier) {
|
||||
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options);
|
||||
let thumbError = this.options.thumbholderOnError.bind(this.options);
|
||||
let thumbCallback = this.options.thumbholderOnComplete
|
||||
let thumbError = this.options.thumbholderOnError
|
||||
let thumbSuccess = (value: PixelMap) => {
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, value);
|
||||
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);
|
||||
this.mMemoryCacheProxy.putValue(this.options.generateCacheKey, imageKnifeData);
|
||||
let save2DiskCache = async (arraybuffer) => {
|
||||
let save2DiskCache = async (arraybuffer:ArrayBuffer) => {
|
||||
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
|
||||
// 落盘之后需要主动移除当前request并且调用下一个加载
|
||||
let removeCurrentAndSearchNextRun = this.options.removeCurrentAndSearchNext.bind(this.options)
|
||||
let removeCurrentAndSearchNextRun = this.options.removeCurrentAndSearchNext
|
||||
removeCurrentAndSearchNextRun();
|
||||
}
|
||||
let runSave2Disk = (resolve, reject) => {
|
||||
let runSave2Disk = (resolve:(value:ArrayBuffer)=>void|PromiseLike<ArrayBuffer>, reject:(reason?:BusinessError|string)=>void) => {
|
||||
resolve(source);
|
||||
}
|
||||
let promise = new Promise(runSave2Disk);
|
||||
|
@ -533,49 +535,49 @@ export class RequestManager {
|
|||
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();
|
||||
thumbOption.setImageViewSize({
|
||||
width: Math.round(this.options.thumbSizeMultiplier * this.options.size.width),
|
||||
height: Math.round(this.options.thumbSizeMultiplier * this.options.size.height)
|
||||
})
|
||||
let thumbCallback = this.options.thumbholderOnComplete.bind(this.options);
|
||||
let thumbError = this.options.thumbholderOnError.bind(this.options);
|
||||
this.options.transformations[0].transform(source, thumbOption, (error, pixelMap: PixelMap) => {
|
||||
let thumbCallback = this.options.thumbholderOnComplete
|
||||
let thumbError = this.options.thumbholderOnError
|
||||
this.options.transformations[0].transform(source, thumbOption, {asyncTransform: (error:BusinessError|string, pixelMap: PixelMap|null) => {
|
||||
if (pixelMap) {
|
||||
let imageKnifeData = this.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap);
|
||||
thumbCallback(imageKnifeData);
|
||||
} else {
|
||||
thumbError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
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) {
|
||||
this.saveCacheAndDisk(pixelMap, filetype, onComplete, source);
|
||||
} else {
|
||||
onError(error);
|
||||
}
|
||||
})
|
||||
}})
|
||||
}, 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 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) => {
|
||||
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, value)
|
||||
if(cacheStrategy){
|
||||
cacheStrategy(imageKnifeData)
|
||||
}
|
||||
onComplete(imageKnifeData)
|
||||
}).catch(err => {
|
||||
}).catch((err:BusinessError) => {
|
||||
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()
|
||||
gifParseImpl.parseGifs(arraybuffer, (data?,err?)=>{
|
||||
gifParseImpl.parseGifs(arraybuffer, (data?:GIFFrame[],err?:BusinessError|string)=>{
|
||||
if(err){
|
||||
onError(err)
|
||||
}
|
||||
|
|
|
@ -13,9 +13,8 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import {RequestOption} from "../RequestOption"
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
// 本地资源解析抽象接口
|
||||
export interface IResourceFetch {
|
||||
loadResource(res: Resource, onCompleteFunction, onErrorFunction);
|
||||
export interface IResourceFetch<T> {
|
||||
loadResource:(res: Resource, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
|
||||
}
|
|
@ -13,23 +13,24 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type {IResourceFetch} from '../resourcemanage/IResourceFetch'
|
||||
import {IResourceFetch} from '../resourcemanage/IResourceFetch'
|
||||
import {ResourceTypeEts} from '../../imageknife/constants/ResourceTypeEts'
|
||||
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
|
||||
export class ParseResClient implements IResourceFetch {
|
||||
loadResource(res: Resource, onCompleteFunction, onErrorFunction) {
|
||||
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
|
||||
import { BusinessError } from '@ohos.base'
|
||||
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 resType = res.type;
|
||||
if (resType == ResourceTypeEts.MEDIA) {
|
||||
globalThis.ImageKnife.getImageKnifeContext().resourceManager
|
||||
.getMedia(resId)
|
||||
((ImageKnifeGlobal.getInstance().getHapContext() as common.UIAbilityContext).resourceManager as resourceManager.ResourceManager)
|
||||
.getMediaContent(resId)
|
||||
.then(data => {
|
||||
let arrayBuffer = this.typedArrayToBuffer(data);
|
||||
onCompleteFunction(arrayBuffer)
|
||||
})
|
||||
.catch(err => {
|
||||
.catch( (err:BusinessError) => {
|
||||
onErrorFunction(err)
|
||||
})
|
||||
}
|
||||
|
|
|
@ -13,30 +13,32 @@
|
|||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import type {IResourceFetch} from '../resourcemanage/IResourceFetch'
|
||||
import {ResourceTypeEts} from '../../imageknife/constants/ResourceTypeEts'
|
||||
import {Base64} from '../../cache/Base64'
|
||||
|
||||
import { IResourceFetch } from '../resourcemanage/IResourceFetch'
|
||||
import { ResourceTypeEts } from '../../imageknife/constants/ResourceTypeEts'
|
||||
import { Base64 } from '../../cache/Base64'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import resourceManager from '@ohos.resourceManager';
|
||||
import { ImageKnifeGlobal } from '../ImageKnifeGlobal';
|
||||
|
||||
export class ParseResClientBase64 implements IResourceFetch {
|
||||
loadResource(res: Resource, onCompleteFunction, onErrorFunction) {
|
||||
export class ParseResClientBase64 implements IResourceFetch<ArrayBuffer> {
|
||||
loadResource(res: Resource, onCompleteFunction: (value: ArrayBuffer) => void | PromiseLike<ArrayBuffer>, onErrorFunction: (reason?: BusinessError | string) => void) {
|
||||
let resId = res.id;
|
||||
let resType = res.type;
|
||||
if (resType == ResourceTypeEts.MEDIA) {
|
||||
globalThis.ImageKnife.getImageKnifeContext().resourceManager
|
||||
.getMediaBase64(resId)
|
||||
((ImageKnifeGlobal.getInstance()
|
||||
.getHapContext() as Record<string, Object>).resourceManager as resourceManager.ResourceManager)
|
||||
.getMediaContentBase64(resId)
|
||||
.then(data => {
|
||||
let matchReg = ';base64,';
|
||||
var firstIndex = data.indexOf(matchReg)
|
||||
let firstIndex = data.indexOf(matchReg)
|
||||
data = data.substring(firstIndex + matchReg.length, data.length)
|
||||
let arrayBuffer = Base64.getInstance()
|
||||
.decode(data);
|
||||
onCompleteFunction(arrayBuffer)
|
||||
})
|
||||
.catch(err => {
|
||||
.catch((err: BusinessError) => {
|
||||
onErrorFunction(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
else if (resType == ResourceTypeEts.RAWFILE) {
|
||||
onErrorFunction('ParseResClientBase64 本地资源是rawfile暂时无法解析出错')
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
export interface AsyncTransform<T> {
|
||||
(err, data: T)
|
||||
asyncTransform:(err:BusinessError|string, data: T | null)=>void
|
||||
}
|
||||
|
|
|
@ -21,7 +21,8 @@ import { TransformUtils } from "../transform/TransformUtils"
|
|||
import image from "@ohos.multimedia.image"
|
||||
import { fastBlur } from "../utils/FastBlur"
|
||||
import {LogUtil} from '../../imageknife/utils/LogUtil'
|
||||
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import {Size} from '../../imageknife/RequestOption'
|
||||
|
||||
export class BlurTransformation implements BaseTransform<PixelMap> {
|
||||
private _mRadius: number;
|
||||
|
@ -38,23 +39,20 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
|
|||
if (!buf || buf.byteLength <= 0) {
|
||||
LogUtil.log(Constants.PROJECT_TAG + ";BlurTransformation buf is empty");
|
||||
if (func) {
|
||||
func(Constants.PROJECT_TAG + ";BlurTransformation buf is empty", null);
|
||||
func?.asyncTransform(Constants.PROJECT_TAG + ";BlurTransformation buf is empty", null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var imageSource = image.createImageSource(buf as any);
|
||||
TransformUtils.getPixelMapSize(imageSource, (error, size: {
|
||||
width: number,
|
||||
height: number
|
||||
}) => {
|
||||
let imageSource:image.ImageSource = image.createImageSource(buf);
|
||||
TransformUtils.getPixelMapSize(imageSource, {asyncTransform:(error:BusinessError|string, size: Size|null) => {
|
||||
if (!size) {
|
||||
func(error, null)
|
||||
func?.asyncTransform(error, null)
|
||||
return;
|
||||
}
|
||||
var pixelMapWidth = size.width;
|
||||
var pixelMapHeight = size.height;
|
||||
var targetWidth = request.size.width;
|
||||
var targetHeight = request.size.height;
|
||||
let pixelMapWidth = size.width;
|
||||
let pixelMapHeight = size.height;
|
||||
let targetWidth = request.size.width;
|
||||
let targetHeight = request.size.height;
|
||||
if (pixelMapWidth < targetWidth) {
|
||||
targetWidth = pixelMapWidth;
|
||||
}
|
||||
|
@ -62,7 +60,7 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
|
|||
targetHeight = pixelMapHeight;
|
||||
}
|
||||
|
||||
var options = {
|
||||
let options:image.DecodingOptions = {
|
||||
editable: true,
|
||||
desiredSize: {
|
||||
width: targetWidth,
|
||||
|
@ -77,10 +75,10 @@ export class BlurTransformation implements BaseTransform<PixelMap> {
|
|||
fastBlur.blur(data, this._mRadius, true, func);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
.catch((e:BusinessError) => {
|
||||
LogUtil.log(Constants.PROJECT_TAG + ";error:" + e);
|
||||
func(e, null);
|
||||
func?.asyncTransform(e, null);
|
||||
})
|
||||
})
|
||||
}})
|
||||
}
|
||||
}
|
|
@ -20,6 +20,8 @@ import { RequestOption } from "../../imageknife/RequestOption"
|
|||
import { LogUtil } from '../../imageknife/utils/LogUtil'
|
||||
import image from "@ohos.multimedia.image"
|
||||
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
|
||||
|
@ -38,27 +40,27 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
|
|||
async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) {
|
||||
if (!buf || buf.byteLength <= 0) {
|
||||
LogUtil.log(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty");
|
||||
if (func) {
|
||||
func(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty", null);
|
||||
if (func != undefined) {
|
||||
func?.asyncTransform(Constants.PROJECT_TAG + ";GrayscaleTransformation buf is empty", null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var imageSource = image.createImageSource(buf as any);
|
||||
let imageSource:image.ImageSource = image.createImageSource(buf);
|
||||
|
||||
let imageInfo = await imageSource.getImageInfo();
|
||||
let size = {
|
||||
let imageInfo:image.ImageInfo = await imageSource.getImageInfo();
|
||||
let size:Size = {
|
||||
width: imageInfo.size.width,
|
||||
height: imageInfo.size.height
|
||||
}
|
||||
|
||||
if (!size) {
|
||||
func(new Error("GrayscaleTransformation The image size does not exist."), null)
|
||||
func?.asyncTransform("GrayscaleTransformation The image size does not exist.", null)
|
||||
return;
|
||||
}
|
||||
var pixelMapWidth = size.width;
|
||||
var pixelMapHeight = size.height;
|
||||
var targetWidth = request.size.width;
|
||||
var targetHeight = request.size.height;
|
||||
let pixelMapWidth:number = size.width;
|
||||
let pixelMapHeight:number = size.height;
|
||||
let targetWidth:number = request.size.width;
|
||||
let targetHeight:number = request.size.height;
|
||||
if (pixelMapWidth < targetWidth) {
|
||||
targetWidth = pixelMapWidth;
|
||||
}
|
||||
|
@ -66,7 +68,7 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
|
|||
targetHeight = pixelMapHeight;
|
||||
}
|
||||
|
||||
var options = {
|
||||
let options:image.DecodingOptions = {
|
||||
editable: true,
|
||||
desiredSize: {
|
||||
width: targetWidth,
|
||||
|
@ -79,18 +81,18 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
|
|||
await data.readPixelsToBuffer(bufferData);
|
||||
|
||||
if (request.gpuEnabled) {
|
||||
let filter = new GPUImageBrightnessFilter();
|
||||
let filter:GPUImageBrightnessFilter = new GPUImageBrightnessFilter();
|
||||
filter.setImageData(bufferData, targetWidth, targetHeight);
|
||||
filter.setBrightness(this._mBrightness);
|
||||
let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight);
|
||||
data.writeBufferToPixels(buf);
|
||||
if (func) {
|
||||
func("success", data);
|
||||
func?.asyncTransform("success", data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var dataArray = new Uint8Array(bufferData);
|
||||
let dataArray = new Uint8Array(bufferData);
|
||||
|
||||
for (let index = 0; index < dataArray.length; index += 4) {
|
||||
dataArray[index] = this.checkVisAble(dataArray[index] * this._mBrightness + dataArray[index]);
|
||||
|
@ -102,7 +104,7 @@ export class BrightnessFilterTransformation implements BaseTransform<PixelMap> {
|
|||
await data.writeBufferToPixels(bufferData);
|
||||
|
||||
if (func) {
|
||||
func("", data);
|
||||
func?.asyncTransform("", data);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -20,6 +20,8 @@ import { RequestOption } from "../../imageknife/RequestOption"
|
|||
import { LogUtil } from '../../imageknife/utils/LogUtil'
|
||||
import image from "@ohos.multimedia.image"
|
||||
import { GPUImageContrastFilter } from '@ohos/gpu_transform'
|
||||
import { BusinessError } from '@ohos.base'
|
||||
import {Size} from '../../imageknife/RequestOption'
|
||||
|
||||
/**
|
||||
* 以24位色图像为例子,每种色彩都可以用0-255,
|
||||
|
@ -50,27 +52,27 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
|
|||
async transform(buf: ArrayBuffer, request: RequestOption, func?: AsyncTransform<PixelMap>) {
|
||||
if (!buf || buf.byteLength <= 0) {
|
||||
LogUtil.log(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty");
|
||||
if (func) {
|
||||
func(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty", null);
|
||||
if (func!=undefined) {
|
||||
func?.asyncTransform(Constants.PROJECT_TAG + ";ContrastFilterTransformation buf is empty", null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var imageSource = image.createImageSource(buf as any);
|
||||
let imageSource:image.ImageSource = image.createImageSource(buf);
|
||||
|
||||
let imageInfo = await imageSource.getImageInfo();
|
||||
let size = {
|
||||
let imageInfo:image.ImageInfo = await imageSource.getImageInfo();
|
||||
let size:Size = {
|
||||
width: imageInfo.size.width,
|
||||
height: imageInfo.size.height
|
||||
}
|
||||
|
||||
if (!size) {
|
||||
func(new Error("ContrastFilterTransformation The image size does not exist."), null)
|
||||
func?.asyncTransform("ContrastFilterTransformation The image size does not exist.", null)
|
||||
return;
|
||||
}
|
||||
var pixelMapWidth = size.width;
|
||||
var pixelMapHeight = size.height;
|
||||
var targetWidth = request.size.width;
|
||||
var targetHeight = request.size.height;
|
||||
let pixelMapWidth:number = size.width;
|
||||
let pixelMapHeight:number = size.height;
|
||||
let targetWidth:number = request.size.width;
|
||||
let targetHeight:number = request.size.height;
|
||||
if (pixelMapWidth < targetWidth) {
|
||||
targetWidth = pixelMapWidth;
|
||||
}
|
||||
|
@ -78,7 +80,7 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
|
|||
targetHeight = pixelMapHeight;
|
||||
}
|
||||
|
||||
var options = {
|
||||
let options:image.DecodingOptions = {
|
||||
editable: true,
|
||||
desiredSize: {
|
||||
width: targetWidth,
|
||||
|
@ -97,13 +99,13 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
|
|||
filter.setContrast(this._mContrast)
|
||||
let buf = await filter.getPixelMapBuf(0, 0, targetWidth, targetHeight);
|
||||
data.writeBufferToPixels(buf);
|
||||
if (func) {
|
||||
func("success", data);
|
||||
if (func != undefined) {
|
||||
func?.asyncTransform("success", data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var dataArray = new Uint8Array(bufferData);
|
||||
let dataArray = new Uint8Array(bufferData);
|
||||
|
||||
let brightness = 0; //亮度的偏移量,可以默认0
|
||||
for (let index = 0; index < dataArray.length; index += 4) {
|
||||
|
@ -114,8 +116,8 @@ export class ContrastFilterTransformation implements BaseTransform<PixelMap> {
|
|||
}
|
||||
|
||||
await data.writeBufferToPixels(bufferData);
|
||||
if (func) {
|
||||
func("", data);
|
||||
if (func != undefined) {
|
||||
func?.asyncTransform("", data);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue