!15 ImageKnife Project Adapter Stage Mode API9

Merge pull request !15 from 周黎生/master
This commit is contained in:
openharmony_ci 2022-07-15 09:21:17 +00:00 committed by Gitee
commit fd8bd60f36
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
120 changed files with 3209 additions and 3306 deletions

11
AppScope/app.json5 Normal file
View File

@ -0,0 +1,11 @@
{
"app": {
"bundleName": "com.openharmony.imageknife",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name",
"distributedNotificationEnabled": true
}
}

View File

@ -0,0 +1,8 @@
{
"string": [
{
"name": "app_name",
"value": "ImageKnife"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -1,3 +1,5 @@
## 1.0.3
- 适配OpenHarmony API9 Stage模型。
## 1.0.2
- 支持用户自定义扩展变换接口。

View File

@ -6,11 +6,13 @@
<filteritem type="filename" name="hvigorfile.js" desc="hvigor构建脚本DevEco Studio自动生成不手动修改"/>
<filteritem type="filename" name="*.json5" desc="hvigor配置文件DevEco Studio自动生成不手动修改"/>
<filteritem type="filepath" name="imageknife/src/main/ets/components/imageknife/pngj/UPNG.js" desc="使用开源库UPNG,使用其默认版权头,无需修改"/>
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for compatibilitylicense header policies">
<filteritem type="filename" name="hvigorfile.js" desc="hvigor构建脚本DevEco Studio自动生成不手动修改"/>
<filteritem type="filename" name="*.json5" desc="hvigor配置文件DevEco Studio自动生成不手动修改"/>
<filteritem type="filepath" name="imageknife/src/main/ets/components/imageknife/pngj/UPNG.js" desc="使用开源库UPNG,使用其默认版权头,无需修改"/>
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for copyright header policies">
</filefilter>

165
README.md
View File

@ -25,24 +25,21 @@ OpenHarmony npm环境配置等更多内容参考安装教程 [如何安装Ope
## 使用说明
1.首先初始化全局ImageKnife实例app.ets中调用ImageKnife.with()进行初始化。
1.首先初始化全局ImageKnife实例AbilityStage.ts中调用ImageKnife.with(this.context)进行初始化
```typescript
import AbilityStage from "@ohos.application.AbilityStage"
import {ImageKnife} from '@ohos/imageknife'
export default {
data: {
imageKnife: {} // ImageKnife全局占位符
},
onCreate() {
this.data.imageKnife = ImageKnife.with();// ImageKnife占位符全局初始化赋值
}
export default class MyAbilityStage extends AbilityStage {
onCreate() {
globalThis.ImageKnife = ImageKnife.with(this.context);
}
}
```
2.参考[推荐使用](###'推荐使用')或[自定义实现](###'自定义实现')
#### 推荐使用:
使用ImageKnifeOption作为入参配合自定义组件ImageKnifeComponent使用。
@ -82,7 +79,7 @@ struct Index {
```typescript
export default class PixelMapPack{
pixelMap:PixelMap;
pixelMap:PixelMap;
}
```
@ -113,7 +110,7 @@ Image(this.imageKnifePixelMapPack.pixelMap)
```typescript
//配置参数
let requestOptin = new RequestOption();
//加载本地图片
//加载本地图片
requestOptin.load($r('app.media.jpgSample'))
.addListener((err,data) => {
//加载成功/失败回调监听
@ -127,26 +124,26 @@ let requestOptin = new RequestOption();
.placeholder( $r('app.media.icon_loading'), (data)=>{
// 占位图回调监听
})
.errorholder( $r('app.media.icon_failed'), (data)=>{
.errorholder( $r('app.media.icon_failed'), (data)=>{
// 失败占位图回调监听
})
.thumbnail(0.3, (data) => {
// 缩略图加载成功回调
})
// 一定要把控件大小传给RequestOption,图片变换必须
// 一定要把控件大小传给RequestOption,图片变换必须
.setImageViewSize({width:200, height:200})
// 设置缓存策略
.diskCacheStrategy(new AUTOMATIC())
.addProgressListener((percentValue: string) => {
// 设置缓存策略
.diskCacheStrategy(new AUTOMATIC())
.addProgressListener((percentValue: string) => {
// 图片网络加载进度条百分比回调
})
.addRetryListener((error: any) => {
// 加载失败重试监听 图片加载失败时优先展示重试图层,点击重试图层,会重新进行一次加载流程
.addRetryListener((error: any) => {
// 加载失败重试监听 图片加载失败时优先展示重试图层,点击重试图层,会重新进行一次加载流程
})
// 左上圆角10pixel像素点
.roundedCorners({top:10})
// 左上圆角10pixel像素点
.roundedCorners({top:10})
// 启动加载流程,执行结果将会返回到上面的回调接口中
ImageKnife.call(requestOptin);
globalThis.ImageKnife.call(requestOptin);
```
##### 步骤4
@ -212,10 +209,12 @@ let requestOptin = new RequestOption();
| request.roundedCorners() | RoundedCornersTransformation | 圆角剪裁 |
| request.sepiaFilter() | SepiaFilterTransformation | 乌墨色滤波器 |
| request.sketchFilter() | SketchFilterTransformation | 素描滤波器 |
| request.mask() | MaskTransformation | 遮罩 |
| request.swirlFilter() | SwirlFilterTransformation | 扭曲滤波器 |
## 兼容性
支持 OpenHarmony API version 8 及以上版本。
支持 OpenHarmony API version 9 及以上版本。
## 目录结构
@ -223,69 +222,71 @@ let requestOptin = new RequestOption();
/imageknife/src/
- main/ets/components
- cache # 缓存相关内容
- diskstrategy # 缓存策略
- key # 缓存key生成策略
- Base64.ets # Base64算法
- CustomMap.ets # 自定义Map封装
- DiskCacheEntry.ets# 磁盘缓存entry
- DiskLruCache.ets # 磁盘LRU缓存策略
- FileReader.ets # 文件读取相关
- FileUtils.ets # 文件工具类
- LruCache.ets # 内存LRU缓存策略
- Md5.ets # MD5算法
- diskstrategy # 缓存策略
- key # 缓存key生成策略
- Base64.ets # Base64算法
- CustomMap.ets # 自定义Map封装
- DiskCacheEntry.ets# 磁盘缓存entry
- DiskLruCache.ets # 磁盘LRU缓存策略
- FileReader.ets # 文件读取相关
- FileUtils.ets # 文件工具类
- LruCache.ets # 内存LRU缓存策略
- Md5.ets # MD5算法
- imageknife # imageknife主要内容
- compress # 压缩相关
- constants # 常量相关
- entry # 部分数据结构
- holder # 占位图相关解析
- interface # 接口相关
- networkmanage # 网络相关
- pngj # pngj相关
- requestmanage # imageknife请求相关
- resourcemanage # 本地资源解析相关
- transform # 图片变换相关
- utils # 工具类相关
- ImageKnife.ets # imageknife门面app持久化类
- ImageKnifeData.ets # 数据封装
- ImageKnifeComponent.ets # 自定义控件封装
- ImageKnifeOption.ets # 用户传参数封装
- PixelMapPack.ets # PixelMap封装
- RequestOption.ets # 用户设置参数封装
- compress # 压缩相关
- constants # 常量相关
- entry # 部分数据结构
- holder # 占位图相关解析
- interface # 接口相关
- networkmanage # 网络相关
- pngj # pngj相关
- requestmanage # imageknife请求相关
- resourcemanage # 本地资源解析相关
- transform # 图片变换相关
- utils # 工具类相关
- ImageKnife.ets # imageknife门面app持久化类
- ImageKnifeData.ets # 数据封装
- ImageKnifeComponent.ets # 自定义控件封装
- ImageKnifeOption.ets # 用户传参数封装
- PixelMapPack.ets # PixelMap封装
- RequestOption.ets # 用户设置参数封装
/entry/src/
- main/ets/MainAbility
- main/ets/MainAbility
- pages # 测试page页面列表
- basicTestFeatureAbilityPage.ets # 测试元能力
- basicTestFileIOPage.ets # 测试fileio
- basicTestMediaImage.ets # 测试媒体image
- basicTestResourceManagerPage.ets # 测试本地资源解析
- compressPage.ets # 压缩页面
- frescoImageTestCasePage.ets # 测试属性动画组件切换
- frescoLayerTestCasePage.ets # 测试ImageKnifeComponent组件切换配合属性动画
- frescoRetryTestCasePage.ets # 测试ImageKnifeComponent加载失败重试
- index.ets # 测试页面入口
- indexFresco.ets # 二级测试页面入口
- loadNetworkTestCasePage.ets # 网络加载测试
- loadResourceTestCasePage.ets # 本地加载测试
- showErrorholderTestCasePage.ets # 加载失败占位图测试
- storageTestDiskLruCache.ets # 磁盘缓存测试
- storageTestLruCache.ets # 内存缓存测试
- testAllCacheInfoPage.ets # 所有缓存信息获取测试
- testAllTypeImageKnifeComponentPage.ets # 所有类型图片加载测试
- testAllTypeNativeImagePage.ets # 所有类型本地图片加载测试
- testGifDontAnimatePage.ets # gif加载静态图片测试
- testImageKnifeOptionChangedPage.ets # ImageKnifeOption数据切换测试
- testImageKnifeOptionChangedPage2.ets # ImageKnifeOption数据切换测试
- testMultiThreadWorkerPage2.ets # 多线程测试
- testPlaceholderPage.ets # 加载占位图测试
- testPreloadPage.ets # 预加载测试
- testResourceManagerPage.ets # 解析本地资源测试
- transformPixelMapPage.ets # 所有类型变换测试
- transformTestCasePage.ets # 所有类型变换配合ImageKnifeComponent测试
- basicTestFeatureAbilityPage.ets # 测试元能力
- basicTestFileIOPage.ets # 测试fileio
- basicTestMediaImage.ets # 测试媒体image
- basicTestResourceManagerPage.ets # 测试本地资源解析
- compressPage.ets # 压缩页面
- cropImagePage.ets # 裁剪页面
- cropImagePage2.ets # 手势裁剪页面
- frescoImageTestCasePage.ets # 测试属性动画组件切换
- frescoLayerTestCasePage.ets # 测试ImageKnifeComponent组件切换配合属性动画
- frescoRetryTestCasePage.ets # 测试ImageKnifeComponent加载失败重试
- index.ets # 测试页面入口
- indexFresco.ets # 二级测试页面入口
- loadNetworkTestCasePage.ets # 网络加载测试
- loadResourceTestCasePage.ets # 本地加载测试
- showErrorholderTestCasePage.ets # 加载失败占位图测试
- storageTestDiskLruCache.ets # 磁盘缓存测试
- storageTestLruCache.ets # 内存缓存测试
- testAllCacheInfoPage.ets # 所有缓存信息获取测试
- testAllTypeImageKnifeComponentPage.ets # 所有类型图片加载测试
- testAllTypeNativeImagePage.ets # 所有类型本地图片加载测试
- testGifDontAnimatePage.ets # gif加载静态图片测试
- testImageKnifeOptionChangedPage.ets # ImageKnifeOption数据切换测试
- testImageKnifeOptionChangedPage2.ets # ImageKnifeOption数据切换测试
- testMultiThreadWorkerPage2.ets # 多线程测试
- testPlaceholderPage.ets # 加载占位图测试
- testPreloadPage.ets # 预加载测试
- testResourceManagerPage.ets # 解析本地资源测试
- transformPixelMapPage.ets # 所有类型变换测试
- transformTestCasePage.ets # 所有类型变换配合ImageKnifeComponent测试
- workers # 测试worker多线程
- worker1.js # worker多线程测试
- worker1.js # worker多线程测试
```
## 贡献代码

View File

@ -1,21 +1,7 @@
{
"app": {
"signingConfigs": [
{
"name": "default",
"material": {
"certpath": "C:\\Users\\zwx1045834\\.ohos\\config\\openharmony\\auto_ohos.cer",
"storePassword": "000000184CD86AF7B78D3E3B6C36B9221705137AC28BD8A341A757477E5DC27D95E6A0DFD5EB51AE",
"keyAlias": "debugKey",
"keyPassword": "00000018DAB1AB9C9DF6E7C4D35BE8EAF4323EFA49131AB39C65BA5C44DE6D3879C6B31AA70D1E14",
"profile": "C:\\Users\\zwx1045834\\.ohos\\config\\openharmony\\auto_ohos_default_com.example.imageknifegiteepro.p7b",
"signAlg": "SHA256withECDSA",
"storeFile": "C:\\Users\\zwx1045834\\.ohos\\config\\openharmony\\auto_ohos.p12"
}
}
],
"compileSdkVersion": 8,
"compatibleSdkVersion": 8,
"compileSdkVersion": 9,
"compatibleSdkVersion": 9,
"products": [
{
"name": "default",
@ -39,6 +25,10 @@
{
"name": "imageknife",
"srcPath": "./imageknife"
},
{
"name": "disklrucache",
"srcPath": "./disklrucache"
}
]
}

3
disklrucache/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/node_modules
/.preview
/build

View File

@ -0,0 +1,5 @@
{
"apiType": "stageMode",
"buildOption": {
}
}

View File

@ -0,0 +1,3 @@
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').harTasks

20
disklrucache/index.ets Normal file
View File

@ -0,0 +1,20 @@
/*
* 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.
*/
/**
* disklrucache
*/
export * from './src/main/ets/components/disklrucache/DiskLruCache'
export * from './src/main/ets/components/disklrucache/DiskCacheEntry'

18
disklrucache/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"license":"ISC",
"types":"",
"devDependencies":{
"@types/spark-md5":"^3.0.2"
},
"name":"@ohos/disklrucache",
"description":"a npm package which contains arkUI2.0 page",
"ohos":{
"org":""
},
"main":"index.ets",
"repository":{},
"version":"1.0.0",
"dependencies":{
"spark-md5":"^3.0.2"
}
}

View File

@ -0,0 +1,115 @@
/*
* 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 CustomMap <K, V> {
map: Map<K, V> = new Map<K, V>()
/**
*
*
* @param key
*/
get(key: K): V | undefined {
if (key == null) {
throw new Error('key is null,checking the parameter');
}
return this.map.get(key)
}
/**
* key的缓存
*
* @param key
*/
hasKey(key: K) {
if (key == null) {
throw new Error('key is null,checking the parameter');
}
return this.map.has(key)
}
/**
*
*
* @param key
* @param value
*/
put(key: K, value: V): V | undefined {
if (key == null || value == null) {
throw new Error('key or value is invalid,checking the parameter');
}
let pre = this.map.get(key)
if (this.hasKey(key)) {
this.map.delete(key)
}
this.map.set(key, value);
return pre
}
/**
* ()
*
* @param key
*/
remove(key: K): boolean {
if (key == null) {
throw new Error('key is null,checking the parameter');
}
return this.map.delete(key)
}
/**
* key
*/
getFirstKey(): K { // keys()可以遍历后需要优化put()方法暂时仅获取index=0的key
return this.map.keys().next().value
}
/**
*
*/
isEmpty(): boolean {
return this.map.size == 0;
}
/**
*
*/
size(): number {
return this.map.size;
}
/**
* Map,. function(key,value,index){..}
*
* @param fn
*/
each(fn) {
this.map.forEach(fn)
}
/**
*
*/
clear() {
this.map.clear()
}
/**
* key
*/
keys(): IterableIterator<K> {
return this.map.keys()
}
}

View File

@ -13,35 +13,34 @@
* limitations under the License.
*/
export class DiskCacheEntry {
// 缓存的key
key: string = ''
// 缓存的key
key: string= ''
// 缓存文件大小
length: number = 0
// 缓存文件大小
length: number= 0
constructor(key: string, length?: number) {
this.key = key
this.length = length
}
constructor(key: string, length?: number) {
this.key = key
this.length = length
}
setKey(key: string) {
this.key = key
}
setKey(key: string) {
this.key = key
}
getKey(): string {
return this.key
}
getkey(): string{
return this.key
}
setLength(length: number) {
this.length = length
}
setLength(length: number) {
this.length = length
}
getLength(): number {
return this.length
}
getLength(): number{
return this.length
}
toString(): string{
return this.key + ' - ' + this.length
}
toString(): string {
return this.key + ' - ' + this.length
}
}

View File

@ -0,0 +1,444 @@
/*
* 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 fileio from '@ohos.fileio'
import { CustomMap } from './CustomMap'
import { FileUtils } from './FileUtils'
import { FileReader } from './FileReader'
import { DiskCacheEntry } from './DiskCacheEntry'
import SparkMD5 from "spark-md5"
export class DiskLruCache {
// 默认缓存数据最大值
private static readonly DEFAULT_MAX_SIZE: number = 30 * 1024 * 1024
// 缓存journal文件名称
private static readonly journal: string = 'journal'
// 缓存journal备份文件名称
private static readonly journalTemp: string = 'journal_temp'
// 备份文件save标识符
private static readonly SAVE: string = 'save'
// 备份文件read标识符
private static readonly READ: string = 'read'
// 备份文件remove标识符
private static readonly REMOVE: string = 'remove'
// 缓存文件路径地址
private path: string = ''
// 缓存journal文件路径
private journalPath: string = ''
// 缓存journal备份文件路径
private journalPathTemp: string = ''
// 缓存数据最大值
private maxSize: number = DiskLruCache.DEFAULT_MAX_SIZE
// 当前缓存数据值
private size: number = 0
// 缓存数据集合
private cacheMap: CustomMap<string, DiskCacheEntry> = new CustomMap<string, DiskCacheEntry>()
private constructor(path: string, maxSize: number) {
this.path = path
this.maxSize = maxSize
this.journalPath = path + DiskLruCache.journal
this.journalPathTemp = path + DiskLruCache.journalTemp
}
/**
* path中的缓存
*
* @param path
* @param maxSize 3M
*/
public static create(path: string, maxSize?: number): DiskLruCache {
if (!!!path) {
throw new Error('DiskLruCache create path is empty, checking the parameter');
}
if (!!!maxSize) {
maxSize = DiskLruCache.DEFAULT_MAX_SIZE
}
if (maxSize <= 0) {
throw new Error("DiskLruCache create maxSize <= 0, checking the parameter");
}
if (!FileUtils.getInstance().existFolder(path)) {
FileUtils.getInstance().createFolder(path, true)
}
if (path.endsWith(FileUtils.SEPARATOR)) {
path = path
} else {
path = path + FileUtils.SEPARATOR
}
let journalPath = path + DiskLruCache.journal
let journalPathTemp = path + DiskLruCache.journalTemp
// 判断日志文件是否存在,如果没有初始化创建
if (FileUtils.getInstance().exist(journalPath)) {
let stat = fileio.statSync(journalPath)
if (stat.size > 0) {
FileUtils.getInstance().createFile(journalPathTemp)
FileUtils.getInstance().copyFile(journalPath, journalPathTemp)
let diskLruCache: DiskLruCache = new DiskLruCache(path, maxSize)
diskLruCache.readJournal(journalPathTemp)
diskLruCache.resetJournalFile()
return diskLruCache
} else {
return new DiskLruCache(path, maxSize)
}
} else {
FileUtils.getInstance().createFile(journalPath)
return new DiskLruCache(path, maxSize)
}
}
/**
* journal文件数据
*
* @param line
*/
private dealWithJournal(line: string) {
let filePath = ''
try {
let lineData = line.split(' ')
if (lineData.length > 1) {
if (lineData[0] != DiskLruCache.REMOVE) {
filePath = this.path + lineData[1]
let fileStat = fileio.statSync(filePath)
if (fileStat.isFile() && fileStat.size > 0) {
this.size = this.size + fileStat.size
FileUtils.getInstance().writeData(this.journalPath, line + FileReader.LF)
this.putCacheMap(lineData[1], fileStat.size)
}
} else {
if (this.cacheMap.hasKey(lineData[1])) {
let cacheEntry: DiskCacheEntry = this.cacheMap.get(lineData[1])
this.size = this.size - cacheEntry.getLength()
this.cacheMap.remove(lineData[1])
}
}
}
} catch (e) {
console.error('DiskLruCache - dealWithJournal e ' + e)
}
}
/**
* disk缓存最大数据值
*
* @param max
*/
setMaxSize(max: number) {
this.maxSize = max
this.trimToSize()
}
/**
* disk缓存数据
*
* @param key
* @param content
*/
set(key: string, content: ArrayBuffer) {
if (!!!key) {
throw new Error('key is null, checking the parameter')
}
if (content == null || content.byteLength == 0) {
throw new Error('content is null, checking the parameter')
}
let fileSize = content.byteLength
key = SparkMD5.hash(key)
this.size = this.size + fileSize
this.putCacheMap(key, fileSize)
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.SAVE + ' ' + key + FileReader.LF)
this.trimToSize()
let tempPath = this.path + key
FileUtils.getInstance().writeNewFile(tempPath, content)
}
/**
* disk缓存数据
*
* @param key
* @param content
*/
async setAsync(key: string, content: ArrayBuffer): Promise<void> {
if (!!!key) {
throw new Error('key is null, checking the parameter')
}
if (content == null || content.byteLength == 0) {
throw new Error('content is null, checking the parameter')
}
let fileSize = content.byteLength
key = SparkMD5.hash(key)
this.size = this.size + fileSize
console.log('setAsync fileSize ='+ fileSize +' all size ='+this.size + ' max size ='+this.maxSize);
this.putCacheMap(key, fileSize)
await FileUtils.getInstance().writeDataAsync(this.journalPath, DiskLruCache.SAVE + ' ' + key + FileReader.LF)
this.trimToSize()
let tempPath = this.path + key
await FileUtils.getInstance().writeNewFileAsync(tempPath, content)
}
/**
* disk缓存数据
*
* @param key key
* @param path
*/
setFileByPath(key: string, path: string) {
if (!!!key) {
throw new Error('key is null, checking the parameter')
}
if (!!!path || !FileUtils.getInstance().exist(path)) {
throw new Error('path is null or no exist file, checking the parameter')
}
let fileSize = FileUtils.getInstance().getFileSize(path)
if (fileSize == -1) {
throw new Error('path getFileSize error ')
}
key = SparkMD5.hash(key)
this.size = this.size + fileSize
this.putCacheMap(key, fileSize)
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.SAVE + ' ' + key + FileReader.LF)
this.trimToSize()
fileSize = FileUtils.getInstance().getFileSize(path)
FileUtils.getInstance().copyFile(path, this.path + key)
}
/**
* disk缓存数据
*
* @param key key
* @param path
*/
async setFileByPathAsync(key: string, path: string): Promise<void> {
if (!!!key) {
throw new Error('key is null, checking the parameter')
}
if (!!!path || !FileUtils.getInstance().exist(path)) {
throw new Error('path is null or no exist file, checking the parameter')
}
let fileSize = FileUtils.getInstance().getFileSize(path)
if (fileSize == -1) {
throw new Error('path getFileSize error ')
}
key = SparkMD5.hash(key)
this.size = this.size + fileSize
this.putCacheMap(key, fileSize)
await FileUtils.getInstance().writeDataAsync(this.journalPath, DiskLruCache.SAVE + ' ' + key + FileReader.LF)
this.trimToSize()
fileSize = FileUtils.getInstance().getFileSize(path)
await FileUtils.getInstance().copyFileAsync(path, this.path + key)
}
/**
* key缓存数据
*
* @param key key
*/
get(key: string): ArrayBuffer {
if (!!!key) {
throw new Error('key is null,checking the parameter');
}
key = SparkMD5.hash(key)
let path = this.path + key;
if (FileUtils.getInstance().exist(path)) {
let ab: ArrayBuffer = FileUtils.getInstance().readFile(path)
this.putCacheMap(key, ab.byteLength)
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.READ + ' ' + key + FileReader.LF)
return ab
} else {
return null;
}
}
/**
* key缓存数据
*
* @param key
*/
async getAsync(key: string): Promise<ArrayBuffer> {
if (!!!key) {
throw new Error('key is null,checking the parameter');
}
key = SparkMD5.hash(key)
let path = this.path + key;
if (FileUtils.getInstance().exist(path)) {
let ab: ArrayBuffer = await FileUtils.getInstance().readFileAsync(path)
this.putCacheMap(key, ab.byteLength)
await FileUtils.getInstance().writeDataAsync(this.journalPath, DiskLruCache.READ + ' ' + key + FileReader.LF)
return ab
} else {
return null;
}
}
/**
* key缓存数据绝对路径
*
* @param key
*/
getFileToPath(key: string): string {
if (!!!key) {
throw new Error('key is null,checking the parameter');
}
key = SparkMD5.hash(key);
let path = this.path + key;
if (FileUtils.getInstance().exist(path)) {
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.READ + ' ' + key + FileReader.LF);
return path
} else {
return null
}
}
/**
* key缓存数据绝对路径
*
* @param key
*/
async getFileToPathAsync(key: string): Promise<string> {
if (!!!key) {
throw new Error('key is null,checking the parameter');
}
key = SparkMD5.hash(key);
let path = this.path + key;
if (FileUtils.getInstance().exist(path)) {
await FileUtils.getInstance().writeDataAsync(this.journalPath, DiskLruCache.READ + ' ' + key + FileReader.LF);
return path
} else {
return null
}
}
/**
* key缓存数据
*
* @param key
*/
deleteCacheDataByKey(key: string): DiskCacheEntry {
if (!!!key) {
throw new Error('key is null,checking the parameter');
}
key = SparkMD5.hash(key)
let path = this.path + key;
if (FileUtils.getInstance().exist(path)) {
let ab = FileUtils.getInstance().readFile(path)
this.size = this.size - ab.byteLength
this.cacheMap.remove(key)
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.REMOVE + ' ' + key + FileReader.LF)
FileUtils.getInstance().deleteFile(path)
}
return this.cacheMap.get(key)
}
/**
*
*
* @param fn
*/
foreachDiskLruCache(fn) {
this.cacheMap.each(fn)
}
/**
* disk缓存数据
*/
cleanCacheData() {
this.cacheMap.each((value, key) => {
FileUtils.getInstance().deleteFile(this.path + key)
})
FileUtils.getInstance().deleteFile(this.journalPath)
this.cacheMap.clear()
this.size = 0
}
/**
* journal文件数据
*/
private resetJournalFile() {
FileUtils.getInstance().clearFile(this.journalPath)
for (let key of this.cacheMap.keys()) {
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.SAVE + ' ' + key + FileReader.LF)
}
}
/**
* journal文件的缓存数据
*
* @param path
*/
private readJournal(path: string) {
let fileReader = new FileReader(path)
let line: string = ''
while (!fileReader.isEnd()) {
line = fileReader.readLine()
line = line.replace(FileReader.LF, '').replace(FileReader.CR, '')
this.dealWithJournal(line)
}
fileReader.close()
FileUtils.getInstance().deleteFile(this.journalPathTemp)
this.trimToSize()
}
/**
* map集合
*
* @param key
* @param length
*/
private putCacheMap(key: string, length?: number) {
if (length > 0) {
console.log('key = '+key)
console.log('value length= '+ length)
this.cacheMap.put(key, new DiskCacheEntry(key, length))
} else {
this.cacheMap.put(key, new DiskCacheEntry(key))
}
}
/**
* LRU算法删除多余缓存数据
*/
private trimToSize() {
while (this.size > this.maxSize) {
let tempKey: string = this.cacheMap.getFirstKey()
let fileSize = FileUtils.getInstance().getFileSize(this.path + tempKey)
if (fileSize > 0) {
this.size = this.size - fileSize
}
console.log('trimToSize fileSize ='+ fileSize +' all size ='+this.size + ' max size ='+this.maxSize);
FileUtils.getInstance().deleteFile(this.path + tempKey)
this.cacheMap.remove(tempKey)
FileUtils.getInstance().writeData(this.journalPath, DiskLruCache.REMOVE + ' ' + tempKey + FileReader.LF)
}
}
getPath(){
return this.path;
}
getCacheMap(){
return this.cacheMap;
}
}

View File

@ -0,0 +1,83 @@
/*
* 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 fileio from '@ohos.fileio'
export class FileReader {
// 换行符
static readonly LF: string = '\n'
// CR符
static readonly CR: string = '\r'
// 文件大小
fileLength: number = 0
// 读取的长度
length: number = 0
// 读写stream
stream: any = null
// 缓存buf
buf: ArrayBuffer = new ArrayBuffer(1)
/**
*
*
* @param path
*/
constructor(path: string) {
if (!path || Object.keys(path).length == 0) {
return
}
try {
this.stream = fileio.createStreamSync(path, 'r+');
let stat = fileio.statSync(path)
this.fileLength = stat.size
} catch (e) {
}
}
/**
*
*/
readLine(): string {
let line = ''
while (this.length <= this.fileLength) {
this.stream.readSync(this.buf, { position: this.length })
this.length++
let temp = String.fromCharCode.apply(null, new Uint8Array(this.buf));
line = line + temp
if (temp == FileReader.LF || temp == FileReader.CR) {
return line
}
}
return line
}
/**
*
*/
isEnd() {
return this.fileLength <= 0 || this.length == this.fileLength
}
/**
* stream
*/
close() {
this.stream.closeSync()
}
}

View File

@ -0,0 +1,240 @@
/*
* 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 fileio from '@ohos.fileio'
export class FileUtils {
private static sInstance: FileUtils
static readonly SEPARATOR: string = '/'
base64Str: string = ''
/**
* FileUtils类
*/
public static getInstance(): FileUtils {
if (!this.sInstance) {
this.sInstance = new FileUtils();
}
return this.sInstance;
}
private constructor() {
}
/**
*
*
* @param path
* @return number id
*/
createFile(path: string): number {
return fileio.openSync(path, 0o100, 0o664)
}
/**
*
*
* @param path
*/
deleteFile(path: string): void {
fileio.unlinkSync(path);
}
/**
*
*
* @param src
* @param dest
*/
copyFile(src: string, dest: string) {
fileio.copyFileSync(src, dest);
}
/**
*
*
* @param src
* @param dest
*/
async copyFileAsync(src: string, dest: string): Promise<void> {
await fileio.copyFile(src, dest);
}
/**
*
*
* @param path
*/
clearFile(path: string): number {
return fileio.openSync(path, 0o1000)
}
/**
* path写入数据
*
* @param path
* @param content
*/
writeData(path: string, content: ArrayBuffer | string) {
let fd = fileio.openSync(path, 0o102, 0o664)
let stat = fileio.statSync(path)
fileio.writeSync(fd, content, { position: stat.size })
fileio.closeSync(fd)
}
/**
* path写入数据
*
* @param path
* @param content
*/
async writeDataAsync(path: string, content: ArrayBuffer | string): Promise<void> {
let fd = await fileio.open(path, 0o102, 0o664)
let stat = await fileio.stat(path)
await fileio.write(fd, content, { position: stat.size })
await fileio.close(fd)
}
/**
* path文件是否存在
*
* @param path
*/
exist(path: string): boolean {
try {
let stat = fileio.statSync(path)
return stat.isFile()
} catch (e) {
console.error("FileUtils exist e " + e)
return false
}
}
/**
* path写入数据
*
* @param path
* @param data
*/
writeNewFile(path: string, data: ArrayBuffer) {
this.createFile(path)
this.writeFile(path, data)
}
/**
* path写入数据
*
* @param path
* @param data
*/
async writeNewFileAsync(path: string, data: ArrayBuffer): Promise<void> {
await fileio.open(path, 0o100, 0o664)
let fd = await fileio.open(path, 0o102, 0o664)
await fileio.ftruncate(fd)
await fileio.write(fd, data)
await fileio.fsync(fd)
await fileio.close(fd)
}
/**
* path的文件大小
*
* @param path
*/
getFileSize(path: string): number {
try {
let stat = fileio.statSync(path)
return stat.size
} catch (e) {
console.error("FileUtils getFileSize e " + e)
return -1
}
}
/**
* path的文件
*
* @param path
*/
readFile(path: string): ArrayBuffer {
let fd = fileio.openSync(path, 0o2);
let length = fileio.statSync(path).size
let buf = new ArrayBuffer(length);
fileio.readSync(fd, buf)
return buf
}
/**
* path的文件
*
* @param path
*/
async readFileAsync(path: string): Promise<ArrayBuffer> {
let stat = await fileio.stat(path);
let fd = await fileio.open(path, 0o2);
let length = stat.size;
let buf = new ArrayBuffer(length);
await fileio.read(fd, buf);
return buf
}
/**
*
*
* @param path
* @param recursive
*/
createFolder(path: string, recursive?: boolean) {
if (recursive) {
if (!this.existFolder(path)) {
let lastInterval = path.lastIndexOf(FileUtils.SEPARATOR)
if (lastInterval == 0) {
return
}
let newPath = path.substring(0, lastInterval)
this.createFolder(newPath, true)
if (!this.existFolder(path)) {
fileio.mkdirSync(path)
}
}
} else {
if (!this.existFolder(path)) {
fileio.mkdirSync(path)
}
}
}
/**
*
*
* @param path
*/
existFolder(path: string): boolean {
try {
let stat = fileio.statSync(path)
return stat.isDirectory()
} catch (e) {
console.error("FileUtils folder exist e " + e)
return false
}
}
private writeFile(path: string, content: ArrayBuffer | string) {
let fd = fileio.openSync(path, 0o102, 0o664)
fileio.ftruncateSync(fd)
fileio.writeSync(fd, content)
fileio.fsyncSync(fd)
fileio.closeSync(fd)
}
}

View File

@ -0,0 +1,11 @@
{
"module": {
"name": "disklrucache",
"type": "har",
"deviceTypes": [
"default",
"tablet"
],
"uiSyntax": "ets"
}
}

View File

@ -0,0 +1,8 @@
{
"string": [
{
"name": "page_show",
"value": "page from npm package"
}
]
}

View File

@ -1,6 +1,11 @@
{
"apiType": 'faMode',
"apiType": 'stageMode',
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/pages/workers/worker1.js",
]
}
},
"targets": [
{

View File

@ -1,2 +1,2 @@
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').legacyHapTasks
module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks

View File

@ -1,21 +0,0 @@
{
"name": "entry",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@ohos/imageknife": {
"version": "file:../imageknife",
"requires": {
"pako": "^1.0.5"
},
"dependencies": {
"pako": {
"version": "1.0.11",
"resolved": "http://mirrors.tools.huawei.com/npm/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="
}
}
}
}
}

View File

@ -1,14 +1,16 @@
{
"license": "Apache License 2.0",
"devDependencies": {},
"name": "entry",
"ohos": {
"org": "huawei",
"directoryLevel": "module",
"buildTool": "hvigor"
"license":"ISC",
"devDependencies":{},
"name":"entry",
"ohos":{
"org":"huawei",
"directoryLevel":"module",
"buildTool":"hvigor"
},
"version": "1.0.0",
"dependencies": {
"@ohos/imageknife": "file:../imageknife"
"description":"example description",
"repository":{},
"version":"1.0.0",
"dependencies":{
"@ohos/imageknife":"file:../imageknife"
}
}
}

View File

@ -1,140 +0,0 @@
{
"app": {
"vendor": "openharmony",
"bundleName": "cn.openharmony.imageknife",
"version": {
"code": 1000000,
"name": "1.0.0"
}
},
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
},
"module": {
"mainAbility": ".MainAbility",
"deviceType": [
"phone",
"tablet"
],
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"orientation": "unspecified",
"visible": true,
"srcPath": "MainAbility",
"name": ".MainAbility",
"srcLanguage": "ets",
"icon": "$media:icon",
"description": "$string:ImageKnife_OHOS",
"formsEnabled": false,
"label": "$string:ImageKnife_OHOS",
"type": "page",
"launchType": "standard"
}
],
"distro": {
"moduleType": "entry",
"installationFree": false,
"deliveryWithInstall": true,
"moduleName": "entry"
},
"package": "cn.openharmony.entry",
"srcPath": "",
"name": ".entry",
"reqPermissions": [
{
"name": "ohos.permission.READ_USER_STORAGE"
},
{
"name": "ohos.permission.INTERNET",
"reason": "Api call",
"usedScene": {
"ability": [
"cn.openharmony.imageknife.MainAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
},
{
"name": "ohos.permission.READ_MEDIA",
"reason": "location background",
"usedScene": {
"when": "always",
"ability": [
"cn.openharmony.imageknife.MainAbility"
]
}
},
{
"name": "ohos.permission.WRITE_MEDIA",
"reason": "location background",
"usedScene": {
"when": "always",
"ability": [
"cn.openharmony.imageknife.MainAbility"
]
}
}
],
"js": [
{
"mode": {
"syntax": "ets",
"type": "pageAbility"
},
"pages": [
"pages/index",
"pages/indexFresco",
"pages/frescoLayerTestCasePage",
"pages/frescoImageTestCasePage",
"pages/frescoRetryTestCasePage",
"pages/basicTestFeatureAbilityPage",
"pages/basicTestFileIOPage",
"pages/basicTestMediaImage",
"pages/basicTestResourceManagerPage",
"pages/storageTestLruCache",
"pages/storageTestDiskLruCache",
"pages/transformTestCasePage",
"pages/pngjTestCasePage",
"pages/testAllTypeImageKnifeComponentPage",
"pages/testAllTypeNativeImagePage",
"pages/loadResourceTestCasePage",
"pages/loadNetworkTestCasePage",
"pages/showErrorholderTestCasePage",
"pages/transformPixelMapPage",
"pages/testGifDontAnimatePage",
"pages/testPreloadPage",
"pages/testImageKnifeOptionChangedPage",
"pages/testImageKnifeOptionChangedPage2",
"pages/compressPage",
"pages/testAllCacheInfoPage",
"pages/testResourceManagerPage",
"pages/testMultiThreadWorkerPage2",
"pages/testImageKnifeOptionChangedPage",
"pages/cropImagePage"
],
"name": ".MainAbility",
"window": {
"designWidth": 720,
"autoDesignWidth": false
}
}
]
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2022 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
@ -12,18 +12,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import app from '@system.app';
import AbilityStage from "@ohos.application.AbilityStage"
import {ImageKnife} from '@ohos/imageknife'
export default {
data: {
imageKnife: {} // ImageKnife
},
onCreate() {
this.data.imageKnife = ImageKnife.with();
},
onDestroy() {
},
}
export default class MyAbilityStage extends AbilityStage {
onCreate() {
globalThis.ImageKnife = ImageKnife.with(this.context);
}
}

View File

@ -0,0 +1,7 @@
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("[Demo] MyAbilityStage onCreate")
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright (C) 2022 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 Ability from '@ohos.application.Ability'
import {ImageKnife} from '@ohos/imageknife'
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
// this.context.resourceManager.getMedia()
// globalThis.ImageKnifeContext = this.context;
// globalThis.ImageKnife = ImageKnife.with(this.context);
// this.context.filesDir
console.log('globalThis.ImageKnife 1 ='+typeof globalThis.ImageKnife)
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate")
windowStage.setUIContent(this.context, "pages/index", null)
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy")
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground")
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground")
}
};

View File

@ -1,146 +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 featureAbility from '@ohos.ability.featureAbility';
import {FileUtils} from '@ohos/imageknife'
import {FileTypeUtil} from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager';
import {Base64} from '@ohos/imageknife'
import {PixelMapPack} from '@ohos/imageknife'
import {ParseImageUtil} from '@ohos/imageknife'
@Entry
@Component
struct BasicTestMediaImage {
@State pixelMapPack:PixelMapPack= new PixelMapPack();
build() {
Scroll() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Flex({direction:FlexDirection.Row}){
Button('本地资源jpg')
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.jpgSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer,(pxielmap)=>{
let jpgPack = new PixelMapPack();
jpgPack.pixelMap = pxielmap;
this.pixelMapPack = jpgPack;
},(err)=>{})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
})
}).margin({left:15}).backgroundColor(Color.Blue)
Button('本地资源png')
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.pngSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer,(pxielmap)=>{
let pngPack = new PixelMapPack();
pngPack.pixelMap = pxielmap;
this.pixelMapPack = pngPack;
},(err)=>{})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
})
}).margin({left:15}).backgroundColor(Color.Blue)
Button('本地资源bmp')
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.bmpSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer,(pxielmap)=>{
let bmpPack = new PixelMapPack();
bmpPack.pixelMap = pxielmap;
this.pixelMapPack = bmpPack;
},(err)=>{})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
})
}).margin({left:15}).backgroundColor(Color.Blue)
Button('本地资源webp')
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.jpgSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer,(pxielmap)=>{
let webpPack = new PixelMapPack();
webpPack.pixelMap = pxielmap;
this.pixelMapPack = webpPack;
},(err)=>{})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
})
}).margin({left:15}).backgroundColor(Color.Blue)
Button('本地资源gif')
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.gifSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer,(pxielmap)=>{
let gifPack = new PixelMapPack();
gifPack.pixelMap = pxielmap;
this.pixelMapPack = gifPack;
},(err)=>{})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
})
}).margin({left:15}).backgroundColor(Color.Blue)
}
.margin({top:15})
Image(this.pixelMapPack.pixelMap)
.width(300)
.height(300)
.backgroundColor(Color.Pink)
}
}
.width('100%')
.height('100%')
}
typedArrayToBuffer(array: Uint8Array): ArrayBuffer {
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
}
}

View File

@ -12,12 +12,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import featureAbility from '@ohos.ability.featureAbility';
@Entry
@Component
struct BasicTestFeatureAbilityPage {
@Watch("watchPathChange") @State filePath:string= "查看featureAbility路径";
@Watch("watchPathChange") @State filePath: string = "查看featureAbility路径";
watchPathChange() {
console.log("watchPathChange");
@ -28,30 +28,19 @@ struct BasicTestFeatureAbilityPage {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(this.filePath).fontSize(20)
Button("featureAbility.getContext().getFilesDir()")
.margin({top:20})
.onClick(()=>{
featureAbility.getContext()
.getFilesDir()
.then((data) => {
.margin({ top: 20 })
.onClick(() => {
let data = globalThis.ImageKnife.getImageKnifeContext().filesDir;
console.log("ImageKnife filesPath = " + data)
this.filePath = data
})
.catch((error) => {
console.error('ImageKnife Failed to obtain the filesPath directory. Cause:' + error.message);
})
})
Button("featureAbility.getContext().getCacheDir()")
.margin({top:20})
.onClick(()=>{
featureAbility.getContext().getCacheDir()
.then((data) => {
.margin({ top: 20 })
.onClick(() => {
let data = globalThis.ImageKnife.getImageKnifeContext().cacheDir;
console.log("ImageKnife cachesPath = " + data)
this.filePath = data
})
.catch((error) => {
console.error('ImageKnife Failed to obtain the cachesPath directory. Cause:' + error.message);
})
})
}
}
.width('100%')

View File

@ -12,14 +12,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import featureAbility from '@ohos.ability.featureAbility';
import { FileUtils } from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager';
@Entry
@Component
struct BasicTestFileIOPage {
@Watch('watchPathChange') @State filePath: string= '查看featureAbility路径';
struct basicTestFileIOPage {
@State filePath: string = '查看featureAbility路径';
appFilePath = '';
appCachePath = '';
@State imageFile: string = ''
@ -39,34 +39,27 @@ struct BasicTestFileIOPage {
Button('featureAbility.getContext().getFilesDir()')
.margin({ top: 10 })
.onClick(() => {
featureAbility.getContext()
.getFilesDir()
.then((data) => {
console.log('ImageKnife filesPath = ' + data)
this.filePath = data
this.appFilePath = data;
})
.catch((error) => {
console.error('ImageKnife Failed to obtain the filesPath directory. Cause:' + error.message);
})
let data = globalThis.ImageKnife.getImageKnifeContext().filesDir;
console.log('ImageKnife filesPath = ' + data)
this.filePath = data
this.appFilePath = data;
})
Button('featureAbility.getContext().getCacheDir()')
.margin({ top: 10 })
.onClick(() => {
featureAbility.getContext()
.getCacheDir()
.then((data) => {
console.log('ImageKnife cachesPath = ' + data)
this.filePath = data
this.appCachePath = data
})
.catch((error) => {
console.error('ImageKnife Failed to obtain the cachesPath directory. Cause:' + error.message);
})
let data = globalThis.ImageKnife.getImageKnifeContext().cacheDir;
console.log('ImageKnife cachesPath = ' + data)
this.filePath = data
this.appFilePath = data;
})
Button('files目录创建Folder1和Folder2 验证statSync mkdirSync')
.margin({ top: 10 })
.onClick(() => {
console.log('files目录创建Folder1和Folder2 验证statSync mkdirSync')
FileUtils.getInstance()
.createFolder(this.appFilePath + '/Folder1');
FileUtils.getInstance()
@ -75,59 +68,64 @@ struct BasicTestFileIOPage {
Button('将media资源存入Folder1 验证writeSync mkdirSync createStreamSync')
.margin({ top: 10 })
.onClick(() => {
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.gifSample').id,)
.then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
let arrayBuffer = this.typedArrayToBuffer(data);
FileUtils.getInstance().writeFile(this.appFilePath + '/Folder1/jpgSample.gif', arrayBuffer)
this.imageFile = 'file://' + this.appFilePath + '/Folder1/jpgSample.gif'
})
.catch(err => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
})
console.log('将media资源存入Folder1 验证writeSync mkdirSync createStreamSync')
globalThis.ImageKnife.getImageKnifeContext().resourceManager
.getMedia($r('app.media.gifSample').id)
.then(data => {
console.log('result.getMedia')
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data length= ' + data.byteLength)
let arrayBuffer = this.typedArrayToBuffer(data);
FileUtils.getInstance().writeFile(this.appFilePath + '/Folder1/jpgSample.gif', arrayBuffer)
this.imageFile = 'file://' + this.appFilePath + '/Folder1/jpgSample.gif'
console.log('Folder1 imaeFile =' + this.imageFile)
})
.catch(err => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
})
})
Button('copy:Folder1至Folder2 验证copyFileSync')
.margin({ top: 10 })
.onClick(() => {
console.log('copy:Folder1至Folder2 验证copyFileSync')
let filePath1 = this.appFilePath + '/Folder1/jpgSample.gif';
let filePath2 = this.appFilePath + '/Folder2/jpgSample.gif';
FileUtils.getInstance().createFolder(this.appFilePath + '/Folder1')
FileUtils.getInstance().createFolder(this.appFilePath + '/Folder2')
FileUtils.getInstance().copyFile(filePath1, filePath2);
this.imageFile = 'file://' + this.appFilePath + '/Folder2/jpgSample.gif'
console.log('Folder2 imaeFile =' + this.imageFile)
})
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('显示空PixelMap')
.margin({ left: 10 })
.onClick(() => {
this.normalPixelMap=true;
this.normalPixelMap = true;
this.normalResource = false;
})
Button('显示RES')
.margin({ left: 10 })
.onClick(() => {
this.normalPixelMap=false;
this.normalPixelMap = false;
this.normalResource = true;
})
Button('显示String')
.margin({ left: 10 })
.onClick(() => {
this.normalPixelMap=false;
this.normalPixelMap = false;
this.normalResource = false;
})
}
Image(this.normalPixelMap?this.imagePixelMap:(this.normalResource? this.imageRes:this.imageFile))
Image(this.normalPixelMap ? this.imagePixelMap : (this.normalResource ? this.imageRes : this.imageFile))
.width(200)
.height(200)
.backgroundColor(Color.Pink)
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
typedArrayToBuffer(array: Uint8Array): ArrayBuffer {

View File

@ -0,0 +1,133 @@
/*
* 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 featureAbility from '@ohos.ability.featureAbility';
import { FileUtils } from '@ohos/imageknife'
import { FileTypeUtil } from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager';
import { Base64 } from '@ohos/imageknife'
import { PixelMapPack } from '@ohos/imageknife'
import { ParseImageUtil } from '@ohos/imageknife'
@Entry
@Component
struct BasicTestMediaImage {
@State pixelMapPack: PixelMapPack = new PixelMapPack();
build() {
Scroll() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Flex({ direction: FlexDirection.Row }) {
Button('本地资源jpg')
.onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.jpgSample').id)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
let jpgPack = new PixelMapPack();
jpgPack.pixelMap = pxielmap;
this.pixelMapPack = jpgPack;
}, (err) => {
})
})
.catch(err => {
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)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
let pngPack = new PixelMapPack();
pngPack.pixelMap = pxielmap;
this.pixelMapPack = pngPack;
}, (err) => {
})
})
.catch(err => {
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)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
let bmpPack = new PixelMapPack();
bmpPack.pixelMap = pxielmap;
this.pixelMapPack = bmpPack;
}, (err) => {
})
})
.catch(err => {
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)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
let webpPack = new PixelMapPack();
webpPack.pixelMap = pxielmap;
this.pixelMapPack = webpPack;
}, (err) => {
})
})
.catch(err => {
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)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
let parseImageUtil = new ParseImageUtil();
parseImageUtil.parseImage(arrayBuffer, (pxielmap) => {
let gifPack = new PixelMapPack();
gifPack.pixelMap = pxielmap;
this.pixelMapPack = gifPack;
}, (err) => {
})
})
.catch(err => {
console.log('basicTestMediaImage - 本地加载资源err' + JSON.stringify(err));
})
}).margin({ left: 15 }).backgroundColor(Color.Blue)
}
.margin({ top: 15 })
Image(this.pixelMapPack.pixelMap)
.width(300)
.height(300)
.backgroundColor(Color.Pink)
}
}
.width('100%')
.height('100%')
}
typedArrayToBuffer(array: Uint8Array): ArrayBuffer {
return array.buffer.slice(array.byteOffset, array.byteLength + array.byteOffset)
}
}

View File

@ -31,10 +31,8 @@ struct BasicTestResourceManagerPage {
Button('getMedia解析一张jpg图片')
.margin({ top: 10 })
.onClick(() => {
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.jpgSample')
.id,)
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.jpgSample')
.id,)
.then(data => {
console.log('basicTestFileIOPage - 本地加载资源 解析后数据data = ' + data)
let arrayBuffer = this.typedArrayToBuffer(data);
@ -45,17 +43,14 @@ struct BasicTestResourceManagerPage {
.catch(err => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
})
})
})
Button('getMediaBase64解析一张png图片')
.margin({ top: 10 })
.onClick(() => {
resourceManager.getResourceManager()
.then(result => {
result.getMediaBase64($r('app.media.pngSample')
.id)
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMediaBase64($r('app.media.pngSample')
.id)
.then(data => {
console.log('ParseResClientBase64 - 本地加载资源 解析后数据data = ' + data)
console.log('ParseResClientBase64 - 本地加载资源 解析后数据data')
let matchReg = ';base64,';
var firstIndex = data.indexOf(matchReg);
data = data.substring(firstIndex + matchReg.length, data.length)
@ -69,7 +64,6 @@ struct BasicTestResourceManagerPage {
.catch(err => {
console.log('basicTestFileIOPage - 本地加载资源err' + JSON.stringify(err));
})
})
})
}

View File

@ -97,7 +97,7 @@ struct CompressPage {
data.push($r('app.media.jpgSample'))
console.info("asasd start compress")
ImageKnife.with()
globalThis.ImageKnife
.compressBuilder()
.load(data)
.ignoreBy(100)
@ -137,7 +137,8 @@ struct CompressPage {
}
}
console.info("asasd start compress")
ImageKnife.with()
globalThis.ImageKnife
.compressBuilder()
.load(data)
.ignoreBy(100)

View File

@ -0,0 +1,104 @@
/*
* 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 { CropImage } from '@ohos/imageknife'
import { CropOptions } from '@ohos/imageknife'
import { Crop } from '@ohos/imageknife'
import { RecourseProvider } from '@ohos/imageknife'
import { PixelMapPack } from '@ohos/imageknife'
import { PixelMapCrop } from '@ohos/imageknife'
import { CropCallback } from '@ohos/imageknife'
import { FileUtils } from '@ohos/imageknife'
@Component
@Entry
export struct CropImagePage2 {
@State options1: PixelMapCrop.Options = new PixelMapCrop.Options();
@State cropTap: boolean = false;
@State pack: PixelMapPack = new PixelMapPack();
@State width: number = 0;
@State height: number = 0;
@State _rotate: number = 0;
@State _scale: number = 1;
private _resource: Resource = $r('app.media.bmpNet');
build() {
Column() {
Button('点击解析图片')
.onClick(() => {
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.bmpNet').id)
.then(data => {
let arrayBuffer = FileUtils.getInstance().uint8ArrayToBuffer(data);
let optionx = new PixelMapCrop.Options();
optionx.setWidth(600)
.setHeight(400)
.setCropFunction((err, pixelmap, sx, sy) => {
console.log('PMC setCropFunction callback')
if (err) {
console.error('PMC crop err =' + err)
} else {
let pack1 = new PixelMapPack();
pack1.pixelMap = pixelmap;
this.pack = pack1;
this.width = sx * px2vp(1);
this.height = sy * px2vp(1);
}
})
optionx.loadBuffer(arrayBuffer, () => {
this.options1 = optionx;
})
})
})
PixelMapCrop({ options: this.options1, cropTap: this.cropTap })
Button('点击裁剪图片')
.onClick(() => {
this.cropTap = !this.cropTap;
})
Image(this.pack.pixelMap)
.width(this.width)
.height(this.height)
.objectFit(ImageFit.Contain)
.rotate({
z: 1,
centerX: this.width / 2,
centerY: this.height / 2,
angle: this._rotate
})
.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;
})))
}
.backgroundColor(Color.Brown)
.width('100%')
.height('100%')
}
}

View File

@ -22,8 +22,6 @@ import {RoundedCornersTransformation} from '@ohos/imageknife'
struct FrescoImageTestCasePage {
@State progresshint:string = "输出加载百分比回调信息"
@State imageKnifeOption1: ImageKnifeOption =
{
loadSrc: "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83ericA1Mv66TwicuYOtbDMBcUhv1aa9RJBeAn9uURfcZD0AUGrJebAn1g2AjN0vb2E1XTET7fTuLBNmA/132",

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 1521 Huawei Device Co., Ltd.
* Copyright (C) 2022 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
@ -13,13 +13,14 @@
* limitations under the License.
*/
import router from '@system.router';
import {Pngj} from '@ohos/imageknife'
@Entry
@Component
struct Index {
@State hint1:string = '启用网络模拟加载替换网络加载'
struct IndexFunctionDemo {
@State hint1: string = '启用网络模拟加载替换网络加载'
build() {
Scroll() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
@ -148,12 +149,20 @@ struct Index {
console.log("pages/pngjTestCasePage 页面跳转")
router.push({ uri: "pages/pngjTestCasePage" });
}).margin({ top: 15 })
Button("测试图片的裁剪")
.onClick(() => {
console.log("pages/cropImagePage 页面跳转")
router.push({ uri: "pages/cropImagePage" });
}).margin({ top: 15 })
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("测试图片的裁剪")
.onClick(() => {
console.log("pages/cropImagePage 页面跳转")
router.push({ uri: "pages/cropImagePage" });
}).margin({ top: 15 })
Button("测试图片的裁剪2")
.onClick(() => {
console.log("pages/cropImagePage2 页面跳转")
router.push({ uri: "pages/cropImagePage2" });
}).margin({ top: 15 })
}.width('100%')
.height(60).backgroundColor(Color.Pink)
}
}
.width('100%')
@ -164,12 +173,6 @@ struct Index {
}
onBackPress() {
let cache = ImageKnife.getMemoryCache();
cache.print()
}
}
var ImageKnife;
var defaultTemp = globalThis.exports.default
if (defaultTemp != undefined) {
ImageKnife = defaultTemp.data.imageKnife;
}

View File

@ -22,27 +22,19 @@ struct IndexFresco {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button("测试控件隐藏与展示和动画")
.onClick(() => {
router.push({ uri: "pages/frescoLayerTestCasePage" });
}).margin({ top: 15 })
router.push({ uri: "pages/frescoLayerTestCasePage" });
}).margin({ top: 15 })
Button("测试自定义控件FrescoImage的加载百分比")
.onClick(() => {
router.push({ uri: "pages/frescoImageTestCasePage" });
}).margin({ top: 15 })
router.push({ uri: "pages/frescoImageTestCasePage" });
}).margin({ top: 15 })
Button("测试自定义控件FrescoImage重试Retry")
.onClick(() => {
router.push({ uri: "pages/frescoRetryTestCasePage" });
}).margin({ top: 15 })
router.push({ uri: "pages/frescoRetryTestCasePage" });
}).margin({ top: 15 })
}
}
.width('100%')
.height('100%')
}
}
}

View File

@ -13,20 +13,23 @@
* limitations under the License.
*/
import router from '@system.router';
import {Pngj} from '@ohos/imageknife'
import { Pngj } from '@ohos/imageknife'
import resourceManager from '@ohos.resourceManager';
import {FileUtils} from '@ohos/imageknife'
import { FileUtils } from '@ohos/imageknife'
import featureability from '@ohos.ability.featureAbility'
import ArkWorker from '@ohos.worker'
@Entry
@Component
struct PngjTestCasePage {
pngSource: ArrayBuffer = new ArrayBuffer(0);
pngSource: ArrayBuffer = new ArrayBuffer(0);
rootFolder: string = '';
@State hint1: string = 'readPngImageInfo内容展示'
@State hint2: string = 'readPngImage内容展示'
@State hint3: string = 'writePngWithString内容展示'
@State hint4: string = 'writePngWithString内容展示'
@State hint5: string = '测试readMetadata'
@State hint6: string = '测试writeMetadata'
build() {
Scroll() {
@ -36,25 +39,15 @@ struct PngjTestCasePage {
Button('点击获取Png图片buffer').fontSize(20)
.onClick(() => {
featureability.getContext()
.getFilesDir()
.then((data) => {
this.rootFolder = data;
})
.catch((err) => {
console.log('点击获取Png图片buffer 路径获取失败 err:' + err)
})
this.rootFolder = globalThis.ImageKnife.getImageKnifeContext().filesDir;
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.Tomato').id)
.then(data => {
this.pngSource = FileUtils.getInstance().uint8ArrayToBuffer(data);
})
.catch(err => {
console.log('点击获取Png图片buffer err=' + err)
})
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.Tomato').id)
.then(data => {
this.pngSource = FileUtils.getInstance().uint8ArrayToBuffer(data);
})
.catch(err => {
console.log('点击获取Png图片buffer err=' + err)
})
})
@ -103,6 +96,7 @@ struct PngjTestCasePage {
}).margin({ top: 5, left: 10 })
}.width('100%')
.height(60).backgroundColor(Color.Pink)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('测试readPngImageInfo')
.onClick(() => {
@ -114,7 +108,10 @@ struct PngjTestCasePage {
Button('测试readPngImageAsync')
.onClick(() => {
let pngj = new Pngj();
let worker = new ArkWorker.Worker('workers/worker1.js', { type: 'classic', name: 'readPngImageAsync'})
let worker = new ArkWorker.Worker('entry/ets/pages/workers/worker1.js', {
type: 'classic',
name: 'readPngImageAsync'
})
pngj.readPngImageAsync(worker, this.pngSource, (sender, value) => {
this.pngSource = sender
this.hint2 = 'img with=' + value.width + ' img height=' + value.height
@ -124,7 +121,10 @@ struct PngjTestCasePage {
Button('测试writePngWithStringAsync')
.onClick(() => {
let pngj = new Pngj();
let worker = new ArkWorker.Worker('workers/worker1.js', { type: 'classic', name: 'writePngWithStringAsync'})
let worker = new ArkWorker.Worker('entry/ets/pages/workers/worker1.js', {
type: 'classic',
name: 'writePngWithStringAsync'
})
pngj.writePngWithStringAsync(worker, 'hello world', this.pngSource, (sender, value) => {
this.pngSource = sender
FileUtils.getInstance().createFileProcess(
@ -138,7 +138,10 @@ struct PngjTestCasePage {
Button('测试writePngAsync')
.onClick(() => {
let pngj = new Pngj();
let worker = new ArkWorker.Worker('workers/worker1.js', { type: 'classic', name: 'writePngAsync'})
let worker = new ArkWorker.Worker('entry/ets/pages/workers/worker1.js', {
type: 'classic',
name: 'writePngAsync'
})
pngj.writePngAsync(worker, this.pngSource, (sender, value) => {
this.pngSource = sender
FileUtils.getInstance().createFileProcess(
@ -165,9 +168,9 @@ struct PngjTestCasePage {
.width('100%')
.height(120)
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
typedArrayToBuffer(array: Uint8Array): ArrayBuffer {

View File

@ -53,12 +53,12 @@ struct StorageTestDiskLruCache {
.backgroundColor(Color.Blue)
Button("替换ImageKnife默认DiskLruCache并设置大小1M")
.onClick(() => {
DiskImageKnife.replaceDiskLruCache(1 * 1024 * 1024)
globalThis.ImageKnife.replaceDiskLruCache(1 * 1024 * 1024)
}).margin({top:15, bottom:15})
Button("替换ImageKnife默认DiskLruCache并设置大小30M")
.onClick(() => {
DiskImageKnife.replaceDiskLruCache(30 * 1024 * 1024)
globalThis.ImageKnife.replaceDiskLruCache(30 * 1024 * 1024)
}).margin({top:15, bottom:15})
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
@ -170,19 +170,24 @@ struct StorageTestDiskLruCache {
request.addAllCacheInfoCallback(this.imageKnifeOption.allCacheInfoCallback)
}
DiskImageKnife.call(request);
globalThis.ImageKnife.call(request);
}
imageKnifeChangeSource(data:ImageKnifeData) {
this.imageKnifeSpecialFixed(data);
//查看mImageKnife中的DiskLruCache
let disk = DiskImageKnife.getDiskMemoryCache();
let showDisk = ''
disk.foreachDiskLruCache((value, key, map) => {
showDisk += "key=" + key + "&value=" + value;
})
this.logText = "日志结果:" + showDisk;
// 由于异步写入可能读取disklrucache的时候还没删成功为了保证成功删除这里使用了延时
setTimeout(() => {
//查看mImageKnife中的DiskLruCache
let disk = globalThis.ImageKnife.getDiskMemoryCache();
let showDisk = ''
disk.foreachDiskLruCache((value, key, map) => {
showDisk += "key=" + key + "&value=" + value;
})
this.logText = "日志结果:" + showDisk;
}, 2000)
}
imageKnifeSpecialFixed(data:ImageKnifeData) {
@ -226,7 +231,7 @@ struct StorageTestDiskLruCache {
console.log("ImageKnife占位图输出=String 拥有上一个图片类型 上一个是SVG")
this.normalPixelMap = false;
this.normalResource = false;
let firstIndex = (data.imageKnifeValue as string).indexOf(DiskImageKnife.getSvgAndGifFolder());
let firstIndex = (data.imageKnifeValue as string).indexOf(globalThis.ImageKnife.getSvgAndGifFolder());
console.log("firstIndex=" + firstIndex);
let suffix = (data.imageKnifeValue as string).substring(firstIndex, (data.imageKnifeValue as string).length)
console.log("suffix =" + suffix);
@ -238,7 +243,7 @@ struct StorageTestDiskLruCache {
this.normalPixelMap = false;
this.normalResource = false;
let firstIndex = (data.imageKnifeValue as string).indexOf(DiskImageKnife.getSvgAndGifFolder());
let firstIndex = (data.imageKnifeValue as string).indexOf(globalThis.ImageKnife.getSvgAndGifFolder());
console.log("firstIndex=" + firstIndex);
let suffix = (data.imageKnifeValue as string).substring(firstIndex, (data.imageKnifeValue as string).length)
console.log("suffix =" + suffix);
@ -280,7 +285,7 @@ struct StorageTestDiskLruCache {
console.log("ImageKnife占位图输出=String 没有上一个图片类型")
this.normalPixelMap = false;
this.normalResource = false;
let firstIndex = (data.imageKnifeValue as string).indexOf(DiskImageKnife.getSvgAndGifFolder());
let firstIndex = (data.imageKnifeValue as string).indexOf(globalThis.ImageKnife.getSvgAndGifFolder());
console.log("firstIndex=" + firstIndex);
let suffix = (data.imageKnifeValue as string).substring(firstIndex, (data.imageKnifeValue as string).length)
console.log("suffix =" + suffix);
@ -318,4 +323,3 @@ struct StorageTestDiskLruCache {
}
}
var DiskImageKnife = globalThis.exports.default.data.imageKnife

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import featureAbility from '@ohos.ability.featureAbility';
import {LruCache} from '@ohos/imageknife'
function getRandomInt(min, max) {

View File

@ -207,4 +207,4 @@ struct TestAllCacheInfoPage {
}
var ImageKnife = globalThis.exports.default.data.imageKnife
var ImageKnife = globalThis.ImageKnife

View File

@ -31,17 +31,17 @@ struct TestGifDontAnimatePage {
build() {
Scroll() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Flex({direction:FlexDirection.Row}){
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('本地资源gif')
.onClick(()=>{
this.imageKnifeOption1 = {
loadSrc: $r('app.media.gifSample'),
size: { width: 300, height: 300 },
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
margin:{left:15,top:15,right:15,bottom:15}
}
.onClick(() => {
this.imageKnifeOption1 = {
loadSrc: $r('app.media.gifSample'),
size: { width: 300, height: 300 },
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
margin: { left: 15, top: 15, right: 15, bottom: 15 }
}
}).margin({left:15}).backgroundColor(Color.Grey)
Button('本地资源gif静态')
@ -95,5 +95,4 @@ struct TestGifDontAnimatePage {
}
}
var ImageKnife = globalThis.exports.default.data.imageKnife
var ImageKnife = globalThis.ImageKnife

View File

@ -105,4 +105,3 @@ struct TestImageKnifeOptionChangedPage2 {
}
var ImageKnife = globalThis.exports.default.data.imageKnife

View File

@ -23,7 +23,10 @@ struct TestMultiThreadWorkerPage2 {
Button("创建Worker向子线程发送携带Arraybuffer数据")
.margin({ top: 20 })
.onClick(() => {
let worker = new ArkWorker.Worker("workers/worker1.js", { type: "classic", name: "zhangsan" })
let worker = new ArkWorker.Worker("entry/ets/pages/workers/worker1.js", {
type: "classic",
name: "zhangsan"
})
worker.onerror = function (data) {
console.info("worker:: receive onerror " + data.lineno + ", msg = " + data.message + ", filename = " + data.filename + ", colno = " + data.colno);
}

View File

@ -15,7 +15,7 @@
import {ImageKnifeComponent} from '@ohos/imageknife'
import {ImageKnifeOption} from '@ohos/imageknife'
import {RequestOption} from '@ohos/imageknife'
import {RotateImageTransformation} from '@ohos/imageknife'
@Entry
@Component
@ -72,18 +72,18 @@ struct TestPreloadPage {
build() {
Scroll() {
Flex({ direction: FlexDirection.Column }) {
Flex({ direction: FlexDirection.Column }) {
Column() {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源gif')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.gifSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源gif 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.gifSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源gif 出现错误! err=' + err)
} else {
console.log('预加载本地资源gif成功! imageKnifedata=' + JSON.stringify(data))
}
return false;
@ -216,17 +216,17 @@ struct TestPreloadPage {
}
Flex({ direction: FlexDirection.Column }) {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源svg')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.svgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源svg 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.svgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源svg 出现错误! err=' + err)
} else {
console.log('预加载本地资源svg成功! imageKnifedata=' + JSON.stringify(data))
}
return false;
@ -296,17 +296,17 @@ struct TestPreloadPage {
}
Flex({ direction: FlexDirection.Column }) {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源webp')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源webp 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源webp 出现错误! err=' + err)
} else {
console.log('预加载本地资源webp成功! imageKnifedata=' + JSON.stringify(data))
}
return false;
@ -374,17 +374,17 @@ struct TestPreloadPage {
}
Flex({ direction: FlexDirection.Column }) {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源bmp')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.bmpSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源bmp 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.bmpSample'))
.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;
@ -452,17 +452,17 @@ struct TestPreloadPage {
}
Flex({ direction: FlexDirection.Column }) {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源png')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.pngSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源png 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.pngSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源png 出现错误! err=' + err)
} else {
console.log('预加载本地资源png成功! imageKnifedata=' + JSON.stringify(data))
}
return false;
@ -530,17 +530,17 @@ struct TestPreloadPage {
}
Flex({ direction: FlexDirection.Column }) {
Column() {
Flex({ direction: FlexDirection.Row }) {
Button('预加载本地资源jpg')
.onClick(() => {
let request = new RequestOption();
request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源jpg 出现错误! err=' + err)
} else {
let request = new RequestOption();
request.load($r('app.media.jpgSample'))
.setImageViewSize({ width: 300, height: 300 })
.addListener((err, data) => {
if (err && err.length > 0) {
console.log('预加载本地资源jpg 出现错误! err=' + err)
} else {
console.log('预加载本地资源jpg成功! imageKnifedata=' + JSON.stringify(data))
}
return false;
@ -608,9 +608,11 @@ struct TestPreloadPage {
}
}
}
.width('100%')
.height('100%')
}
aboutToAppear() {
@ -619,4 +621,4 @@ struct TestPreloadPage {
}
var ImageKnife = globalThis.exports.default.data.imageKnife
var ImageKnife = globalThis.ImageKnife

View File

@ -36,9 +36,7 @@ struct TestResourceManagerPage {
.height(300)
Button("点击执行ResourceManager的Base64")
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMediaBase64($r('app.media.jpgSample').id)
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMediaBase64($r('app.media.jpgSample').id)
.then(data => {
console.log("jpgSample data=" + data)
let matchUseLess = ";base64,";
@ -55,15 +53,11 @@ struct TestResourceManagerPage {
this.imageKnifeData = newImageKnifeData;
})
})
})
Button("点击执行ResourceManager的非Base64")
.margin({top:25})
.onClick(()=>{
resourceManager.getResourceManager()
.then(result => {
result.getMedia($r('app.media.pngSample').id)
globalThis.ImageKnife.getImageKnifeContext().resourceManager.getMedia($r('app.media.pngSample').id)
.then(data => {
console.log("arrayBuffer data=" + data)
let fileTypeUtil = new FileTypeUtil();
@ -73,8 +67,6 @@ struct TestResourceManagerPage {
newImageKnifeData.imageKnifeType = typeValue
this.imageKnifeData = newImageKnifeData;
})
})
})
}
}

View File

@ -12,17 +12,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {RequestOption} from '@ohos/imageknife'
import {CropCircleWithBorderTransformation} from '@ohos/imageknife/src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation'
import {RotateImageTransformation} from '@ohos/imageknife'
import {CropSquareTransformation} from '@ohos/imageknife'
import {CropTransformation} from '@ohos/imageknife'
import {CropType} from '@ohos/imageknife'
import {GrayscaleTransformation} from '@ohos/imageknife'
import {BrightnessFilterTransformation} from '@ohos/imageknife'
import {ContrastFilterTransformation} from '@ohos/imageknife'
import {InvertFilterTransformation} from '@ohos/imageknife'
import {SepiaFilterTransformation} from '@ohos/imageknife'
import { RequestOption } from '@ohos/imageknife'
import { CropCircleTransformation } from '@ohos/imageknife'
import { RoundedCornersTransformation } from '@ohos/imageknife'
import {
CropCircleWithBorderTransformation
} from '@ohos/imageknife/src/main/ets/components/imageknife/transform/CropCircleWithBorderTransformation'
import { RotateImageTransformation } from '@ohos/imageknife'
import { CropSquareTransformation } from '@ohos/imageknife'
import { CropTransformation } from '@ohos/imageknife'
import { CropType } from '@ohos/imageknife'
import { GrayscaleTransformation } from '@ohos/imageknife'
import { BrightnessFilterTransformation } from '@ohos/imageknife'
import { ContrastFilterTransformation } from '@ohos/imageknife'
import { InvertFilterTransformation } from '@ohos/imageknife'
import { SepiaFilterTransformation } from '@ohos/imageknife'
import {SketchFilterTransformation} from '@ohos/imageknife'
import {BlurTransformation} from '@ohos/imageknife'
import {PixelationFilterTransformation} from '@ohos/imageknife'
@ -874,4 +878,4 @@ struct TransformPixelMapPage {
}
}
var ImageKnife = globalThis.exports.default.data.imageKnife
var ImageKnife = globalThis.ImageKnife

View File

@ -13,9 +13,16 @@
* limitations under the License.
*/
import arkWorker from '@ohos.worker';
import {handler} from '@ohos/imageknife/src/main/ets/components/imageknife/pngj/PngWork'
arkWorker.parentPort.onmessage = handler

View File

@ -0,0 +1,40 @@
{
"module": {
"name": "entry",
"type": "entry",
"srcEntrance": "./ets/Application/AbilityStage.ts",
"description": "$string:entry_desc",
"mainElement": "MainAbility",
"deviceTypes": [
"default",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"requestPermissions": [{"name": "ohos.permission.INTERNET"}],
"uiSyntax": "ets",
"abilities": [
{
"name": "MainAbility",
"srcEntrance": "./ets/MainAbility/MainAbility.ts",
"description": "$string:MainAbility_desc",
"icon": "$media:icon",
"label": "$string:MainAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:test_color",
"visible": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
]
}
}

View File

@ -1,5 +1,18 @@
{
"string": [
{
"name": "entry_desc",
"value": "description"
},
{
"name": "MainAbility_desc",
"value": "description"
},
{
"name": "MainAbility_label",
"value": "ImageKnife"
},
{
"name": "ImageKnife_OHOS",
"value": "ImageKnife_OHOS"

View File

@ -0,0 +1,33 @@
{
"src": [
"pages/index",
"pages/indexFresco",
"pages/frescoLayerTestCasePage",
"pages/frescoImageTestCasePage",
"pages/frescoRetryTestCasePage",
"pages/basicTestFeatureAbilityPage",
"pages/basicTestFileIOPage",
"pages/basicTestMediaImage",
"pages/basicTestResourceManagerPage",
"pages/storageTestLruCache",
"pages/storageTestDiskLruCache",
"pages/transformTestCasePage",
"pages/pngjTestCasePage",
"pages/testAllTypeImageKnifeComponentPage",
"pages/testAllTypeNativeImagePage",
"pages/loadResourceTestCasePage",
"pages/loadNetworkTestCasePage",
"pages/showErrorholderTestCasePage",
"pages/transformPixelMapPage",
"pages/testGifDontAnimatePage",
"pages/testPreloadPage",
"pages/testImageKnifeOptionChangedPage",
"pages/testImageKnifeOptionChangedPage2",
"pages/compressPage",
"pages/testAllCacheInfoPage",
"pages/testResourceManagerPage",
"pages/testMultiThreadWorkerPage2",
"pages/cropImagePage",
"pages/cropImagePage2"
]
}

View File

@ -1,68 +0,0 @@
{
"app": {
"bundleName": "com.example.imageknifegiteepro",
"vendor": "example",
"version": {
"code": 1000000,
"name": "1.0.0"
}
},
"deviceConfig": {},
"module": {
"package": "com.example.entry_test",
"name": ".entry_test",
"mainAbility": ".TestAbility",
"srcPath": "",
"deviceType": [
"phone",
"tablet"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "entry_test",
"moduleType": "feature",
"installationFree": false
},
"abilities": [
{
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"orientation": "unspecified",
"visible": true,
"srcPath": "TestAbility",
"name": ".TestAbility",
"srcLanguage": "ets",
"icon": "$media:icon",
"description": "$string:description_TestAbility",
"formsEnabled": false,
"label": "$string:entry_TestAbility",
"type": "page",
"launchType": "standard"
}
],
"js": [
{
"mode": {
"syntax": "ets",
"type": "pageAbility"
},
"pages": [
"pages/index"
],
"name": ".TestAbility",
"window": {
"designWidth": 720,
"autoDesignWidth": false
}
}
]
}
}

View File

@ -0,0 +1,21 @@
/*
* Copyright (C) 2022 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 AbilityStage from "@ohos.application.AbilityStage"
export default class TestAbilityStage extends AbilityStage {
onCreate() {
console.log("[Demo] TestAbilityStage onCreate")
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2022 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 Ability from '@ohos.application.Ability'
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
import { Hypium } from 'hypium/index'
import testsuite from '../test/List.test'
export default class TestAbility extends Ability {
onCreate(want, launchParam) {
console.log('TestAbility onCreate')
var abilityDelegator: any
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var abilityDelegatorArguments: any
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
console.info('start run testcase!!!')
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
}
onDestroy() {
console.log('TestAbility onDestroy')
}
onWindowStageCreate(windowStage) {
console.log('TestAbility onWindowStageCreate')
windowStage.setUIContent(this.context, 'TestAbility/pages/index', null)
globalThis.abilityContext = this.context;
}
onWindowStageDestroy() {
console.log('TestAbility onWindowStageDestroy')
}
onForeground() {
console.log('TestAbility onForeground')
}
onBackground() {
console.log('TestAbility onBackground')
}
};

View File

@ -1,32 +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 AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
import { Hypium } from 'hypium/index'
import testsuite from '../test/List.test'
export default {
onCreate() {
console.info('Application onCreate')
var abilityDelegator: any
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var abilityDelegatorArguments: any
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
console.info('start run testcase!!!')
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
},
onDestroy() {
console.info('Application onDestroy')
},
}

View File

@ -1,18 +1,18 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* Copyright (C) 2022 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,
* 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 router from '@system.router';
import router from '@ohos.router';
@Entry
@Component
@ -20,7 +20,6 @@ struct Index {
aboutToAppear() {
console.info('TestAbility index aboutToAppear')
}
@State message: string = 'Hello World'
build() {
Row() {

View File

@ -1,13 +1,13 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* Copyright (C) 2022 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,
* 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.
@ -20,25 +20,24 @@ var abilityDelegatorArguments = undefined
function translateParamsToString(parameters) {
const keySet = new Set([
'-s class', '-s notClass', '-s suite', '-s itName',
'-s level', '-s testType', '-s size', '-s timeout',
'-s package'
'-s class', '-s notClass', '-s suite', '-s it',
'-s level', '-s testType', '-s size', '-s timeout'
])
let targetParams = '';
for (const key in parameters) {
if (keySet.has(key)) {
targetParams += ' ' + key + ' ' + parameters[key]
targetParams = `${targetParams} ${key} ${parameters[key]}`
}
}
return targetParams.trim()
}
async function onAbilityCreateCallback() {
console.log('onAbilityCreateCallback');
console.log("onAbilityCreateCallback");
}
async function addAbilityMonitorCallback(err: any) {
console.info('addAbilityMonitorCallback : ' + JSON.stringify(err))
console.info("addAbilityMonitorCallback : " + JSON.stringify(err))
}
export default class OpenHarmonyTestRunner implements TestRunner {
@ -46,21 +45,20 @@ export default class OpenHarmonyTestRunner implements TestRunner {
}
onPrepare() {
console.info('OpenHarmonyTestRunner OnPrepare')
console.info("OpenHarmonyTestRunner OnPrepare ")
}
onRun() {
async onRun() {
console.log('OpenHarmonyTestRunner onRun run')
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments()
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator()
var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility'
let lMonitor = {
abilityName: testAbilityName,
onAbilityCreate: onAbilityCreateCallback,
};
var testAbilityName = abilityDelegatorArguments.parameters['-p'] + '.TestAbility'
abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback)
var cmd = 'aa start -d 0 -a ' + testAbilityName + ' -b ' + abilityDelegatorArguments.bundleName
var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName
cmd += ' '+translateParamsToString(abilityDelegatorArguments.parameters)
console.info('cmd : '+cmd)
abilityDelegator.executeShellCommand(cmd,
@ -69,9 +67,6 @@ export default class OpenHarmonyTestRunner implements TestRunner {
console.info('executeShellCommand : data : ' + d.stdResult);
console.info('executeShellCommand : data : ' + d.exitCode);
})
console.info('OpenHarmonyTestRunner onRun call abilityDelegator.getAppContext')
var context = abilityDelegator.getAppContext()
console.info('getAppContext : ' + JSON.stringify(context))
console.info('OpenHarmonyTestRunner onRun end')
}
};

View File

@ -1,13 +1,13 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* Copyright (C) 2022 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,
* 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.

View File

@ -1,13 +1,13 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the 'License');
* Copyright (C) 2022 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,
* 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.

View File

@ -0,0 +1,37 @@
{
"module": {
"name": "entry_test",
"type": "feature",
"srcEntrance": "./ets/TestAbility/TestAbility.ts",
"description": "$string:entry_test_desc",
"mainElement": "TestAbility",
"deviceTypes": [
"default",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:test_pages",
"uiSyntax": "ets",
"abilities": [
{
"name": "TestAbility",
"srcEntrance": "./ets/TestAbility/TestAbility.ts",
"description": "$string:TestAbility_desc",
"icon": "$media:icon",
"label": "$string:TestAbility_label",
"visible": true,
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
]
}
]
}
}

View File

@ -0,0 +1,8 @@
{
"color": [
{
"name": "white",
"value": "#FFFFFF"
}
]
}

View File

@ -1,12 +1,16 @@
{
"string": [
{
"name": "description_TestAbility",
"value": "eTS_Empty Ability"
"name": "entry_test_desc",
"value": "i am an entry for tv"
},
{
"name": "entry_TestAbility",
"value": "entry_TestAbility"
"name": "TestAbility_desc",
"value": "the tv entry test ability"
},
{
"name": "TestAbility_label",
"value": "tvBase"
}
]
}

View File

@ -0,0 +1,5 @@
{
"src": [
"TestAbility/pages/index"
]
}

View File

@ -1,2 +1,2 @@
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').legacyAppTasks
module.exports = require('@ohos/hvigor-ohos-plugin').appTasks

View File

@ -1,5 +1,5 @@
{
"apiType": "faMode",
"apiType": "stageMode",
"buildOption": {
}
}

View File

@ -1,3 +1,3 @@
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').legacyHarTasks
module.exports = require('@ohos/hvigor-ohos-plugin').harTasks

View File

@ -22,7 +22,6 @@ export * from './src/main/ets/components/cache/FileUtils'
export * from './src/main/ets/components/cache/Md5'
export * from './src/main/ets/components/cache/Base64'
export * from './src/main/ets/components/cache/LruCache'
export * from './src/main/ets/components/cache/DiskLruCache'
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'
@ -48,6 +47,8 @@ export * from './src/main/ets/components/imageknife/compress/provider/RecoursePr
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'
/**
* transform
@ -82,6 +83,8 @@ export * from './src/main/ets/components/imageknife/pngj/Pngj'
export {handler} from './src/main/ets/components/imageknife/pngj/PngWork'
export * from './src/main/ets/components/imageknife/pngj/UPNG'
/**
* ImageKnife
*/

View File

@ -1,13 +0,0 @@
{
"name": "@ohos/imageknife",
"version": "1.0.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"pako": {
"version": "1.0.11",
"resolved": "http://mirrors.tools.huawei.com/npm/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="
}
}
}

View File

@ -1,27 +1,29 @@
{
"types": "",
"keywords": [
"types":"",
"keywords":[
"OpenHarmony",
"ImageKnife",
"glide"
],
"author": "ohos_tpc",
"description": "专门为OpenHarmony打造的一款图像加载缓存库致力于更高效、更轻便、更简单",
"ohos": {
"org": "opensource"
"author":"ohos_tpc",
"description":"专门为OpenHarmony打造的一款图像加载缓存库致力于更高效、更轻便、更简单",
"ohos":{
"org":"opensource"
},
"main": "index.ets",
"repository": "https://gitee.com/openharmony-tpc/ImageKnife",
"version": "1.0.2",
"dependencies": {
"pako": "^1.0.5"
"main":"index.ets",
"repository":"https://gitee.com/openharmony-tpc/ImageKnife",
"version":"1.0.2",
"dependencies":{
"pako":"^1.0.5",
"@ohos/disklrucache":"file:../disklrucache",
"crc-32":"^1.2.0"
},
"tags": [
"tags":[
"OpenHarmony",
"ImageKnife",
"glide"
],
"license": "Apache License 2.0",
"devDependencies": {},
"name": "@ohos/imageknife"
}
"license":"Apache License 2.0",
"devDependencies":{},
"name":"@ohos/imageknife"
}

View File

@ -1,24 +0,0 @@
{
"app": {
"bundleName": "cn.openharmony.imageknife",
"vendor": "openharmony",
"version": {
"code": 1000000,
"name": "1.0.0"
}
},
"deviceConfig": {},
"module": {
"package": "cn.openharmony.imageknife",
"deviceType": [
"phone",
"tablet"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "imageknife",
"moduleType": "har"
},
"uiSyntax": "ets"
}
}

View File

@ -1,318 +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 {CustomMap} from './CustomMap'
import {FileUtils} from './FileUtils'
import {FileReader} from './FileReader'
import {DiskCacheEntry} from './DiskCacheEntry'
import fileio from '@ohos.fileio';
import featureability from '@ohos.ability.featureAbility'
import {Md5} from './Md5'
export class DiskLruCache {
// 缓存数据集合
cacheMap: CustomMap<string, DiskCacheEntry> = new CustomMap<string, DiskCacheEntry>()
fileUtils: FileUtils = FileUtils.getInstance()
diskCacheFolder: string = 'ImageKnifeDiskCache'
// 缓存文件路劲地址
dirPath: string= ''
// 缓存数据最大值
maxSize: number = 30 * 1024 * 1024
// 当前缓存数据值
size: number = 0
// 缓存journal文件名称
journal: string = 'journal'
// 缓存journal备份文件名称
journalTemp: string = 'journal_temp'
// 缓存journal文件路径
journalPath: string = ''
// 缓存journal备份文件路径
journalPathTemp: string = ''
constructor(maxSize: number, direction?: string) {
if (maxSize > 0) {
this.maxSize = maxSize
}
if (!this.isNull(direction)) {
if (direction.endsWith('/')) {
this.dirPath = direction
} else {
this.dirPath = direction + '/'
}
} else {
featureability.getContext()
.getFilesDir()
.then((data) => {
console.log('DiskLruCache - FileDir= ' + data)
let dirPathFolder = data + '/' + this.diskCacheFolder
this.dirPath = dirPathFolder;
FileUtils.getInstance()
.createFolder(dirPathFolder)
this.init()
})
.catch((error) => {
console.log('DiskLruCache FileDir Error Cause:' + error.message);
})
}
}
/**
* 初始化缓存文件
*/
private init() {
if (this.dirPath.endsWith('/')) {
this.dirPath = this.dirPath
} else {
this.dirPath = this.dirPath + '/'
}
this.journalPath = this.dirPath + this.journal
this.journalPathTemp = this.dirPath + this.journalTemp
try {
var stat = fileio.statSync(this.journalPath)
if (stat.isFile() && stat.size > 0) {
this.fileUtils.createFile(this.journalPathTemp)
this.fileUtils.copyFile(this.journalPath, this.journalPathTemp)
this.readJournal(this.journalPathTemp)
this.resetJournalFile()
} else {
this.fileUtils.createFile(this.journalPath)
}
} catch (e) {
console.log('DiskLruCache - init e ' + e)
this.fileUtils.createFile(this.journalPath)
}
}
/**
* 重置journal文件数据
*/
resetJournalFile(){
this.fileUtils.clearFile(this.journalPath)
for(let key of this.cacheMap.keys()){
this.fileUtils.writeData(this.journalPath, 'save ' + key + '\n')
}
}
/**
* 读取journal文件的缓存数据
*/
readJournal(path: string) {
var fileReader = new FileReader(path)
var line: string = ''
while (!fileReader.isEnd()) {
line = fileReader.readLine()
line = line.replace('\n', '').replace('\r', '')
this.dealwithJournal(line)
}
this.fileUtils.deleteFile(this.journalPathTemp)
this.trimToSize()
}
/**
* 处理journal文件数据
*/
dealwithJournal(line: string) {
var picPath = ''
try {
var datas = line.split(' ')
if (datas.length > 1) {
if (datas[0] != 'remove') {
picPath = this.dirPath + datas[1]
var picstat = fileio.statSync(picPath)
if (picstat.isFile() && picstat.size > 0) {
this.size = this.size + picstat.size
this.fileUtils.writeData(this.journalPath, line + '\n')
this.putCacheMap(datas[1], picstat.size)
}
} else {
if (this.cacheMap.hasKey(datas[1])) {
var cacheEntry: DiskCacheEntry = this.cacheMap.get(datas[1])
this.size = this.size - cacheEntry.getLength()
this.cacheMap.remove(datas[1])
}
}
}
} catch (e) {
console.log('DiskLruCache - dealwithJournal e = ' + e)
}
}
/**
* 设置disk缓存最大数据值
*/
setMaxSize(max: number) {
this.maxSize = max
this.trimToSize()
}
/**
* 缓存数据map集合
*/
private putCacheMap(key: string, length?: number) {
if (this.cacheMap.hasKey(key)) {
this.cacheMap.remove(key)
}
if (length > 0) {
this.cacheMap.put(key, new DiskCacheEntry(key, length))
} else {
this.cacheMap.put(key, new DiskCacheEntry(key))
}
}
/**
* 存储disk缓存数据
*/
putCacheData(key: string, content?: ArrayBuffer, path?: string) {
if (key == null) {
throw new Error('key is null,checking the parameter');
}
var fileSize = 0
var isvalid: boolean = false
key = Md5.hashStr(key)
if (content != null && content.byteLength > 0) {
isvalid = true
var tempPath = this.dirPath + key
fileSize = content.byteLength
this.fileUtils.writePic(tempPath, content)
}
if (!this.isNull(path) && this.fileUtils.exist(path)) {
isvalid = true
fileSize = this.fileUtils.getFileSize(path)
this.fileUtils.copyFile(path, this.dirPath + key)
}
if (isvalid) {
this.size = this.size + fileSize
this.putCacheMap(key, fileSize)
this.fileUtils.writeData(this.journalPath, 'save ' + key + '\n')
this.trimToSize()
} else {
throw ('putCacheData() key or content or path is invalid')
}
}
/**
* 根据LRU算法删除多余缓存数据
*/
private trimToSize() {
while (this.size > this.maxSize) {
var tempkey: string = this.cacheMap.getFirstKey()
var fileSize = this.fileUtils.getFileSize(this.dirPath + tempkey)
if (fileSize > 0) {
this.size = this.size - fileSize
}
this.fileUtils.deleteFile(this.dirPath + tempkey)
this.cacheMap.remove(tempkey)
this.fileUtils.writeData(this.journalPath, 'remove ' + tempkey + '\n')
}
}
/**
* 获取key缓存数据
*/
getCacheDataByKey(key: string): ArrayBuffer{
if (key == null) {
throw new Error('key is null,checking the parameter');
}
key = Md5.hashStr(key)
var path = this.dirPath + key;
if (this.fileUtils.exist(path)) {
var ab: ArrayBuffer = this.fileUtils.readFilePic(path)
this.putCacheMap(key, ab.byteLength)
this.fileUtils.writeData(this.journalPath, 'read ' + key + '\n')
return ab
} else {
return null;
}
}
/**
* 获取key缓存数据绝对路径
*/
getCacheFileByKey(key: string): string{
if (key == null) {
throw new Error('key is null,checking the parameter');
}
key = Md5.hashStr(key)
if (this.dirPath.endsWith('/')) {
this.dirPath = this.dirPath
} else {
this.dirPath = this.dirPath + '/'
}
var path = this.dirPath + key;
if (this.fileUtils.exist(path)) {
this.fileUtils.writeData(this.journalPath, 'read ' + key + '\n')
return path
} else {
return null
}
}
/**
* 删除key缓存数据
*/
deleteCacheDataBykey(key: string): DiskCacheEntry{
if (key == null) {
throw new Error('key is null,checking the parameter');
}
key = Md5.hashStr(key)
var path = this.dirPath + key;
if (this.fileUtils.exist(path)) {
var ab = this.fileUtils.readFilePic(path)
this.size = this.size - ab.byteLength
this.cacheMap.remove(key)
this.fileUtils.writeData(this.journalPath, 'remove ' + key + '\n')
this.fileUtils.deleteFile(path)
}
return this.cacheMap.get(key)
}
/**
* 清除所有disk缓存数据
*/
cleanCacheData() {
var length = this.cacheMap.size()
for (var index = 0; index < length; index++) {
this.fileUtils.deleteFile(this.dirPath + this.cacheMap[index])
}
this.fileUtils.deleteFile(this.journalPath)
this.cacheMap.clear()
this.size = 0
}
/**
* 空字符串判断
*/
private isNull(str: string): boolean{
if (!str || Object.keys(str).length == 0) {
return true
} else {
return false
}
}
foreachDiskLruCache(fn){
this.cacheMap.each(fn)
}
}

View File

@ -179,26 +179,6 @@ export class FileUtils {
}
}
/**
* 读取media的资源文件
*/
readMediaPic() {
resmgr.getResourceManager()
.then(result => {
result.getMediaBase64($r('app.media.icon')
.id)
.then(data => {
console.error("FileUtils - readPic data = " + data)
data = data.replace("data:image/png;base64,", "")
console.error("FileUtils - readPic this.data = " + data)
this.base64Str = data
console.error("FileUtils - readPic this.base64Str = " + this.base64Str)
})
.catch(err => {
console.log("FileUtils - readPic err" + JSON.stringify(err));
})
})
}
/**
* stream式读取

View File

@ -12,9 +12,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import{DiskStrategy} from '../../diskstrategy/DiskStrategy'
import{DataSrc} from '../../diskstrategy/DataSrc'
import{EncodeStrategy} from '../../diskstrategy/EncodeStrategy'
import { DiskStrategy } from '../../diskstrategy/DiskStrategy'
import { DataSrc } from '../../diskstrategy/DataSrc'
import { EncodeStrategy } from '../../diskstrategy/EncodeStrategy'
export class ALL implements DiskStrategy {
getName(): string{

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
import {DiskLruCache} from "../cache/DiskLruCache"
import {LruCache} from "../cache/LruCache"
import { DiskLruCache } from "@ohos/disklrucache"
import { LruCache } from "../cache/LruCache"
import {EngineKeyFactories} from "../cache/key/EngineKeyFactories"
import {RequestOption} from "../imageknife/RequestOption"
import {AsyncCallback} from "../imageknife/interface/asynccallback"
@ -35,6 +35,8 @@ import featureAbility from '@ohos.ability.featureAbility';
import {CompressBuilder} from "../imageknife/compress/CompressBuilder"
export class ImageKnife {
static readonly SEPARATOR: string = '/'
private imageKnifeContext;
private memoryCache: LruCache<string, any>;
private diskMemoryCache: DiskLruCache;
private dataFetch: IDataFetch;
@ -46,17 +48,47 @@ export class ImageKnife {
private runningRequest: Array<RequestOption>;
private pendingRequest: Array<RequestOption>;
private fileTypeUtil: FileTypeUtil; // 通用文件格式辨别
private diskCacheFolder: string = "ImageKnifeDiskCache"
private svgAndGifFolder: string = "svgAndGifFolder"; // svg和gif的文件路径地址
private svgAndGifCommitFile: string = "svgAndGifCommitFile" // svg和gif提交记录
private defaultListener:AsyncCallback<ImageKnifeData>; // 全局监听器
private defaultListener: AsyncCallback<ImageKnifeData>; // 全局监听器
private constructor(imgCtx) {
this.imageKnifeContext = imgCtx;
// 构造方法传入size 为保存文件个数
this.memoryCache = new LruCache<string, any>(100);
// 创建disk缓存 传入的size 为多少比特 比如20KB 传入20*1024
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext.filesDir + ImageKnife.SEPARATOR + this.diskCacheFolder, 30 * 1024 * 1024);
// 创建网络下载能力
this.dataFetch = new DownloadClient();
// 创建本地数据解析能力
this.resourceFetch = new ParseResClient();
// 初始化本地 文件保存
this.filesPath = this.imageKnifeContext.filesDir;
this.initSvgAndGifEnvironment();
this.runningRequest = new Array();
this.pendingRequest = new Array();
// 通用文件格式识别初始化
this.fileTypeUtil = new FileTypeUtil();
}
getMemoryCache(): LruCache<string, any>{
return this.memoryCache;
}
setMemoryCache(lrucache: LruCache<string, any>){
this.memoryCache = lrucache;
public static with(context): ImageKnife{
if (!this.sInstance) {
this.sInstance = new ImageKnife(context);
}
return this.sInstance;
}
getDiskMemoryCache(): DiskLruCache{
@ -81,46 +113,18 @@ export class ImageKnife {
this.svgAndGifFolder = folderPath;
}
getDefaultListener(){
getImageKnifeContext() {
return this.imageKnifeContext;
}
setMemoryCache(lrucache: LruCache<string, any>) {
this.memoryCache = lrucache;
}
getDefaultListener() {
return this.defaultListener;
}
setDefaultListener(newDefaultListener:AsyncCallback<ImageKnifeData>){
this.defaultListener = newDefaultListener;
}
private constructor() {
// 构造方法传入size 为保存文件个数
this.memoryCache = new LruCache<string, any>(100);
// 创建disk缓存 传入的size 为多少比特 比如20KB 传入20*1024
this.diskMemoryCache = new DiskLruCache(30 * 1024 * 1024);
// 创建网络下载能力
this.dataFetch = new DownloadClient();
// 创建本地数据解析能力
this.resourceFetch = new ParseResClient();
// 初始化本地 文件保存
featureAbility.getContext()
.getFilesDir()
.then((data) => {
this.filesPath = data
this.initSvgAndGifEnvironment();
})
.catch((error) => {
console.error('ImageKnife Failed to obtain the filesPath directory. Cause:' + error.message);
})
this.runningRequest = new Array();
this.pendingRequest = new Array();
// 通用文件格式识别初始化
this.fileTypeUtil = new FileTypeUtil();
}
private initSvgAndGifEnvironment() {
let folderExist = FileUtils.getInstance().existFolder(this.filesPath + "/" + this.svgAndGifFolder)
let fileExist =
@ -149,11 +153,8 @@ export class ImageKnife {
private static sInstance: ImageKnife;
public static with(): ImageKnife{
if (!this.sInstance) {
this.sInstance = new ImageKnife();
}
return this.sInstance;
setDefaultListener(newDefaultListener: AsyncCallback<ImageKnifeData>) {
this.defaultListener = newDefaultListener;
}
public compressBuilder(): CompressBuilder{
@ -178,15 +179,15 @@ export class ImageKnife {
}
// 替代原来的DiskLruCache
public replaceDiskLruCache(size:number){
this.diskMemoryCache = new DiskLruCache(size);
public replaceDiskLruCache(size:number) {
// this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext.filesDir+ImageKnife.SEPARATOR+this.diskCacheFolder, size);
if(this.diskMemoryCache.cacheMap.size() <= 0) {
this.diskMemoryCache = new DiskLruCache(size);
}else{
let newDiskLruCache = new DiskLruCache(size);
if (this.diskMemoryCache.getCacheMap().size() <= 0) {
this.diskMemoryCache = DiskLruCache.create(this.imageKnifeContext.filesDir + ImageKnife.SEPARATOR + this.diskCacheFolder, size);
} else {
let newDiskLruCache = DiskLruCache.create(this.imageKnifeContext.filesDir + ImageKnife.SEPARATOR + this.diskCacheFolder, size);
this.diskMemoryCache.foreachDiskLruCache(function (value, key, map) {
newDiskLruCache.putCacheData(key, value, null);
newDiskLruCache.set(key, value);
})
this.diskMemoryCache = newDiskLruCache;
}

View File

@ -178,23 +178,11 @@ export struct ImageKnifeComponent {
}
// imageknife 第一次启动和数据刷新后重新发送请求
imageKnifeExecute() {
if(ImageKnife){
}else{
ImageKnife = globalThis.exports.default.data.imageKnife;
}
if(ImageKnife){
}else{
console.log('ImageKnife Singleton Initialization Not Completed!')
}
let request = new RequestOption();
this.configNecessary(request);
this.configCacheStrategy(request);
this.configDisplay(request);
ImageKnife.call(request);
globalThis.ImageKnife.call(request);
}
imageKnifeChangeSource(data:ImageKnifeData) {
@ -341,8 +329,7 @@ export struct ImageKnifeComponent {
}
}
var ImageKnife;
var defaultTemp = globalThis.exports.default
if (defaultTemp != undefined) {
ImageKnife = defaultTemp.data.imageKnife;
}

View File

@ -369,19 +369,8 @@ export class RequestOption {
break;
}
}
if(ImageKnife){
}else{
ImageKnife = globalThis.exports.default.data.imageKnife;
}
if(ImageKnife){
}else{
console.log('ImageKnife Singleton Initialization Not Completed!')
}
// 加载成功之后
ImageKnife.removeRunning(this);
globalThis.ImageKnife.removeRunning(this);
}
loadError(err) {
@ -396,25 +385,9 @@ export class RequestOption {
this.errorholderFunc(this.errorholderData)
}
}
// 加载失败之后
if(ImageKnife){
}else{
ImageKnife = globalThis.exports.default.data.imageKnife;
}
if(ImageKnife){
}else{
console.log('ImageKnife Singleton Initialization Not Completed!')
}
ImageKnife.removeRunning(this);
globalThis.ImageKnife.removeRunning(this);
}
}
var ImageKnife;
var defaultTemp = globalThis.exports.default
if (defaultTemp != undefined) {
ImageKnife = defaultTemp.data.imageKnife;
}

View File

@ -20,8 +20,8 @@ import fileio from '@ohos.fileio';
import {CompressAdapter} from '../compress/provider/CompressAdapter'
import {DataStringPathProvider} from '../compress/provider/DataStringPathProvider'
import {RecourseProvider} from '../compress/provider/RecourseProvider'
import featureability from '@ohos.ability.featureAbility'
import {Engine} from '../compress/Engine'
import { Engine } from '../compress/Engine'
import { ImageKnife } from '../ImageKnife'
export class CompressBuilder {
private _mTargetDir: string;
@ -106,10 +106,11 @@ export class CompressBuilder {
public async get():Promise<string> {
if (!this._mTargetDir) {
let path = await featureability.getContext().getFilesDir();
let context = globalThis.ImageKnife.getImageKnifeContext();
let path = context.filesDir;
var timestamp = (new Date()).valueOf();
this._outFilePath = path + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
let result =await this.startAsyncCompress();
let result = await this.startAsyncCompress();
return result;
} else {
let result =await this.startAsyncCompress();
@ -200,15 +201,9 @@ export class CompressBuilder {
}
private getImageCacheFile() {
featureability.getContext()
.getFilesDir()
.then(path => {
var timestamp = (new Date()).valueOf();
this._outFilePath = path + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
this.startCompress();
})
.catch(error => {
throw new Error("getImageCacheFile happened error:" + JSON.stringify(error));
})
let context = globalThis.ImageKnife.getImageKnifeContext();
var timestamp = (new Date()).valueOf();
this._outFilePath = context.filesDir + "/compress/" + timestamp + (Math.random() * 100).toFixed(0) + ".jpg";
this.startCompress();
}
}

View File

@ -70,7 +70,6 @@ export class Engine {
}
compress() {
console.info("asasd compress()")
if (this.mCompressAdapter instanceof DataStringPathProvider) {
// file
this.mCompressAdapter.openInternal((buffer) => {
@ -90,7 +89,7 @@ export class Engine {
var height = info.size.height;
var width = info.size.width;
var computeSize = this.computeSize(width, height);
console.info("asasd compress computeSize:" + computeSize);
console.info("Engine compress computeSize:" + computeSize);
let options = {
editable: true,
sampleSize: computeSize,

View File

@ -14,7 +14,6 @@
*/
import {CompressAdapter, PixelMapFormat} from "../provider/CompressAdapter"
import resmgr from '@ohos.resourceManager'
import {CompressDataListener} from "../listener/CompressDataListener"
import {FileTypeUtil} from '../../../imageknife/utils/FileTypeUtil'
@ -43,20 +42,18 @@ export class RecourseProvider extends CompressAdapter {
if (!this._mResourceData) {
throw Error("compress resource is empty");
}
resmgr.getResourceManager()
.then(result => {
result.getMedia(this._mResourceData
.id)
.then(data => {
let buffer = this.uint8ArrayToBuffer(data);
let fileTypeUtil = new FileTypeUtil()
this._mPixelMapHeader = fileTypeUtil.getFileType(buffer);
callback(buffer);
globalThis.ImageKnife.getImageKnifeContext().resourceManager
.getMedia(this._mResourceData.id)
.then(data => {
let buffer = this.uint8ArrayToBuffer(data);
let fileTypeUtil = new FileTypeUtil()
this._mPixelMapHeader = fileTypeUtil.getFileType(buffer);
callback(buffer);
})
.catch(err => {
.catch(err => {
console.log("RecourseProvider openInternal err" + JSON.stringify(err));
})
})
}
getPixelMapFormat(): PixelMapFormat{

View File

@ -13,13 +13,12 @@
* limitations under the License.
*/
import {AsyncTransform} from "../transform/AsyncTransform"
import { CropCallback } from './CropCallback'
import image from "@ohos.multimedia.image"
import {TransformUtils} from "../transform/TransformUtils"
export namespace Crop {
export function crop(buf: ArrayBuffer, x: number, y: number, cropWidth: number, cropHeight: number, func?: AsyncTransform<PixelMap>, colorRatio?: number) {
export function crop(buf: ArrayBuffer, x: number, y: number, cropWidth: number, cropHeight: number, func?: CropCallback<PixelMap>, colorRatio?: number) {
if (!buf || buf.byteLength <= 0) {
console.log("Crop buf is empty");
if (func) {
@ -28,7 +27,7 @@ export namespace Crop {
return;
}
var imageSource = image.createImageSource(buf as any);
TransformUtils.getPixelMapSize(imageSource, (error, size: {
getPixelMapSize(imageSource, (error, size: {
width: number,
height: number
}) => {
@ -72,7 +71,7 @@ export namespace Crop {
})
}
async function colorRatioPixelMap(data: any, width: number, height: number, colorRatio: number, func?: AsyncTransform<PixelMap>) {
async function colorRatioPixelMap(data: any, width: number, height: number, colorRatio: number, func?: CropCallback<PixelMap>) {
if (!data) {
func("colorRatio pixelMap is null", null);
return;
@ -94,4 +93,23 @@ export namespace Crop {
await writePromise;
func("", data);
}
function getPixelMapSize(imageSource: any, func: CropCallback<{
width: number,
height: number
}>) {
if (!imageSource) {
return;
}
imageSource.getImageInfo((err, value) => {
if (err) {
func(err, null)
return;
}
var pWidth = value.size.width;
var pHeight = value.size.height;
func('', { width: pWidth, height: pHeight });
})
}
}

View File

@ -0,0 +1,17 @@
/*
* Copyright (C) 2022 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 interface CropCallback<T> {
(err, data: T)
}

View File

@ -0,0 +1,903 @@
/*
* Copyright (C) 2022 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 image from "@ohos.multimedia.image"
import { Crop } from './Crop'
import { CropCallback } from './CropCallback'
@Component
struct PixelMapCrop {
@Watch('watchOptions') @State options: PixelMapCrop.Options = new PixelMapCrop.Options();
@Watch('watchCropTap') @Prop cropTap: boolean;
@State bWidth: number = 0;
@State bHeight: number = 0;
@State cWidth: number = 0;
@State cHeight: number = 0;
downX: number = 0;
downY: number = 0;
moveX: number = 0;
moveY: number = 0;
lastMoveX: number = 0;
lastMoveY: number = 0;
// 裁剪4个角区域 下标0和1左上点 下标2和3右下点
leftTopArea: number[] = [0, 0, 0, 0]
leftBottomArea: number[] = [0, 0, 0, 0]
rightTopArea: number[] = [0, 0, 0, 0]
rightBottomArea: number[] = [0, 0, 0, 0]
// 4个边框区域
leftLineArea: number[] = [0, 0, 0, 0]
topLineArea: number[] = [0, 0, 0, 0]
rightLineArea: number[] = [0, 0, 0, 0]
bottomLineArea: number[] = [0, 0, 0, 0]
//四个角的点
topLeftPoint: number[] = [0, 0]
topRightPoint: number[] = [0, 0]
bottomLeftPoint: number[] = [0, 0]
bottomRightPoint: number[] = [0, 0]
//角宽
connerWidth: number = 4
//边框线宽
lineWidth: number = 2
//内部预览细线
gridLineWidth: number = 1
MIN_LENGTH = this.connerWidth * 2 * 4
isValidTouch = false;
isTopLeftAreaTouch = false;
isTopRightAreaTouch = false;
isBottomLeftAreaTouch = false;
isBottomRightAreaTouch = false;
isTopLineAreaTouch = false;
isLeftLineAreaTouch = false;
isRightLineAreaTouch = false;
isBottomLineAreaTouch = false;
isMoveTouch = false;
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private contextGesture: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
watchOptions() {
this.readyCrop();
}
watchCropTap() {
console.log('PMC watchCropTap callback')
if (this.options.cropAction) {
console.log('PMC cropAction start')
this.options.cropAction(this.topLeftPoint, this.bottomRightPoint, this.options.pixelScale);
}
}
readyCrop() {
if (!this.options.width || !this.options.height || !this.options.pixelBuffer || !this.options.pixelMap) {
throw new Error('PixelMapCrop Options width must not be null & height must not be null & pixelMap must not be null & pixelBuffer must not be null ')
return
}
this.bWidth = px2vp(this.options.width);
this.bHeight = px2vp(this.options.height);
this.cWidth = px2vp(this.options.pixelWidth)
this.cHeight = px2vp(this.options.pixelHeight)
this.context.drawImage(this.options.pixelMap, 0, 0)
this.cropDefault();
this.buildCropBoxConnerArea()
this.buildCropBoxLineArea()
this.drawCropBox();
}
//获取裁剪 初始位置
cropDefault() {
// 左上角 初始坐标
this.topLeftPoint = [this.cWidth / 4.0 - this.connerWidth / 2.0, this.cHeight / 4.0 - this.connerWidth / 2.0]
// 右上角 初始坐标
this.topRightPoint = [this.cWidth / 4.0 * 3.0 + this.connerWidth / 2.0, this.cHeight / 4.0 - this.connerWidth / 2.0]
// 左下角 初始坐标
this.bottomLeftPoint = [this.cWidth / 4.0 - this.connerWidth / 2.0, this.cHeight / 4.0 * 3.0 + this.connerWidth / 2.0]
// 右下角 初始坐标
this.bottomRightPoint = [this.cWidth / 4.0 * 3.0 + this.connerWidth / 2.0, this.cHeight / 4.0 * 3.0 + this.connerWidth / 2.0]
}
buildCropBoxConnerArea() {
// 左上角 初始区域
this.leftTopArea = [this.topLeftPoint[0], this.topLeftPoint[1], this.topLeftPoint[0] + this.MIN_LENGTH / 2, this.topLeftPoint[1] + this.MIN_LENGTH / 2]
// 右上角 初始区域
this.rightTopArea = [this.topRightPoint[0] - this.MIN_LENGTH / 2, this.topRightPoint[1], this.topRightPoint[0], this.topRightPoint[1] + this.MIN_LENGTH / 2]
// 左下角 初始区域
this.leftBottomArea = [this.bottomLeftPoint[0], this.bottomLeftPoint[1] - this.MIN_LENGTH / 2, this.bottomLeftPoint[0] + this.MIN_LENGTH / 2, this.bottomLeftPoint[1]]
// 右下角 初始区域
this.rightBottomArea = [this.bottomRightPoint[0] - this.MIN_LENGTH / 2, this.bottomRightPoint[1] - this.MIN_LENGTH / 2, this.bottomRightPoint[0], this.bottomRightPoint[1]]
}
buildCropBoxLineArea() {
// 左线
this.leftLineArea = [this.topLeftPoint[0], this.topLeftPoint[1] + this.MIN_LENGTH / 2, this.bottomLeftPoint[0] + this.MIN_LENGTH / 2, this.bottomLeftPoint[1] - this.MIN_LENGTH / 2]
// 上线
this.topLineArea = [this.topLeftPoint[0] + this.MIN_LENGTH / 2, this.topLeftPoint[1], this.topRightPoint[0] - this.MIN_LENGTH / 2, this.topRightPoint[1] + this.MIN_LENGTH / 2]
// 右线
this.rightLineArea = [this.topRightPoint[0] - this.MIN_LENGTH / 2, this.topRightPoint[1] + this.MIN_LENGTH / 2, this.bottomRightPoint[0], this.bottomRightPoint[1] - this.MIN_LENGTH / 2]
// 下线
this.bottomLineArea = [this.bottomLeftPoint[0] + this.MIN_LENGTH / 2, this.bottomLeftPoint[1] - this.MIN_LENGTH / 2, this.bottomRightPoint[0] - this.MIN_LENGTH / 2, this.bottomRightPoint[1]]
}
// 绘制裁剪框
drawCropBox() {
this.contextGesture.clearRect(0, 0, this.cWidth, this.cHeight)
// 绘制 裁剪框内部 透明底色 外部非透明底色
this.drawTransparentBackground();
// 绘制网格线
if (this.options.hasGuideLine) {
this.drawGridLine()
}
// 绘制裁剪框边框线
this.drawConnerLine()
// 绘制裁剪框边框
this.drawConner()
}
drawTransparentBackground() {
this.contextGesture.fillStyle = 'rgba(0,0,0,0.8)'
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1])
this.contextGesture.lineTo(this.topRightPoint[0], this.topRightPoint[1])
this.contextGesture.lineTo(this.bottomRightPoint[0], this.bottomRightPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1])
this.contextGesture.closePath();
this.contextGesture.moveTo(0, 0)
this.contextGesture.lineTo(0, this.cHeight)
this.contextGesture.lineTo(this.cWidth, this.cHeight)
this.contextGesture.lineTo(this.cWidth, 0)
this.contextGesture.closePath();
this.contextGesture.fill();
}
drawGridLine() {
this.contextGesture.lineWidth = this.gridLineWidth * px2vp(1)
this.contextGesture.lineCap = 'square'
this.contextGesture.strokeStyle = '#ffffff'
let contentW = this.topRightPoint[0] - this.topLeftPoint[0]
let stepW = contentW / 3.0;
let contentH = this.bottomLeftPoint[1] - this.topLeftPoint[1]
let stepH = contentH / 3.0;
// 竖线1
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0] + stepW * 1.0, this.topLeftPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0] + stepW * 1.0, this.bottomLeftPoint[1])
this.contextGesture.stroke()
// 竖线2
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0] + stepW * 2.0, this.topLeftPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0] + stepW * 2.0, this.bottomLeftPoint[1])
this.contextGesture.stroke()
//横线1
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1] + stepH * 1.0)
this.contextGesture.lineTo(this.topRightPoint[0], this.topRightPoint[1] + stepH * 1.0)
this.contextGesture.stroke()
//横线2
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1] + stepH * 2.0)
this.contextGesture.lineTo(this.topRightPoint[0], this.topRightPoint[1] + stepH * 2.0)
this.contextGesture.stroke()
}
// 边框
drawConnerLine() {
this.contextGesture.lineWidth = this.lineWidth
this.contextGesture.lineCap = 'square'
this.contextGesture.strokeStyle = '#aaaaaa'
// 上框
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1])
this.contextGesture.lineTo(this.topRightPoint[0], this.topRightPoint[1])
this.contextGesture.stroke()
// 左框
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1])
this.contextGesture.stroke()
// 右框
console.log('PMC this.topRightPoint=' + this.topRightPoint + ' this.bottomRightPoint=' + this.bottomRightPoint)
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topRightPoint[0], this.topRightPoint[1])
this.contextGesture.lineTo(this.bottomRightPoint[0], this.bottomRightPoint[1])
this.contextGesture.stroke()
// 下框
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1])
this.contextGesture.lineTo(this.bottomRightPoint[0], this.bottomRightPoint[1])
this.contextGesture.stroke()
}
// 边框角
drawConner() {
this.contextGesture.lineWidth = this.connerWidth
this.contextGesture.lineCap = 'square'
this.contextGesture.strokeStyle = '#ffffff'
// 左上角
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1])
this.contextGesture.lineTo(this.topLeftPoint[0], this.topLeftPoint[1] + this.MIN_LENGTH / 2.0)
this.contextGesture.stroke()
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topLeftPoint[0], this.topLeftPoint[1])
this.contextGesture.lineTo(this.topLeftPoint[0] + this.MIN_LENGTH / 2.0, this.topLeftPoint[1])
this.contextGesture.stroke()
// 右上角
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topRightPoint[0], this.topRightPoint[1])
this.contextGesture.lineTo(this.topRightPoint[0], this.topRightPoint[1] + this.MIN_LENGTH / 2.0)
this.contextGesture.stroke()
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.topRightPoint[0], this.topRightPoint[1])
this.contextGesture.lineTo(this.topRightPoint[0] - this.MIN_LENGTH / 2.0, this.topRightPoint[1])
this.contextGesture.stroke()
// 左下角
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1] - this.MIN_LENGTH / 2.0)
this.contextGesture.stroke()
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.bottomLeftPoint[0], this.bottomLeftPoint[1])
this.contextGesture.lineTo(this.bottomLeftPoint[0] + this.MIN_LENGTH / 2.0, this.bottomLeftPoint[1])
this.contextGesture.stroke()
// 右下角
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.bottomRightPoint[0], this.bottomRightPoint[1])
this.contextGesture.lineTo(this.bottomRightPoint[0], this.bottomRightPoint[1] - this.MIN_LENGTH / 2.0)
this.contextGesture.stroke()
this.contextGesture.beginPath()
this.contextGesture.moveTo(this.bottomRightPoint[0], this.bottomRightPoint[1])
this.contextGesture.lineTo(this.bottomRightPoint[0] - this.MIN_LENGTH / 2.0, this.bottomRightPoint[1])
this.contextGesture.stroke()
}
build() {
Stack() {
Canvas(this.context)
.width(this.cWidth)
.height(this.cHeight)
.onReady(() => {
}).backgroundColor(Color.Yellow)
Canvas(this.contextGesture)
.width(this.cWidth)
.height(this.cHeight)
// .backgroundColor('#33000000')
.onReady(() => {
})
.onTouch((event: TouchEvent) => {
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.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
}
})
}
.width(this.bWidth)
.height(this.bHeight)
.padding({
left: (this.bWidth - this.cWidth) / 2.0,
top: (this.bHeight - this.cHeight) / 2.0,
right: (this.bWidth - this.cWidth) / 2.0,
bottom: (this.bHeight - this.cHeight) / 2.0
})
.backgroundColor(Color.Pink)
}
touchLeftTopArea(dx: number, dy: number) {
if (this.isTopLeftAreaTouch) {
let boarderLeft = this.topLeftPoint[0] + dx
if (boarderLeft < 0) {
dx = 0 - this.topLeftPoint[0];
}
let boarderTop = this.topLeftPoint[1] + dy
if (boarderTop < 0) {
dy = 0 - this.topLeftPoint[1]
}
let boarderRight = this.topLeftPoint[0] + dx
if (boarderRight > this.topRightPoint[0] - this.MIN_LENGTH) {
dx = this.topRightPoint[0] - this.MIN_LENGTH - this.topLeftPoint[0]
}
let boarderBottom = this.topLeftPoint[1] + dy
if (boarderBottom > this.bottomLeftPoint[1] - this.MIN_LENGTH) {
dy = this.bottomLeftPoint[1] - this.MIN_LENGTH - this.topLeftPoint[1]
}
this.topLeftPoint[0] = this.topLeftPoint[0] + dx;
this.topLeftPoint[1] = this.topLeftPoint[1] + dy;
this.topRightPoint[1] = this.topRightPoint[1] + dy;
this.bottomLeftPoint[0] = this.bottomLeftPoint[0] + dx;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchRightTopArea(dx: number, dy: number) {
if (this.isTopRightAreaTouch) {
let boarderLeft = this.topRightPoint[0] + dx
if (boarderLeft < this.topLeftPoint[0] + this.MIN_LENGTH) {
dx = this.topLeftPoint[0] + this.MIN_LENGTH - this.topRightPoint[0];
}
let boarderTop = this.topRightPoint[1] + dy
if (boarderTop < 0) {
dy = 0 - this.topRightPoint[1]
}
let boarderRight = this.topRightPoint[0] + dx
if (boarderRight > this.cWidth) {
dx = this.cWidth - this.topRightPoint[0]
}
let boarderBottom = this.topRightPoint[1] + dy
if (boarderBottom > this.bottomRightPoint[1] - this.MIN_LENGTH) {
dy = this.bottomRightPoint[1] - this.MIN_LENGTH - this.topLeftPoint[1]
}
this.topRightPoint[0] = this.topRightPoint[0] + dx;
this.topRightPoint[1] = this.topRightPoint[1] + dy;
this.topLeftPoint[1] = this.topLeftPoint[1] + dy;
this.bottomRightPoint[0] = this.bottomRightPoint[0] + dx;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchLeftBottomArea(dx: number, dy: number) {
if (this.isBottomLeftAreaTouch) {
let boarderLeft = this.bottomLeftPoint[0] + dx
if (boarderLeft < 0) {
dx = 0 - this.bottomLeftPoint[0];
}
let boarderTop = this.bottomLeftPoint[1] + dy
if (boarderTop < this.topLeftPoint[1] + this.MIN_LENGTH) {
dy = this.topLeftPoint[1] + this.MIN_LENGTH - this.bottomLeftPoint[1]
}
let boarderRight = this.bottomLeftPoint[0] + dx
if (boarderRight > this.bottomRightPoint[0] - this.MIN_LENGTH) {
dx = this.bottomRightPoint[0] - this.MIN_LENGTH - this.bottomLeftPoint[0]
}
let boarderBottom = this.bottomLeftPoint[1] + dy
if (boarderBottom > this.cHeight) {
dy = this.cHeight - this.bottomLeftPoint[1]
}
this.bottomLeftPoint[0] = this.bottomLeftPoint[0] + dx;
this.bottomLeftPoint[1] = this.bottomLeftPoint[1] + dy;
this.topLeftPoint[0] = this.topLeftPoint[0] + dx;
this.bottomRightPoint[1] = this.bottomRightPoint[1] + dy;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchRightBottomArea(dx: number, dy: number) {
if (this.isBottomRightAreaTouch) {
let boarderLeft = this.bottomRightPoint[0] + dx
if (boarderLeft < this.bottomLeftPoint[0] + this.MIN_LENGTH) {
dx = this.bottomLeftPoint[0] + this.MIN_LENGTH - this.bottomRightPoint[0];
}
let boarderTop = this.bottomRightPoint[1] + dy
if (boarderTop < this.topRightPoint[1] + this.MIN_LENGTH) {
dy = this.topRightPoint[1] + this.MIN_LENGTH - this.bottomRightPoint[1]
}
let boarderRight = this.bottomRightPoint[0] + dx
if (boarderRight > this.cWidth) {
dx = this.cWidth - this.bottomRightPoint[0]
}
let boarderBottom = this.bottomRightPoint[1] + dy
if (boarderBottom > this.cHeight) {
dy = this.cHeight - this.bottomRightPoint[1]
}
this.bottomRightPoint[0] = this.bottomRightPoint[0] + dx;
this.bottomRightPoint[1] = this.bottomRightPoint[1] + dy;
this.bottomLeftPoint[1] = this.bottomLeftPoint[1] + dy;
this.topRightPoint[0] = this.topRightPoint[0] + dx;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchTopLineArea(dx: number, dy: number) {
if (this.isTopLineAreaTouch) {
let boarderTop = this.topLeftPoint[1] + dy
if (boarderTop < 0) {
dy = 0 - this.topLeftPoint[1]
}
let boarderBottom = this.topLeftPoint[1] + dy
if (boarderBottom > this.bottomLeftPoint[1] - this.MIN_LENGTH) {
dy = this.bottomLeftPoint[1] - this.MIN_LENGTH - this.topLeftPoint[1]
}
this.topLeftPoint[1] = this.topLeftPoint[1] + dy;
this.topRightPoint[1] = this.topRightPoint[1] + dy;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchBottomLineArea(dx: number, dy: number) {
if (this.isBottomLineAreaTouch) {
let boarderTop = this.bottomLeftPoint[1] + dy
if (boarderTop < this.topLeftPoint[1] + this.MIN_LENGTH) {
dy = this.topLeftPoint[1] + this.MIN_LENGTH - this.bottomLeftPoint[1]
}
let boarderBottom = this.bottomLeftPoint[1] + dy
if (boarderBottom > this.cHeight) {
dy = this.cHeight - this.bottomLeftPoint[1]
}
this.bottomLeftPoint[1] = this.bottomLeftPoint[1] + dy;
this.bottomRightPoint[1] = this.bottomRightPoint[1] + dy;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchLeftLineArea(dx: number, dy: number) {
if (this.isLeftLineAreaTouch) {
let boarderLeft = this.topLeftPoint[0] + dx
if (boarderLeft < 0) {
dx = 0 - this.topLeftPoint[0];
}
let boarderRight = this.topLeftPoint[0] + dx
if (boarderRight > this.topRightPoint[0] - this.MIN_LENGTH) {
dx = this.topRightPoint[0] - this.MIN_LENGTH - this.topLeftPoint[0]
}
this.topLeftPoint[0] = this.topLeftPoint[0] + dx;
this.bottomLeftPoint[0] = this.bottomLeftPoint[0] + dx;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchRightLineArea(dx: number, dy: number) {
if (this.isRightLineAreaTouch) {
let boarderLeft = this.topRightPoint[0] + dx
if (boarderLeft < this.topLeftPoint[0] + this.MIN_LENGTH) {
dx = this.topLeftPoint[0] + this.MIN_LENGTH - this.topRightPoint[0];
}
let boarderRight = this.topRightPoint[0] + dx
if (boarderRight > this.cWidth) {
dx = this.cWidth - this.topRightPoint[0]
}
this.topRightPoint[0] = this.topRightPoint[0] + dx;
this.bottomRightPoint[0] = this.bottomRightPoint[0] + dx;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
touchMoveCropBox(dx: number, dy: number) {
if (this.isMoveTouch) {
let boarderLeft = this.topLeftPoint[0] + dx
if (boarderLeft < 0) {
dx = 0 - this.topLeftPoint[0];
}
let boarderTop = this.topLeftPoint[1] + dy
if (boarderTop < 0) {
dy = 0 - this.topLeftPoint[1]
}
let boarderRight = this.bottomRightPoint[0] + dx
if (boarderRight > this.cWidth) {
dx = this.cWidth - this.bottomRightPoint[0]
}
let boarderBottom = this.bottomRightPoint[1] + dy
if (boarderBottom > this.cHeight) {
dy = this.cHeight - this.bottomRightPoint[1]
}
this.topLeftPoint[0] = this.topLeftPoint[0] + dx;
this.topLeftPoint[1] = this.topLeftPoint[1] + dy;
this.topRightPoint[0] = this.topRightPoint[0] + dx;
this.topRightPoint[1] = this.topRightPoint[1] + dy;
this.bottomLeftPoint[0] = this.bottomLeftPoint[0] + dx;
this.bottomLeftPoint[1] = this.bottomLeftPoint[1] + dy;
this.bottomRightPoint[0] = this.bottomRightPoint[0] + dx;
this.bottomRightPoint[1] = this.bottomRightPoint[1] + dy;
this.buildCropBoxConnerArea();
this.buildCropBoxLineArea();
this.drawCropBox();
}
}
// 判断用户手指按下的点的位置
belongRegion() {
this.resetTouch();
// 首先判断是否落在裁剪框默认范围内
this.isBelongCropBox();
console.log('PMC this.isValidTouch=' + this.isValidTouch)
console.log('PMC downx =' + this.downX + ' downy =' + this.downY + 'this.leftTopArea =' + this.leftTopArea + ' this.leftBottomArea=' + this.leftBottomArea
+ ' this.rightTopArea=' + this.rightTopArea + ' this.rightBottomArea=' + this.rightBottomArea);
// 其次判断是否落在裁剪框4个角位置范围
if (this.isValidTouch) {
console.log('PMC C1')
this.isTopLeftAreaTouch = this.connerBelonged(this.leftTopArea)
console.log('PMC C2')
this.isBottomLeftAreaTouch = this.connerBelonged(this.leftBottomArea)
console.log('PMC C3')
this.isTopRightAreaTouch = this.connerBelonged(this.rightTopArea)
console.log('PMC C4')
this.isBottomRightAreaTouch = this.connerBelonged(this.rightBottomArea)
console.log('PMC result this.isTopLeftAreaTouch =' + this.isTopLeftAreaTouch + ' this.isTopRightAreaTouch =' + this.isTopRightAreaTouch
+ ' this.isBottomLeftAreaTouch=' + this.isBottomLeftAreaTouch + ' isBottomRightAreaTouch' + this.isBottomRightAreaTouch)
// 再判断是否落在裁剪框4个边框范围
if (!this.isTopLeftAreaTouch && !this.isBottomLeftAreaTouch && !this.isTopRightAreaTouch && !this.isBottomRightAreaTouch) {
console.log('PMC L1')
this.isTopLineAreaTouch = this.lineBelonged(this.topLineArea)
console.log('PMC L2')
this.isLeftLineAreaTouch = this.lineBelonged(this.leftLineArea)
console.log('PMC L3')
this.isRightLineAreaTouch = this.lineBelonged(this.rightLineArea)
console.log('PMC L4')
this.isBottomLineAreaTouch = this.lineBelonged(this.bottomLineArea)
console.log('PMC result this.isTopLineAreaTouch =' + this.isTopLineAreaTouch + ' this.isLeftLineAreaTouch =' + this.isLeftLineAreaTouch
+ ' this.isRightLineAreaTouch=' + this.isRightLineAreaTouch + ' isBottomLineAreaTouch' + this.isBottomLineAreaTouch)
}
if (!this.isTopLeftAreaTouch && !this.isBottomLeftAreaTouch && !this.isTopRightAreaTouch && !this.isBottomRightAreaTouch
&& !this.isTopLineAreaTouch && !this.isLeftLineAreaTouch && !this.isRightLineAreaTouch && !this.isBottomLineAreaTouch
) {
this.belongMoveTouch();
}
}
// 最后的其他位置都是整体平移整个裁剪框
}
resetTouch() {
this.isValidTouch = false;
this.isTopLeftAreaTouch = false;
this.isTopRightAreaTouch = false;
this.isBottomLeftAreaTouch = false;
this.isBottomRightAreaTouch = false;
this.isTopLineAreaTouch = false;
this.isLeftLineAreaTouch = false;
this.isRightLineAreaTouch = false;
this.isBottomLineAreaTouch = false;
this.isMoveTouch = false;
}
isBelongCropBox() {
let x0 = this.topLeftPoint[0];
let y0 = this.topLeftPoint[1];
let x1 = this.bottomRightPoint[0];
let y1 = this.bottomRightPoint[1];
if (this.downX >= x0 && this.downX <= x1 && this.downY >= y0 && this.downY <= y1) {
this.isValidTouch = true;
} else {
this.isValidTouch = false;
}
}
belongMoveTouch() {
let x0 = this.topLeftPoint[0] + this.MIN_LENGTH / 2;
let y0 = this.topLeftPoint[1] + this.MIN_LENGTH / 2;
let x1 = this.bottomRightPoint[0] - this.MIN_LENGTH / 2;
let y1 = this.bottomRightPoint[1] - this.MIN_LENGTH / 2;
if (this.downX > x0 && this.downX < x1 && this.downY > y0 && this.downY < y1) {
this.isMoveTouch = true;
} else {
this.isMoveTouch = false;
}
}
lineBelonged(area: number[]) {
let x0 = area[0];
let y0 = area[1];
let x1 = area[2];
let y1 = area[3];
if (this.downX > x0 && this.downX < x1 && this.downY > y0 && this.downY < y1) {
return true;
}
return false;
}
connerBelonged(area: number[]): boolean {
let x0 = area[0];
let y0 = area[1];
let x1 = area[2];
let y1 = area[3];
console.log('PMC downx=' + this.downX + ' downY' + this.downY + ' x0=' + x0 + ' y0=' + y0 + ' x1=' + x1 + ' y1=' + y1)
if (this.downX >= x0 && this.downX <= x1 && this.downY >= y0 && this.downY <= y1) {
console.log('PMC conner is belonged!')
return true
}
return false;
}
}
namespace PixelMapCrop {
export class Options {
width: number;
height: number;
pixelMap: PixelMap;
// 是否需要绘制线
hasGuideLine: boolean;
pixelBuffer: ArrayBuffer;
// 展示pixel宽度
pixelWidth: number;
// 展示pixel高度
pixelHeight: number;
// 缩放scale:center-inside类型缩放的比例
pixelScale: number;
// 用户裁剪后的回调
cropFunction: Function;
// 本地裁剪框 回调
cropAction: Function;
constructor() {
}
// 裁剪动作
setCropFunction(crop: (error, pixelmap, sx, sy) => 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)
}, 1);
}
return this;
}
setWidth(imageWidth: number) {
this.width = imageWidth;
return this;
}
setHeight(imageHeight: number) {
this.height = imageHeight;
return this;
}
setGuideLine(guideLine: boolean) {
this.hasGuideLine = guideLine;
}
getGuideLine() {
return this.hasGuideLine;
}
async loadBuffer(buffer: ArrayBuffer, readyCrop: Function) {
if (!buffer || buffer.byteLength <= 0) {
console.log('PixelMapCrop "loadBuffer" method buf is empty');
return;
}
//数据赋值
this.pixelBuffer = buffer;
let imageSource = image.createImageSource(buffer as any);
imageSource.getImageInfo().then((imageInfo) => {
//获取宽高
let scaleInside = 1;
if (this.width && this.height) {
//center_inside 模式判断
let scaleW = imageInfo.size.width / (this.width * 1.0)
let scaleH = imageInfo.size.height / (this.height * 1.0)
if (scaleH > 1 || scaleW > 1) {
scaleInside = 1.0 / Math.max(scaleW, scaleH)
}
} else {
this.width = imageInfo.size.width;
this.height = imageInfo.size.height;
}
this.pixelScale = scaleInside;
this.pixelWidth = imageInfo.size.width * scaleInside;
this.pixelHeight = imageInfo.size.height * scaleInside;
let options = {
editable: true,
rotate: 0,
desiredSize: {
width: imageInfo.size.width * scaleInside,
height: imageInfo.size.height * scaleInside,
}
}
imageSource.createPixelMap(options).then((pixelmap) => {
this.pixelMap = pixelmap;
if (readyCrop) {
readyCrop();
}
})
});
}
}
}
export default PixelMapCrop;

View File

@ -13,122 +13,107 @@
* limitations under the License.
*/
import {IDataFetch} from "../networkmanage/IDataFetch"
import {RequestOption} from "../RequestOption"
import {Md5} from "../../cache/Md5"
import{FileUtils} from "../../cache/FileUtils"
import { IDataFetch } from "../networkmanage/IDataFetch"
import { RequestOption } from "../RequestOption"
import { Md5 } from "../../cache/Md5"
import { FileUtils } from "../../cache/FileUtils"
import loadRequest from '@ohos.request';
export class DownloadClient implements IDataFetch {
loadData(request: RequestOption, onCompleteFunction, onErrorFunction) {
let requestUrl = request.loadSrc as string;
if (requestUrl.startsWith("http") || requestUrl.startsWith("https")) {
let filename = Md5.hashStr(request.generateDataKey);
let downloadFolder = request.getFilesPath() + "/" + request.networkCacheFolder;
let allpath = request.getFilesPath() + "/" + request.networkCacheFolder + "/" + filename + ".img";
let filename = Md5.hashStr(request.generateDataKey);
let downloadFolder = request.getFilesPath() + "/" + request.networkCacheFolder;
let allpath = request.getFilesPath() + "/" + request.networkCacheFolder + "/" + filename + ".img";
if (!FileUtils.getInstance().existFolder(downloadFolder)) {
FileUtils.getInstance().createFolder(downloadFolder)
}
if (!FileUtils.getInstance().existFolder(downloadFolder)) {
FileUtils.getInstance().createFolder(downloadFolder)
}
if (FileUtils.getInstance().exist(allpath)) {
FileUtils.getInstance().deleteFile(allpath)
}
if (FileUtils.getInstance().exist(allpath)) {
FileUtils.getInstance().deleteFile(allpath)
}
let desc = filename + ".img";
let desc = filename + ".img";
var downloadConfig = {
url: (request.loadSrc as string),
filePath: allpath,
};
var downloadConfig = {
url: (request.loadSrc as string),
filePath: allpath,
header: {},
enableMetered: true,
enableRoaming: true,
description: desc,
networkType: 1,
title: filename,
};
let loadTask = null;
loadRequest.download(globalThis.ImageKnife.getImageKnifeContext(), downloadConfig).then(downloadTask => {
if (downloadTask) {
loadTask = downloadTask;
let loadTask = null;
loadRequest.download(downloadConfig, (err, downloadTask) =>{
if(err){
onErrorFunction(err)
}else {
if (downloadTask) {
loadTask = downloadTask;
loadTask.on('progress', (receivedSize, totalSize) => {
let percent = Math.round(((receivedSize * 1.0) / (totalSize * 1.0)) * 100) + "%"
if (request.progressFunc) {
request.progressFunc(percent);
}
});
loadTask.on('progress', (err, receivedSize, totalSize) => {
let percent = Math.round(((receivedSize * 1.0) / (totalSize * 1.0)) * 100) + "%"
if (request.progressFunc) {
request.progressFunc(percent);
}
});
loadTask.on('complete', () => {
let downloadPath = allpath;
request.downloadFilePath = downloadPath;
let arraybuffer = FileUtils.getInstance().readFilePic(downloadPath)
onCompleteFunction(arraybuffer);
FileUtils.getInstance().deleteFile(downloadPath);
loadTask.on('complete', () => {
let downloadPath = allpath;
request.downloadFilePath = downloadPath;
let arraybuffer = FileUtils.getInstance().readFilePic(downloadPath)
onCompleteFunction(arraybuffer);
FileUtils.getInstance().deleteFile(downloadPath);
loadTask.off('complete', () => {
loadTask.off('complete', () => {
loadTask = null;
})
})
loadTask.off('pause', () => {
})
loadTask.off('pause', () => {
})
loadTask.off('remove', () => {
})
loadTask.off('remove', () => {
})
loadTask.off('progress', () => {
})
loadTask.off('progress', () => {
})
loadTask.off('fail', () => {
})
})
loadTask.on('pause', () => {
})
loadTask.on('remove', () => {
})
loadTask.on('fail', (err) => {
onErrorFunction('DownloadClient 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 => {
loadTask = null;
console.log('DownloadClient Download task fail err =' + err);
})
}
})
} else {
onErrorFunction('DownloadClient downloadTask dismiss!')
}
}
loadTask.off('fail', () => {
})
loadTask = null;
})
} else {
onErrorFunction("DownloadClient 暂不支持除http之外的uri加载")
}
loadTask.on('pause', () => {
})
loadTask.on('remove', () => {
})
loadTask.on('fail', (err) => {
onErrorFunction('DownloadClient 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 => {
loadTask = null;
console.log('DownloadClient Download task fail err =' + err);
})
}
})
} else {
onErrorFunction('DownloadClient downloadTask dismiss!')
}
}).catch((err) => {
onErrorFunction(err)
})
}
}

View File

@ -16,7 +16,6 @@ import {UPNG} from '../pngj/UPNG';
import {PngCallback} from '../pngj/PngCallback';
import image from '@ohos.multimedia.image';
import resourceManager from '@ohos.resourceManager';
import featureability from '@ohos.ability.featureAbility'
import ArkWorker from '@ohos.worker'
export class Pngj {
@ -60,17 +59,16 @@ export class Pngj {
callback(pngBuffer, newPng);
}
readPngImageAsync(worker:ArkWorker.Worker, pngBuffer: ArrayBuffer, callback:PngCallback<ArrayBuffer, any>){
worker.onerror = function(data){
readPngImageAsync(worker: any, pngBuffer: ArrayBuffer, callback: PngCallback<ArrayBuffer, any>) {
worker.onerror = function (data) {
}
worker.onmessageerror = function(e){
worker.onmessageerror = function (e) {
}
worker.onexit = function(){
worker.onexit = function () {
}
@ -85,24 +83,20 @@ export class Pngj {
}
worker.terminate();
}
var obj = { type: 'readPngImageAsync', data:pngBuffer}
var obj = { type: 'readPngImageAsync', data: pngBuffer }
worker.postMessage(obj, [pngBuffer])
}
writePngWithStringAsync(worker:ArkWorker.Worker,addInfo:string, pngBuffer:ArrayBuffer, callback:PngCallback<ArrayBuffer,any>) {
worker.onerror = function(data){
writePngWithStringAsync(worker: any, addInfo: string, pngBuffer: ArrayBuffer, callback: PngCallback<ArrayBuffer, any>) {
worker.onerror = function (data) {
}
worker.onmessageerror = function(e){
worker.onmessageerror = function (e) {
}
worker.onexit = function(){
worker.onexit = function () {
}
@ -123,18 +117,16 @@ export class Pngj {
}
writePngAsync(worker:ArkWorker.Worker,pngBuffer:ArrayBuffer, callback:PngCallback<ArrayBuffer,any>) {
worker.onerror = function(data){
writePngAsync(worker: any, pngBuffer: ArrayBuffer, callback: PngCallback<ArrayBuffer, any>) {
worker.onerror = function (data) {
}
worker.onmessageerror = function(e){
worker.onmessageerror = function (e) {
}
worker.onexit = function(){
worker.onexit = function () {
}

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
import {ICache} from "../requestmanage/ICache"
import {DiskLruCache} from "../../cache/DiskLruCache"
import { ICache } from "../requestmanage/ICache"
import { DiskLruCache } from "@ohos/disklrucache"
export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
private mDiskLruCache: DiskLruCache;
@ -29,7 +29,7 @@ export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
}
getCachePath():string{
let folderPath = this.mDiskLruCache.dirPath
let folderPath = this.mDiskLruCache.getPath();
if (folderPath.endsWith('/')) {
return folderPath;
} else {
@ -38,11 +38,11 @@ export class DiskCacheProxy implements ICache<string, ArrayBuffer> {
}
getValue(key: string): ArrayBuffer{
return this.mDiskLruCache.getCacheDataByKey(key);
return this.mDiskLruCache.get(key);
}
putValue(key: string, value: ArrayBuffer) {
this.mDiskLruCache.putCacheData(key, value, null)
async putValue(key: string, value: ArrayBuffer) {
await this.mDiskLruCache.setAsync(key, value)
}
removeValue(key: string): ArrayBuffer{

View File

@ -29,7 +29,6 @@ export class MemoryCacheProxy <K, V> implements ICache<K, V> {
}
getValue(key: K): V{
console.log("Level1MemoryCache getValue come in!");
return this.mLruCache.get(key);
}

View File

@ -13,9 +13,9 @@
* limitations under the License.
*/
import {RequestOption} from "../../imageknife/RequestOption"
import {DiskLruCache} from "../../cache/DiskLruCache"
import {LruCache} from "../../cache/LruCache"
import { RequestOption } from "../../imageknife/RequestOption"
import { DiskLruCache } from "@ohos/disklrucache"
import { LruCache } from "../../cache/LruCache"
import {FileUtils} from "../../cache/FileUtils"
import {Md5} from "../../cache/Md5"
import{MemoryCacheProxy} from "../requestmanage/MemoryCacheProxy"
@ -485,8 +485,8 @@ export class RequestManager {
new Promise((resolve, reject) => {
resolve(source)
})
.then((arraybuffer: ArrayBuffer) => {
this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
.then(async (arraybuffer: ArrayBuffer) => {
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
})
.catch((err) => {
console.log("save diskLruCache error=" + err);
@ -541,18 +541,18 @@ export class RequestManager {
return imageKnifeData;
}
private saveCacheAndDisk(value: PixelMap, filetype:string, onComplete, source:ArrayBuffer){
private saveCacheAndDisk(value: PixelMap, filetype:string, onComplete, source:ArrayBuffer) {
let imageKnifeData = this.createImageKnifeData(ImageKnifeData.PIXELMAP, value, filetype);
this.mMemoryCacheProxy.putValue(this.options.generateCacheKey, imageKnifeData);
let save2DiskCache = (arraybuffer) => {
this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
}
let save2DiskCache = async (arraybuffer) => {
await this.mDiskCacheProxy.putValue(this.options.generateDataKey, arraybuffer)
}
let runSave2Disk = (resolve, reject) => {
resolve(source);
}
}
let promise = new Promise(runSave2Disk);
promise.then(save2DiskCache);
onComplete(imageKnifeData);
promise.then(save2DiskCache);
onComplete(imageKnifeData);
}
thumbnailProcess(source:ArrayBuffer, filetype:string, onComplete, onError){

View File

@ -23,16 +23,14 @@ export class ParseResClient implements IResourceFetch {
let resId = res.id;
let resType = res.type;
if (resType == ResourceTypeEts.MEDIA) {
resourceManager.getResourceManager()
.then(result => {
result.getMedia(resId)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
onCompleteFunction(arrayBuffer)
})
.catch(err => {
onErrorFunction(err)
})
globalThis.ImageKnife.getImageKnifeContext().resourceManager
.getMedia(resId)
.then(data => {
let arrayBuffer = this.typedArrayToBuffer(data);
onCompleteFunction(arrayBuffer)
})
.catch(err => {
onErrorFunction(err)
})
}
else if (resType == ResourceTypeEts.RAWFILE) {

View File

@ -24,21 +24,19 @@ export class ParseResClientBase64 implements IResourceFetch {
let resId = res.id;
let resType = res.type;
if (resType == ResourceTypeEts.MEDIA) {
resourceManager.getResourceManager()
.then(result => {
result.getMediaBase64(resId)
.then(data => {
let matchReg = ';base64,';
var firstIndex = data.indexOf(matchReg)
data = data.substring(firstIndex + matchReg.length, data.length)
let arrayBuffer = Base64.getInstance()
.decode(data);
onCompleteFunction(arrayBuffer)
})
.catch(err => {
onErrorFunction(err)
})
globalThis.ImageKnife.getImageKnifeContext().resourceManager
.getMediaBase64(resId)
.then(data => {
let matchReg = ';base64,';
var firstIndex = data.indexOf(matchReg)
data = data.substring(firstIndex + matchReg.length, data.length)
let arrayBuffer = Base64.getInstance()
.decode(data);
onCompleteFunction(arrayBuffer)
})
.catch(err => {
onErrorFunction(err)
})
}
else if (resType == ResourceTypeEts.RAWFILE) {
onErrorFunction('ParseResClientBase64 本地资源是rawfile暂时无法解析出错')

View File

@ -13,13 +13,13 @@
* limitations under the License.
*/
import {BaseTransform} from "../transform/BaseTransform.ets"
import {AsyncTransform} from "../transform/AsyncTransform.ets"
import {Constants} from "../constants/Constants.ets"
import {RequestOption} from "../../imageknife/RequestOption.ets"
import {TransformUtils} from "../transform/TransformUtils.ets"
import { BaseTransform } from "../transform/BaseTransform"
import { AsyncTransform } from "../transform/AsyncTransform"
import { Constants } from "../constants/Constants"
import { RequestOption } from "../../imageknife/RequestOption"
import { TransformUtils } from "../transform/TransformUtils"
import image from "@ohos.multimedia.image"
import {fastBlur} from "../utils/FastBlur"
import { fastBlur } from "../utils/FastBlur"
export class BlurTransformation implements BaseTransform<PixelMap> {

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