专门为OpenHarmony打造的一款图像加载缓存库,致力于更高效、更轻便、更简单
| Files | Last commit | Last update |
|---|---|---|
| 1 year ago | ||
| 2 years ago | ||
| 1 year ago | ||
| 10 months ago | ||
| 2 years ago | ||
| 9 months ago | ||
| 1 year ago | ||
| 3 years ago | ||
| 2 years ago | ||
| 2 years ago | ||
| 10 months ago | ||
| 4 years ago | ||
| 2 years ago | ||
| 1 year ago | ||
| 2 years ago | ||
| 9 months ago | ||
| 9 months ago | ||
| 1 year ago | ||
| 2 years ago | ||
| 2 years ago | ||
| 2 years ago | ||
| 1 year ago |
ImageKnife
ImageKnife is a specially crafted image loading and caching library for OpenHarmony, optimized for efficiency, lightness, and simplicity.
Currently, ImageKnife has ceased to evolve. recommend imageknifepro, Supports the use of ArkTS APIs for ArkTS applications and C APIs for non-ArkTS applications; Enhances image loading performance through built-in system APIs (network C APIs and image C APIs); Allows you to customize C API extensions only, including network download, decoding, file caching, and memory caching by using interceptors and the responsibility chain pattern, catering to diverse scenarios.
Introduction
This project is a self-developed version for OpenHarmony, inspired by the open-source Glide library. It features:
- Custom memory cache strategy and adjustable cache size (LRU strategy by default)
- Disk L2 cache for downloaded images
- Custom implementation of image obtaining and network download
- Listening for network download progress through callbacks
- Image options for borders and rounded corners
- Image scaling with objectFit, including auto-adapting height
- Image scaling through transformation
- Concurrent request management with priority queuing
- No requests made for images whose lifecycle has been destroyed
- Custom cache keys
- Custom HTTP request headers
- Cache storage control (memory or file cache) with writeCacheStrategy
- Image preloading with preLoadCache
- Image loading only from cache with onlyRetrieveFromCache
- Image transformations such as blurring and highlighting
- Memory optimization through downsampling
Future features:
- Custom image decoding
Note that the 3.x version has been significantly restructured from the 2.x version, mainly in the following aspects:
- Rendering with the Image component instead of the Canvas component
- Refactored dispatch logic to control the number of concurrent requests and support priority in request queuing
- Custom memory cache policies and sizes with initMemoryCache
- Custom options for image obtaining and network download
Therefore, there are some differences in APIs and capabilities, which mainly include the following:
- The drawLifeCycle API is not supported; images are drawn manually through the canvas.
- In the new version, parameters such as mainScaleType and border are consistent with the system Image component.
- GIF/WebP animation playback and control (using ImageAnimator)
- Anti-aliasing related parameters
How to Install
ohpm install @ohos/imageknife
// If file caching is required, initialize the file cache in advance.
await ImageKnife.getInstance().initFileCache(context, 256, 256 * 1024 * 1024)
How to Use
1. Displaying a Local Resource Image
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: $r("app.media.app_icon"),
placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Auto
}
}).width(100).height(100)
2. Displaying a File From Local Context Files
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: this.localFile,
placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Auto
}
}).width(100).height(100)
3. Displaying a Network Image
ImageKnifeComponent({
imageKnifeOption: {
loadSrc:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png",
placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Auto
}
}).width(100).height(100)
4. Downloading an Image with Custom Options
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: "https://file.atomgit.com/uploads/user/1704857786989_8994.jpeg",
placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Auto,
customGetImage: custom
}
}).width(100).height(100)
// Custom implementation of the image acquisition method, such as custom network download.
@Concurrent
async function custom(context: Context, src: string | PixelMap | Resource): Promise<ArrayBuffer | undefined> {
console.info("ImageKnife:: custom download: " + src)
// Example of hardcoding to read from a local file. You can also request a network image.
return context.resourceManager.getMediaContentSync($r("app.media.bb").id).buffer as ArrayBuffer
}
5. Listening for Network Download Progress
ImageKnifeComponent({
imageKnifeOption: {
loadSrc:"https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png",
progressListener:(progress:number)=>{console.info("ImageKinfe:: call back progress = " + progress)}
}
}).width(100).height(100)
6. Setting Border Options
ImageKnifeComponent({ imageKnifeOption:
{
loadSrc: $r("app.media.rabbit"),
border: {radius:50}
}
}).width(100).height(100)
7. Setting Image Transformation Options
ImageKnifeComponent({ imageKnifeOption:
{
loadSrc: $r("app.media.rabbit"),
border: {radius:50},
transformation: new BlurTransformation(3)
}
}).width(100).height(100)
Multiple combined transformation usages:
let transformations: collections.Array<PixelMapTransformation> = new collections.Array<PixelMapTransformation>();
transformations.push(new BlurTransformation(5));
transformations.push(new BrightnessTransformation(0.2));
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: $r('app.media.pngSample'),
placeholderSrc: $r("app.media.loading"),
errorholderSrc: $r("app.media.app_icon"),
objectFit: ImageFit.Contain,
border: { radius: { topLeft: 50, bottomRight: 50 } }, // Rounded corner settings
transformation: transformations.length > 0 ? new MultiTransTransformation(transformations) : undefined // Graphic transformation group
}
}).width(300)
.height(300)
.rotate({ angle: 90 }) // Rotate by 90 degrees.
.contrast(12) // Contrast filter
Other transformation-related properties can be stacked to achieve combined transformation effects.
Example of circular cropping:
ImageKnifeComponent({ imageKnifeOption:
{
loadSrc: $r('app.media.pngSample'),
objectFit: ImageFit.Cover,
border: { radius: 150 }
}
}).width(300)
.height(300)
Example of circular cropping with border:
ImageKnifeComponent({ imageKnifeOption:
{
loadSrc: $r('app.media.pngSample'),
objectFit: ImageFit.Cover,
border: { radius: 150, color: Color.Red, width: 5 }
}
}).width(300)
.height(300)
Example of contrast filtering:
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: $r('app.media.pngSample')
}
}).width(300)
.height(300)
.contrast(12)
Example of rotation:
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: $r('app.media.pngSample')
}
}).width(300)
.height(300)
.rotate({angle:90})
.backgroundColor(Color.Pink)
8. Listening for Image Loading Success and Failure
ImageKnifeComponent({ imageKnifeOption:
{
loadSrc: $r("app.media.rabbit"),
onLoadListener:{
onLoadStart:()=>{
this.starTime = new Date().getTime()
console.info("Load start: ");
},
onLoadFailed: (err) => {
console.error("Load Failed Reason: " + err + " cost " + (new Date().getTime() - this.starTime) + " milliseconds");
},
onLoadSuccess: (data, imageData) => {
console.info("Load Successful: cost " + (new Date().getTime() - this.starTime) + " milliseconds");
return data;
},
onLoadCancel(err){
console.info(err)
}
}
}
}).width(100).height(100)
9. Using syncLoad
syncLoad sets whether to load images synchronously. By default, images are loaded asynchronously. When loading a small image, you are advised to set syncLoad to true so that the image loading can be quickly completed on the main thread.
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading")
},syncLoad:true
})
10. Using ImageKnifeAnimatorComponent
ImageKnifeAnimatorComponent({
imageKnifeOption: {
loadSrc:"https://gd-hbimg.huaban.com/e0a25a7cab0d7c2431978726971d61720732728a315ae-57EskW_fw658",
placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed')
},animatorOption:this.animatorOption
}).width(300).height(300).backgroundColor(Color.Orange).margin({top:30})
11. Obtaining Image Loading Information Through Callbacks
ImageKnifeComponent({ imageKnifeOption: {
loadSrc: $r('app.media.pngSample'),
objectFit: ImageFit.Contain,
onLoadListener: {
onLoadStart: (req) => {
let startCallBackData = JSON.stringify(req?.imageKnifeData);
},
onLoadFailed: (res, req) => {
let failedBackData = res + ";" + JSON.stringify(req?.imageKnifeData);
},
onLoadSuccess: (data, imageData, req) => {
let successBackData = JSON.stringify(req?.imageKnifeData);
},
onLoadCancel: (res, req) => {
let cancelBackData = res + ";" + JSON.stringify(req?.imageKnifeData);
}
},
border: { radius: 50 },
onComplete: (event) => {
if (event && event.loadingStatus == 0) {
let render_success = JSON.stringify(Date.now())
}
}
}
}).width(100).height(100)
12. Image Downsampling
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r('app.media.loading'),
errorholderSrc:$r('app.media.failed'),
downsampleOf: DownsampleStrategy.NONE
}
}).width(300).height(300)
13. Customizing an RCP Network Request
ImageKnifeComponent({
imageKnifeOption:{
loadSrc:"http//xx.xx",
customGetImage:custom
}
})
// Customize the download method.
@Concurrent
async function custom(context: Context, src: string | PixelMap | Resource,headers?: Record<string,Object>): Promise<ArrayBuffer | undefined> {
return new Promise((resolve,reject)=>{
if (typeof src == "string") {
let session = GetSession.session
let req = new rcp.Request(src,"GET");
session.fetch(req).then((response)=>{
if(response.statusCode == 200) {
let buffer = response.body
resolve(buffer)
} else {
reject("rcp code:"+response.statusCode)
}
}).catch((err:BusinessError)=>{
reject("error rcp src:"+src+",err:"+JSON.stringify(err))
})
}
})
}
Reuse Scenario
Clear the component content in the aboutToRecycle lifecycle and trigger image loading through watch listening.
Available APIs
ImageKnife Components
| Name | Parameter | Description |
|---|---|---|
| ImageKnifeComponent | ImageKnifeOption | Image display component. |
| ImageKnifeAnimatorComponent | ImageKnifeOption, AnimatorOption | Animated image control component. |
AnimatorOption Parameters
| Name | Type | Description |
|---|---|---|
| state | AnimationStatus | Playback status. Optional. |
| iterations | number | Number of playback times. Optional. |
| reverse | boolean | Playback order. Optional. |
| onStart | ()=>void | Triggered when the animation starts. Optional. |
| onFinish | ()=>void | Triggered when the animation finishes or stops. Optional. |
| onPause | ()=>void | Triggered when the animation pauses. Optional. |
| onCancel | ()=>void | Triggered when the animation is canceled, that is, when it is reset to its initial state. Optional. |
| onRepeat | ()=>void | Triggered when the animation repeats. Optional. |
ImageKnifeOption Parameters
| Name | Type | Description |
|---|---|---|
| loadSrc | string, PixelMap, Resource | Main image. |
| placeholderSrc | PixelMap, Resource | Placeholder image. Optional. |
| errorholderSrc | PixelMap, Resource | Error image. Optional. |
| objectFit | ImageFit | How the main image is resized to fit its container. Optional. |
| placeholderObjectFit | ImageFit | How the placeholder image is resized to fit its container. Optional. |
| errorholderObjectFit | ImageFit | How the error image is resized to fit its container. Optional. |
| writeCacheStrategy | CacheStrategyType | Cache writing strategy. Optional. |
| onlyRetrieveFromCache | boolean | Whether to skip network and local requests. Optional. |
| customGetImage | customGetImage?:(context: Context, src: string, PixelMap, Resource ,headers?: Record<string, Object>) => Promise<ArrayBuffer, undefined> | Custom image download. Optional. |
| border | BorderOptions | Border corner. Optional. |
| priority | taskpool.Priority | Load priority. Optional. |
| context | common.UIAbilityContext | Context. Optional. |
| progressListener | (progress: number)=>void | Progress. Optional. |
| signature | String | Custom cache signature. Optional. |
| headerOption | Array | Request headers. Optional. |
| transformation | PixelMapTransformation | Image transformation. Optional. |
| drawingColorFilter | ColorFilter, drawing.ColorFilter | Drawing color filter. Optional. |
| onComplete | (event:EventImage, undefined) => void | Callback for image loading completion. Optional. |
| onLoadListener | onLoadStart?: (req?: ImageKnifeRequest) => void,onLoadSuccess?: (data: string | PixelMap | undefined, imageData: ImageKnifeData, req?: ImageKnifeRequest) => void,onLoadFailed?: (err: string, req?: ImageKnifeRequest) => void,onLoadCancel?: (res: string, req?: ImageKnifeRequest) => void | Callback for image loading events. |
| downsampleOf | DownsampleStrategy | Downsampling. Optional. |
| httpOption | HttpRequestOption | Network request configuration. Optional. |
| pixelName | string | PixelMap naming. Optional. |
| dynamicRangeMode | DynamicRangeMode | Dynamic range of the image to be displayed. Optional. |
Downsampling Types
| Type | Description |
|---|---|
| NONE | No downsampling. |
| AT_MOST | No upscaling is performed if the requested size is larger than the actual size. |
| FIT_CENTER_MEMORY | Auto-adaptation, with memory prioritized. |
| FIT_CENTER_QUALITY | Auto-adaptation, with quality prioritized. |
| CENTER_INSIDE_MEMORY | Auto-adaptation, with memory prioritized based on the maximum aspect ratio. |
| CENTER_INSIDE_QUALITY | Auto-adaptation, with quality prioritized based on the maximum aspect ratio. |
| AT_LEAST | Auto-adaptation with the minimum aspect ratio. |
ImageKnife APIs
| Name | Type | Description |
|---|---|---|
| initMemoryCache | newMemoryCache: IMemoryCache | Initializes a custom memory cache strategy. |
| initFileCache | context: Context, size: number, memory: number | Initializes the file cache size and quantity. |
| reload | request: ImageKnifeRequest | Reloads the image. |
| preLoad | loadSrc: string I ImageKnifeOption | Preloads and returns the image request. |
| cancel | request: ImageKnifeRequest | Cancels an image request. |
| preLoadCache | loadSrc: string I ImageKnifeOption | Preloads and returns the file cache path. |
| getCacheImage | loadSrc: string, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string) | Obtains resources from memory or file cache. |
| addHeader | key: string, value: Object | Adds a global HTTP request header. |
| setHeaderOptions | Array | Sets global HTTP request headers. |
| deleteHeader | key: string | Deletes a global HTTP request header. |
| setCustomGetImage | customGetImage?:(context: Context, src: string, PixelMap, Resource ,headers?: Record<string, Object>) => Promise<ArrayBuffer, undefined> | Sets global custom download. |
| setEngineKeyImpl | IEngineKey | Sets a global cache key generation strategy. |
| putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string | Writes data to the memory disk cache. |
| removeMemoryCache | url: string, ImageKnifeOption | Removes the specified memory cache. |
| removeFileCache | url: string, ImageKnifeOption | Removes the specified disk cache. |
| getCacheLimitSize | cacheType?: CacheStrategy | Obtains the maximum size of the specified cache. |
| getCurrentCacheNum | cacheType?: CacheStrategy | Obtains the number of cached images. |
| getCurrentCacheSize | cacheType?: CacheStrategy | Obtains the current size of the specified cache. |
| getCurrentCacheSize | cacheType?: CacheStrategy | Obtains the current size of the specified cache. |
Callbacks
| Name | Field | Description |
|---|---|---|
| onLoadStart | req: ImageKnifeRequest | req: image request information, such as the image URL and the width and height of the component. ImageKnifeRequest contains ImageKnifeData, which includes the start time of the request and the time when the memory cache is checked. |
| onLoadSuccess | data: string, PixelMap, undefined, imageData: ImageKnifeData, req?: ImageKnifeRequest | data: result data of the successful load. imageData: information about the image stored in the cache. req: image request information. The ImageKnifeData contains the original image size, decoded image size, format, image frame, request end time, disk check time, network request start and end times, and image decoding start and end times. |
| onLoadFailed | err: string, req?: ImageKnifeRequest | err: error information. req: image request information. The ImageKnifeData within it includes error information (ErrorInfo and TimeInfo). ErrorInfo contains the error phase, error code, and network request error code. TimeInfo includes the request end time, disk check time, network request start and end times, and image decoding start and end times. |
| onLoadCancel | reason: string, req?: ImageKnifeRequest | reason: reason for canceling the callback. req: image request information. The ImageKnifeData within it includes error information (ErrorInfo and TimeInfo). ErrorInfo contains the error phase, error code, and network request error code. TimeInfo includes the request end time, disk check time, network request start and end times, and image decoding start and end times. |
Graphic Transformation Types (GPUImage Dependency Required)
| Type | Description |
|---|---|
| BlurTransformation | Blurs the image. |
| BrightnessTransformation | Applies a brightness filter. |
| CropSquareTransformation | Crops the image to a square. |
| CropTransformation | Crops the image to a custom rectangle. |
| GrayScaleTransformation | Applies a grayscale filter. |
| InvertTransformation | Applies an inversion filter. |
| KuwaharaTransformation | Applies a Kuwahara filter (using GPUImage). |
| MaskTransformation | Applies a mask. |
| PixelationTransformation | Applies a pixelation filter (using GPUImage). |
| SepiaTransformation | Applies a sepia filter (using GPUImage). |
| SketchTransformation | Applies a sketch filter (using GPUIImage). |
| SwirlTransformation | Applies a swirl filter (using GPUImage). |
| ToonTransformation | Applies a cartoon filter (using GPUImage). |
| VignetterTransformation | Applies a vignette filter (using GPUImage). |
Downloading and Installing the GPUImage Dependency
Method 1: In the Terminal window, run the following command to install the third-party HAR. DevEco Studio will automatically add the HAR as a dependency to the oh-package.json5 file of the project.
ohpm install @ohos/gpu_transform
Method 2: Set the third-party HAR as a dependency in the oh-package.json5 file of the project. The following is a configuration example:
"dependencies": {
"@ohos/gpu_transform": "^1.0.2"
}
Constraints
This project has been verified in the following version: DevEco Studio 5.1.0 Release(5.1.0.849), SDK: API18 Release(5.1.0.849)
Directory Structure
/ImageKnife # Project root directory
├── entry # Sample code folder
├── library # ImageKnife library folder
│ ├── src/main/ets
│ │ ├── 3rd_party # MD5 hash algorithm implementation
│ │ ├── cache # Cache-related implementation
│ │ ├── components # Component implementation
│ │ ├── downsampling # Image downsampling
│ │ ├── key # Cache key generation
│ │ ├── loaderStrategy # Image loading strategy
│ │ ├── model # Data model
│ │ ├── parseStrategy # Image parsing strategy
│ │ ├── queue # Request queue
│ │ ├── transform # Image transformation
│ │ ├── utils # Utility classes
│ │ ├── ImageKnife.ets # Core class
│ │ ├── ImageKnifeDispatcher.ets # Request dispatcher
│ │ └── ImageKnifeLoader.ets # Image loader
│ └── index.ets # Export library APIs
├── sharedlibrary # Used to verify ImageKnife library's cross-module image reading functionality
├── gpu_transform # GPU transformation related module
├── README.md # English installation and usage instructions
└── README_zh.md # Chinese installation and usage instructions
About Obfuscation
- For details, see Code Obfuscation.
- To prevent the imageknife library from being obfuscated, add exclusion rules to the obfuscation-rules.txt configuration file.
-keep
./oh_modules/@ohos/imageknife
How to Contribute
If you find any problem during the use, submit an issue or a PR to us.
License
This project is licensed under Apache License 2.0.
Known Issues
- The ImageFit property cannot be set for the ImageKnifeAnimator component.