用户可用于高效加载和缓存图片,支持本地、网络图片及动图展示。项目提供ArkTs和C两种API,具备自定义缓存策略、图片变换、进度监听等功能,加载速度快且支持生命周期管理。
Access rate limit exceeded. Please log in to continue.
ImageKnifepro
This project is developed based on ImageKnife.
Introduction
imageknifepro is an image loading and caching library designed for OpenHarmony — the C implementation of ImageKnife, built for higher performance, a smaller footprint, and simpler integration. The main features are as follows:
- 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
- Custom decoding
- Custom file cache
- Listening for network download progress through callbacks
- Image options for borders and rounded corners
- Image scaling with objectFit, including auto-adapting height
- ImageKnifeComponent supports image repeating with objectRepeat
- Concurrent request management with priority queuing
- No requests made for images whose lifecycle has been destroyed
- Custom cache key generation strategy
- Custom HTTP request headers
- Cache storage control (memory or file cache, or no cache) with writeCacheStrategy
- Image preloading with preLoad
- Image loading only from cache with onlyRetrieveFromCache
- Image downsampling and decoding
- Single or multiple image transformations such as blurring and highlighting
- ImageKnifeComponent supports both animated and static images.
- Animated images support playback controls such as play and pause, and support both batch decoding mode and frame-by-frame decoding mode.
- Graphic transformation effects can be applied to animated images.
- Custom image file formats are supported.
- Thumbnail loading is supported.
- Little-endian file caching is supported, along with enabling file extensions via cache names.
- Static DNS rules are supported.
- CRC32 checksum verification and retrying with backup URLs are supported.
Compared to the ImageKnife ArkTS version, the main improvements of imageknifepro are as follows:
- Provides both ArkTS API and C API: usable as ArkTS components in ArkTS apps, or as native components via C API.
- Uses the system Network Kit C API for downloads and the system Image C API for rendering, resulting in faster image loading.
- Supports customizable interceptors (network download, decoding, file caching, memory caching) via C API only, based on a responsibility-chain pattern allowing multiple custom loaders per request.
Installation
ohpm install @ohos/imageknifepro
For more information on OpenHarmony ohpm environment setup, see How to install OpenHarmony HAR.
Constraints
Compatibility
OpenHarmony API Version >= 15
Verified on the following version:
- DevEco Studio: 6.1.1.300; ROM: 6.1.0.135
Initialization Example
ImageKnifePro initialization is optional but recommended to enable file caching and improve performance. Call initialization in the Ability
onCreate(or equivalent) lifecycle when possible.
import { CacheStrategy, ImageKnife } from '@ohos/imageknifepro';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// Initialize file cache: (context, max items, max size in bytes)
ImageKnife.getInstance().initFileCache(this.context, 256, 256 * 1024 * 1024);
// Optional: adjust memory cache limits (strategy, max items, max bytes)
ImageKnife.getInstance().setCacheLimit(CacheStrategy.MEMORY, 256, 64 * 1024 * 1024);
// Optional: set max concurrent requests
ImageKnife.getInstance().setMaxRequests(9);
}
}
Quick Start Example
The example below shows a full flow from initialization to displaying a remote image.
import { ImageKnifeComponent, ImageKnifeOption, ImageKnife } from '@ohos/imageknifepro'
@Entry
@Component
struct QuickStartPage {
// 1. Configure image loading options
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: 'https://www.example.com/example.png', // Main image URL
placeholderSrc: $r('app.media.loading'), // Placeholder
errorSrc: $r('app.media.error'), // Error image
}
build() {
Column() {
// 2. Display image
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
ImageKnifeComponentV2 Example
import { ImageKnifeComponentV2, ImageKnifeOptionV2, ImageKnife, ImageInfo } from '@ohos/imageknifepro'
@Entry
@ComponentV2
struct QuickStartPageV2 {
// 1. Define image loading options as a single @Local option object
@Local option: ImageKnifeOptionV2 = {
loadSrc: 'https://www.example.com/example.png',
placeholderSrc: $r('app.media.loading'),
errorSrc: $r('app.media.error'),
objectFit: ImageFit.Cover,
border: { radius: 20 },
}
build() {
Column() {
// 2. Display image using V2 component
ImageKnifeComponentV2({
imageKnifeOption: this.option,
}).width(200).height(200)
}
}
}
ImageKnifeViewV2 Example
import { ImageKnifeViewV2, ImageKnifeOptionV2, ImageKnife } from '@ohos/imageknifepro'
@Entry
@ComponentV2
struct ViewV2Example {
// 1. Define image loading options as a single @Local option object
@Local option: ImageKnifeOptionV2 = {
loadSrc: 'https://www.example.com/example.png',
placeholderSrc: $r('app.media.loading'),
errorSrc: $r('app.media.error'),
}
build() {
Column() {
ImageKnifeViewV2({
imageKnifeOption: this.option,
}).width(200).height(200)
}
}
}
How to Use
Displaying a Local Resource Image
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc: $r("app.media.app_icon"),
placeholderSrc: $r("app.media.loading"),
thumbnailSrc:$r("app.media.app_icon"),
errorSrc: $r("app.media.error"),
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Displaying a File From Local Context Files
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc: "file:/data/storage/el2/base/haps/entry/files/example_cache_file",
placeholderSrc: "file:/data/storage/el2/base/haps/entry/files/localFile",
thumbnailSrc: "file:/data/storage/el2/base/haps/entry/files/localImage",
errorSrc: "file:/data/storage/el2/base/haps/entry/files/example_cache_fileTest",
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Displaying a Network Image
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:"https://www.example.com/example.png",
placeholderSrc: "https://www.example.com/example_placeholder.png",
thumbnailSrc:"https://www.example.com/example_thumbnail.png",
errorSrc: "https://www.example.com/example_errorSrc.png",
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Listening for Network Download Progress
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:"https://www.example.com/example.png",
progressListener:(progress:number) => {
console.info("ImageKinfe:: call back progress = " + progress)
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Setting Border Options
The
BorderOptionstype used byborderis a universal attribute in ArkUI.
The border radius you set is constrained by the component's dimensions. It is recommended that the maximum radius not exceed half of the component’s width or height; otherwise, irregular (non-uniform) rounded corners will be rendered. ArkUI documentation on borderRadius
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.test"),
border: {radius:50, width:1, color:Color.red}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Setting Component Draggable
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.test")
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption,
imageDraggable:true
}).width(200).height(200)
}
}
}
Setting Component Content Transition
Note: The content transition effect does not take effect on devices with API version lower than 21.
ImageKnifeComponent({
imageKnifeOption: {
loadSrc: $r("app.media.test"),
},
contentTransition:ContentTransitionType.OPACITY
}).width(100).height(100)
Listening for Image Loading State
Choose callback event that you need.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.rabbit'),
onLoadListener: {
onLoadStart: (imageInfo) => {
console.info('Load start, requestId: ' + imageInfo.requestId)
},
onLoadFailed: (err, imageInfo) => {
console.error('Load failed: ' + err)
},
onLoadSuccess: (imageInfo) => {
console.info('Load Successful')
},
onLoadCancel: (reason, imageInfo) => {
console.info('Load cancelled: ' + reason)
},
onMemorySuccess: (imageInfo) => {
console.info('Load from memory')
},
onDownloadSuccess: (imageInfo) => {
console.info('Image Download succeeded')
},
onDecodeSuccess: (imageInfo) => {
console.info('Image Decode succeeded')
},
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Using syncLoad
Note: Only set
syncLoadtotruefor small local Resource images. Do not use synchronous loading for network images or large images.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.pngSample")
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption,
syncLoad:true
}).width(200).height(200)
}
}
}
Using ImageKnifeComponent Display Animate Image
You can use animatorOption to control the animation playback, pause, playback times, and listen for corresponding events.
import { ImageKnifeComponent, ImageKnifeOption, AnimatorOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:"https://www.example.com/example_animation.gif",
placeholderSrc:$r('app.media.loading'),
errorSrc:$r('app.media.failed'),
animationDecodeMode:AnimationDecodeMode.AUTO
}
@State animatorOption: AnimatorOption = {
state: AnimationStatus.Running,
iterations: -1,
onFinish: () => {
LogUtil.info('ImageKnifeAnimatorComponent animatorOption onFinish')
},
onStart: () => {
LogUtil.info('ImageKnifeAnimatorComponent animatorOption onStart')
},
onPause: () => {
LogUtil.info('ImageKnifeAnimatorComponent animatorOption onPause')
},
onCancel: () => {
LogUtil.info('ImageKnifeAnimatorComponent animatorOption onCancel')
},
onRepeat: () => {
LogUtil.info('ImageKnifeAnimatorComponent animatorOption onRepeat')
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption,
animatorOption:this.animatorOption
}).width(200).height(200)
}
}
}
Obtaining Image Loading Information Through Callbacks
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc: $r('app.media.pngSample'),
objectFit: ImageFit.Contain,
onLoadListener: {
onLoadStart: (imageInfo) => {
let startCallBackData = JSON.stringify(imageInfo);
},
onLoadFailed: (err, imageInfo) => {
let failedBackData = err + ";" + JSON.stringify(imageInfo);
},
onLoadSuccess: (imageInfo) => {
let successBackData = JSON.stringify(imageInfo);
},
onLoadCancel: (reason, imageInfo) => {
let cancelBackData = reason + ";" + JSON.stringify(imageInfo);
}
},
border: { radius: 50 },
onComplete: (event) => {
if (event && event.loadingStatus == 0) {
let render_success = JSON.stringify(Date.now())
}
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Image Downsampling
import { ImageKnifeComponent, ImageKnifeOption, DownSamplingStrategy } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading"),
downSampling: DownSamplingStrategy.FIT_CENTER_QUALITY
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Transformation of a Single Graphic
import { ImageKnifeComponent, ImageKnifeOption, TransformationType } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading"),
transformationOption: {
type:TransformationType.BRIGHTEN,
f32:[0.21]
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Transformation of Multiple Graphics
import { ImageKnifeComponent, ImageKnifeOption, TransformationType } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading"),
multiTransformationOption: [
{
type:TransformationType.GAUSSIAN_BLUR,
f32:[12]
},
{
type:TransformationType.BRIGHTEN,
f32:[0.21]
},
{
type:TransformationType.INVERT
}
]
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Transformation of Common Crop Scale
import { ImageKnifeComponent, ImageKnifeOption, TransformationType, CommonCropScaleData } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:$r("app.media.pngSample"),
placeholderSrc:$r("app.media.loading"),
transformationOption: {
type:TransformationType.COMMON_CROP_SCALE, // crop first, then scale
onCommonCropScale: (pixelmapWidth: number, pixelmapHeight: number,
originWidth: number, originHeight: number)=> {
// custom callback to specify the cropping region and scaling factors
let data = new CommonCropScaleData();
data.region = {x:pixelmapWidth/4, y:0, size:{width:pixelmapWidth/2, height:pixelmapHeight}}
data.scaleX = 1
data.scaleY = 0.5
return data
}
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
CRC32 Checking And Fallback Urls
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:"https://www.example.com/example.png",
placeholderSrc:$r("app.media.loading"),
crc32: 1218992157,
fallbackUrls:[
"https://www.example.com/fallbackUrl01.png",
"https://www.example.com/fallbackUrl02.png",
]
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Static DNS Rule
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption:ImageKnifeOption = {
loadSrc:"https://www.example.com/example.png",
placeholderSrc:$r("app.media.loading"),
dnsOption:{
staticDnsRule:[
{host:"www.example.com", port:80, ipAddresses:["192.168.11.22"]},
]
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption:this.imageKnifeOption
}).width(200).height(200)
}
}
}
Setting the PixelMap Name
Use the
pixelNameproperty on the main image to assist in diagnosing image memory issues.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
pixelName: "ImageKnife pixel"
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Setting Image Orientation
Use the
orientationproperty on the main image to specify the desired display orientation.
By default, the image’s EXIF metadata is used to determine orientation, supporting both rotation and mirroring.
You can also explicitly set a specific orientation.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
orientation: Orientation.RIGHT
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
DynamicRange
Sets the dynamic range for the main image. By default, it is automatically determined based on the image content.
You can explicitly specify SDR (Standard Dynamic Range) or force HDR (High Dynamic Range) mode.
Currently, onlyImageKnifeComponentsupports HDR.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
dynamicRange: DynamicRange.HDR
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Resizing During Image Stretching
Use the
resizeableoption to define fixed margins that remain unchanged when the image is stretched. Applied to the main image.
This setting has no effect iftop + bottomexceeds the original image height orleft + rightexceeds the original image width.
Specify the number of pixels (in vp units) to keep unchanged on each side during stretching.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
resizeable: {
left: 50,
top: 50,
right: 50,
bottom: 100
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption,
}).width(200).height(200)
}
}
}
Load Only from Cache
Use the
onlyRetrieveFromCacheproperty. If the image is not present in the cache, loading fails immediately without attempting to download.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
onlyRetrieveFromCache: true
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Priority – Loading Priority
Three priority levels are supported: HIGH, MEDIUM, and LOW.
When the number of concurrent image loading requests exceeds the configured maximum, new requests are queued, and execution order within the queue follows this priority.
Local resources and images with existing file cache bypass the queue and load immediately (since no network download is needed).
Images already in memory cache are displayed directly without spawning background loading tasks.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
priority: Priority.HIGH
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Image Color Filtering
Use the
drawingColorFilterproperty to apply a color filter. Recommended primarily for SVG images.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
import { drawing } from '@kit.GraphicsDrawingKit'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r("app.media.svgIcon"),
drawingColorFilter: {
color: { alpha: 255, red: 255, green: 1, blue: 1 },
mode: drawing.BlendMode.SRC_IN
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Image Memory Allocation Mode
Use the
allocationModeproperty to control memory allocation strategy. By default, the mode is automatically selected based on image format and dimensions.
SVG images do not support DMA memory.
DMA memory allocation helps avoid texture upload overhead during rendering of large images.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
allocationMode: AllocationMode.DMA
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Manually Triggering imageKnifeOption Property Watch
To reduce overhead,
imageKnifeOptiononly observes changes at the top level of its properties. Deep nested changes won’t trigger an update.
Modify theforceWatchvalue—a dummy property unrelated to loading—to explicitly trigger the watcher.
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
private count: number = 0;
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
placeholderSrc: $r("app.media.loading"),
dnsOption: {
staticDnsRule: [
{ host: "www.example.com", port: 80, ipAddresses: ["192.168.11.22"] },
]
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
Button("Modify Nested Property").onClick(() => {
this.imageKnifeOption.dnsOption?.staticDnsRule[0].ipAddresses.push("172.168.51.22");
// Trigger watcher by updating forceWatch
this.count += 1;
this.imageKnifeOption.forceWatch = this.count;
}).margin(10)
}
}
}
ImageKnifeView Component Auto-Adapts to Image Aspect Ratio
import { ImageKnifeViewV2, ImageKnifeOptionV2, ImageKnife } from '@ohos/imageknifepro'
@Entry
@ComponentV2
struct ViewV2Example {
@Local option: ImageKnifeOptionV2 = {
loadSrc: 'https://www.example.com/example.png',
placeholderSrc: $r('app.media.loading'),
errorSrc: $r('app.media.error'),
}
build() {
Column() {
ImageKnifeViewV2({
imageKnifeOption: this.option,
adaptable: true
})
.width(200) // Only width is set; height adjusts automatically based on image aspect ratio
}
}
}
Customizing Network Requests
Note: Custom implementations can only be done on the C side, as ArkTS functions cannot be called from C++ worker threads.
For details about the C-side custom network interceptor, see the example.
Customizing Graphic Transformation
Note: Custom implementations can only be done on the C side, as ArkTS functions cannot be called from C++ worker threads.
For details about the C-side custom graphic transformation, see the example.
Customizing File Format
Note: Custom implementations can only be done on the C side, as ArkTS functions cannot be called from C++ worker threads.
For details about the C-side custom file format, see the example.
Customizing Key Generator Object
Note: Custom implementations can only be done on the C side, as ArkTS functions cannot be called from C++ worker threads.
For details about the C-side custom key generator, see the example.
Reuse Scenario
Clear the component content in the aboutToRecycle lifecycle and trigger image loading through watch listening.
Example of ImageKnife Singleton Global Interface
The global singleton instance is obtained via
ImageKnife.getInstance(), which provides access to all singleton APIs. The global interface includes cache management, image preloading and cancellation, component pre-creation, global HTTP header configuration, global DNS settings, and more.
Image Cache Management
Provides APIs to query memory and file cache usage, limits, etc., as well as APIs to clear caches.
Also provides an API to add additional file cache instances (small-end file caches).
Small-End File Cache
ImageKnifePro supports two types of file caches:
- Big-End File Cache (default): Initialized via
initFileCache. All images share a single LRU space. - Small-End File Cache (additional instance): Added via
addSmallEndFileCache. Each instance has its own independent LRU space, completely isolated from the big-end cache.
Use Case: When you need independent management—such as separate storage paths or eviction policies—for specific images (e.g., avatars or icons), you can create a small-end file cache instance.
- You must specify a name and a sandbox subdirectory for the small-end instance.
- You can configure maximum file count and disk usage limits for the instance.
- Adding a small-end cache triggers asynchronous initialization; you can check
errorCodeto verify success. - It's recommended to add small-end file caches during the
onCreatephase of your application Ability.
// Create two independent small-end cache instances
ImageKnife.getInstance().addSmallEndFileCache("small end", this.context, "small_end")
ImageKnife.getInstance().addSmallEndFileCache("icon", this.context, "small_end_icon", 64, 64 * 1024 * 1024)
.then((errorCode) => {
if (errorCode != CacheErrorCode.SUCCESS) {
console.log("Create File Cache Small End Failed:" + errorCode)
}
})
When using in a component, specify the desired file cache instance via ImageKnifeOption.fileCacheName. If not configured, the default (big-end) file cache is used:
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct ExamplePage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "https://www.example.com/example.png",
placeholderSrc: $r("app.media.loading"),
fileCacheName: "small end"
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Cache Status Management
// Check if the default (big-end) file cache is initialized
let result = ImageKnife.getInstance().isFileCacheInit()
// Get max number of images allowed in memory cache
let memoryNum = ImageKnife.getInstance().getCacheLimitNum(CacheStrategy.MEMORY)
// Get max number of images allowed in file cache
let fileNum = ImageKnife.getInstance().getCacheLimitNum(CacheStrategy.FILE)
// Get max memory usage (in bytes) for memory cache
let memorySize = ImageKnife.getInstance().getCacheLimitSize(CacheStrategy.MEMORY)
// Get max disk usage (in bytes) for file cache
let fileSize = ImageKnife.getInstance().getCacheLimitSize(CacheStrategy.FILE)
// Get current number of images in memory cache
let currentMemoryNum = ImageKnife.getInstance().getCurrentCacheNum(CacheStrategy.MEMORY)
// Get current number of images in file cache
let currentFileNum = ImageKnife.getInstance().getCurrentCacheNum(CacheStrategy.FILE)
// Get current memory usage (in bytes)
let currentMemorySize = ImageKnife.getInstance().getCurrentCacheSize(CacheStrategy.MEMORY)
// Get current disk usage (in bytes)
let currentFileSize = ImageKnife.getInstance().getCurrentCacheSize(CacheStrategy.FILE)
// Enable file extension for file cache: after enabling, cached filenames in sandbox will include extensions.
// Recommended to configure once during the Ability's `onCreate` phase.
ImageKnife.getInstance().fileCacheEnableExtension()
// Adjust memory cache size. Recommended to configure once during the Ability's `onCreate` phase.
ImageKnife.getInstance().setCacheLimit(CacheStrategy.MEMORY, 256, 64 * 1024 * 1024)
For small-end file cache status management, use the corresponding APIs with the optional
cacheNameparameter. If omitted, operations apply to the default big-end cache. To manage a small-end instance, pass its name explicitly.
The following examples assume a small-end cache named"small end"has already been added:
// Check if the "small end" file cache is initialized
let result = ImageKnife.getInstance().isFileCacheInit("small end")
// Get max image count for the "small end" file cache
let fileNum = ImageKnife.getInstance().getCacheLimitNum(CacheStrategy.FILE, "small end")
// Get max disk usage (bytes) for the "small end" file cache
let fileSize = ImageKnife.getInstance().getCacheLimitSize(CacheStrategy.FILE, "small end")
// Get current image count in the "small end" file cache
let currentFileNum = ImageKnife.getInstance().getCurrentCacheNum(CacheStrategy.FILE, "small end")
// Get current disk usage (bytes) for the "small end" file cache
let currentFileSize = ImageKnife.getInstance().getCurrentCacheSize(CacheStrategy.FILE, "small end")
// Enable file extension for the "small end" cache
ImageKnife.getInstance().fileCacheEnableExtension("small end")
Clearing Caches
You can clear all caches or selectively clear specific ones.
File cache clearing operations are asynchronous.
// Clear all memory cache
ImageKnife.getInstance().removeAllMemoryCache()
// Clear specific memory cache entry by URL
ImageKnife.getInstance().removeMemoryCache("http://www.example.com/exampleImage.jpg")
// Clear specific memory cache entry by ImageKnifeOption (matches signature and post-processing)
ImageKnife.getInstance().removeMemoryCache({
loadSrc: "http://www.example.com/exampleImage.jpg",
transformationOption: {
type: TransformationType.GRAY_SCALE
},
signature: "for test" // Optional; different signatures yield different cache entries
})
// Clear all entries in the default (big-end) file cache
ImageKnife.getInstance().removeAllFileCache()
// Clear all entries in the "small end" file cache
ImageKnife.getInstance().removeAllFileCache("small end")
// Clear specific entry in big-end file cache by URL
ImageKnife.getInstance().removeFileCache("http://www.example.com/exampleImage.jpg")
// Clear specific entry in big-end file cache by ImageKnifeOption (with signature)
ImageKnife.getInstance().removeFileCache({
loadSrc: "http://www.example.com/exampleImage.jpg",
signature: "for test"
})
// Clear specific entry in small-end file cache by specifying fileCacheName and signature
ImageKnife.getInstance().removeFileCache({
loadSrc: "http://www.example.com/exampleImage.jpg",
fileCacheName: "small end",
signature: "for test" // Optional; different signatures yield different cache entries
})
Check if Cache Exists
By default, checks both memory and file caches; returns
falseonly if neither exists, otherwise returnstrue.
You can check only the memory cache or only the file cache.
To match a specific small-end file cache, specify the small-end cache name in thefileCacheNameproperty of theImageKnifeOptionpassed to the method.
let url = "www.example.image.test";
// Check both memory and file caches by default
let res = ImageKnife.getInstance().checkImageCache(url);
// Check only the memory cache
res = ImageKnife.getInstance().checkImageCache(url, CacheStrategy.MEMORY);
// Check only the file cache
res = ImageKnife.getInstance().checkImageCache(url, CacheStrategy.FILE);
// Check a specific small-end file cache
res = ImageKnife.getInstance().checkImageCache({ loadSrc: url, fileCacheName: "checkImageCache_20" }, CacheStrategy.FILE);
Image Preloading and Cancellation
Supports standard preloading, returning file paths, or returning PixelMap objects.
Most downsampling strategies rely on component-measured dimensions to calculate target decode size. Since preloading isn’t tied to any UI component, these strategies generally cannot be applied during preloading.
Once preloaded, subsequent component loads of the same image can directly use memory or file cache.
If a component initiates a load while the same image is still being preloaded, the requests are merged to avoid redundant loading.
Standard Preloading
// Preload a network image into both file and memory cache
let request = ImageKnife.getInstance().preload("http://www.example.com/exampleImage.jpg")
// Cancel the above preload request
ImageKnife.getInstance().cancel(request)
// Use ImageKnifeOption for detailed configuration and callbacks
ImageKnife.getInstance().preload({
loadSrc: "http://www.example.com/exampleImage.jpg",
transformationOption: {
type: TransformationType.GRAY_SCALE
},
allocationMode: AllocationMode.DMA,
onLoadListener: {
onLoadSuccess: (imageInfo) => {
console.log("request " + imageInfo.requestId + " load success")
},
onLoadFailed: (err, imageInfo) => {
console.log("request " + imageInfo.requestId + " load Failed:" + err)
}
}
})
// Often, preloading to file cache is sufficient without immediate display.
// Set writeCacheStrategy to FILE to skip memory caching and avoid decoding overhead.
ImageKnife.getInstance().preload({
loadSrc: "http://www.example.com/exampleImage.jpg",
writeCacheStrategy: CacheStrategy.FILE
})
Preload and Return Sandbox File Path
The returned sandbox path can be read directly via file APIs or passed to an ImageKnifeComponent for display.
To use with the system’s Image component, prepend"file:/".
// Using URL
let filePath = ImageKnife.getInstance().preloadCache("http://www.example.com/exampleImage.jpg")
// Using ImageKnifeOption
filePath = ImageKnife.getInstance().preloadCache({
loadSrc: "http://www.example.com/exampleImage.jpg",
onLoadListener: {
onLoadSuccess: (imageInfo) => {
console.log("request " + imageInfo.requestId + " load success")
},
onLoadFailed: (err, imageInfo) => {
console.log("request " + imageInfo.requestId + " load Failed:" + err)
}
}
})
Load Image and Return PixelMap
Returns a PixelMap wrapper object. Depending on whether the image is animated, it may contain one or multiple frames.
It’s strongly recommended to callpixelmap.release()after use to promptly reduce memory reference counts. Relying on GC may cause high peak memory usage.
let localPixelmap: Pixelmap | undefined = undefined;
// Load and get PixelMap using URL
ImageKnife.getInstance().getCacheImage("http://www.example.com/exampleImage.jpg").then((imageKnifeData) => {
if (imageKnifeData != undefined) {
if (imageKnifeData?.frameCount as number >= 1 && imageKnifeData?.pixelmapList != undefined) {
let arr = imageKnifeData?.pixelmapList as Array<PixelMap>
// Assume we only need the first (static) frame
localPixelmap = arr[0];
// Release extra frames immediately
for (let i = 1; i < imageKnifeData.pixelmapList.length; i++) {
imageKnifeData.pixelmapList[i].release()
}
}
}
})
Using ImageKnifeOption with explicit cache strategy:
let localPixelmap: Pixelmap | undefined = undefined;
let option: ImageKnifeOption = {
loadSrc: "http://www.example.com/exampleImage.jpg",
onLoadListener: {
onLoadSuccess: (imageInfo) => {
console.log("request " + imageInfo.requestId + " load success")
},
onLoadFailed: (err, imageInfo) => {
console.log("request " + imageInfo.requestId + " load Failed:" + err)
}
}
}
/**
* Load and get PixelMap using ImageKnifeOption, attempting to fetch only from memory cache.
* CacheStrategy options:
* - DEFAULT: try memory then file cache
* - MEMORY: only memory cache
* - FILE: only file cache
* - NONE: bypass cache and load fresh
*/
ImageKnife.getInstance().getCacheImage(option, CacheStrategy.MEMORY).then((imageKnifeData) => {
if (imageKnifeData != undefined) {
if (imageKnifeData?.frameCount as number >= 1 && imageKnifeData?.pixelmapList != undefined) {
let arr = imageKnifeData?.pixelmapList as Array<PixelMap>
localPixelmap = arr[0];
for (let i = 1; i < imageKnifeData.pixelmapList.length; i++) {
imageKnifeData.pixelmapList[i].release()
}
}
}
})
Retry on Load Failure
ImageKnife does not automatically retry failed loads, but provides a
reloadAPI. Business logic should control retry count and intervals.
import { ImageKnifeComponent, ImageKnifeOption, ImageKnife } from '@ohos/imageknifepro'
@Entry
@Component
struct TestPage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: 'https://www.example.com/example.png',
onLoadListener: {
onLoadFailed: (err, imageInfo) => {
// Retry using the failed request's ID
ImageKnife.getInstance().reload(imageInfo.requestId)
}
}
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption
}).width(200).height(200)
}
}
}
Global Custom DNS Configuration
Supports global static and dynamic DNS settings.
If both are configured, dynamic DNS takes precedence.
Recommended to configure once during the Ability’sonCreatephase.
// Set global static DNS rules
ImageKnife.getInstance().setGlobalDnsOption({
staticDnsRule: [
{ host: "www.example.com", port: 80, ipAddresses: ["192.168.1.254", "192.189.7.3"] },
{ host: "www.test.com", port: 80, ipAddresses: ["192.168.88.24"] },
]
})
// Dynamic DNS callback: return IP list based on custom logic
function dynamicDnsCallback(host: string, port: number): Promise<Array<string>> {
return new Promise<Array<string>>((resolve) => {
let arr: Array<string> = []
if (host == "www.example.com") {
arr.push("192.168.98.77")
arr.push("192.168.198.27")
} else {
arr.push("192.168.19.22")
}
resolve(arr);
});
}
// Set global dynamic DNS with timeout (in milliseconds); if timeout, proceed with normal download
ImageKnife.getInstance().setGlobalDynamicDns(dynamicDnsCallback, 60)
Global Load Completion Callback
Recommended to set once during the Ability’s
onCreatephase.
Triggered on success, failure, or cancellation. Useful for unified telemetry.
ImageKnife.getInstance().setGlobalLoadEndCallback((
src: string, // Image source (e.g., URL)
requestType: string, // Request type: main, placeholder, thumbnail, error image
isSuccess: boolean, // Whether load succeeded
timeInfo?: TimeInfo, // Timing info for each stage
errorCode?: string, // Error code on failure
errorMessage?: string, // Error message
requestHeader?: string, // HTTP request headers
responseHeader?: string // HTTP response headers
) => {
// Example: log for analytics
console.log("ON_LOAD_END src:" + src + " requestType:" + requestType + " isSuccess:" + isSuccess +
" timeInfo:" + JSON.stringify(timeInfo) + " errorCode:" + errorCode + " errorMessage:" + errorMessage +
" requestHeader:" + requestHeader + " responseHeader:" + responseHeader)
})
JPEG Decoding Optimization
Recommended to configure once during the Ability’s
onCreatephase.
Disabled by default.
When enabled (true), reduces memory footprint of decoded JPEGs.
Note: Optimization is disabled if transformations (e.g., grayscale) are applied—default decoding is used instead.
When enabled,getCacheImagemay return PixelMaps in non-RGBA formats.
// Enable JPEG decoding optimization
ImageKnife.getInstance().setJpegOptimizeDecoding(true)
// Check current setting
let result = ImageKnife.getInstance().getJpegOptimizeDecoding()
PNG Decoding Optimization
Recommended to configure once during the Ability’s
onCreatephase.
Disabled by default.
When enabled (true), reduces memory footprint of decoded PNGs.
Note: Optimization is disabled if transformations are applied—default decoding is used instead.
Note: Optimization is disabled if the PNG may contain transparency/Alpha—default decoding is used instead.
When enabled,getCacheImagemay return PixelMaps in non-RGBA formats.
// Enable PNG decoding optimization
ImageKnife.getInstance().setPngOptimizeDecoding(true)
// Check current setting
let result = ImageKnife.getInstance().getPngOptimizeDecoding()
WebP Decoding Optimization
Recommended to configure once during the Ability’s
onCreatephase.
Disabled by default.
When enabled (true), reduces memory footprint of decoded WebPs.
Note: Optimization is disabled if transformations are applied—default decoding is used instead.
Note: Optimization is disabled if the WebP may contain transparency/Alpha (including animated frames)—default decoding is used instead.
When enabled,getCacheImagemay return PixelMaps in non-RGBA formats.
// Enable WebP decoding optimization
ImageKnife.getInstance().setWebpOptimizeDecoding(true)
// Check current setting
let result = ImageKnife.getInstance().getWebpOptimizeDecoding()
HEIC Decoding Optimization
Recommended to configure once during the Ability’s
onCreatephase.
Disabled by default.
When enabled (true), reduces memory footprint of decoded HEICs.
Note: Optimization is disabled if transformations are applied—default decoding is used instead.
Note: Optimization is disabled if the HEIC may contain transparency/Alpha—default decoding is used instead.
When enabled,getCacheImagemay return PixelMaps in non-RGBA formats.
// Enable HEIC decoding optimization
ImageKnife.getInstance().setHeicOptimizeDecoding(true)
// Check current setting
let result = ImageKnife.getInstance().getHeicOptimizeDecoding()
Add/Remove Global HTTP Headers
Recommended to configure global headers during the Ability’s
onCreatephase.
// Add multiple headers at once
ImageKnife.getInstance().setHeaderOptions([
{
key: "User-Agent",
value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124"
},
{
key: "imageTag",
value: "test"
}
])
// Remove a specific header
ImageKnife.getInstance().deleteHeader("imageTag")
Add External PixelMap to ImageKnife Cache
For scenarios where you already have a PixelMap and want to inject it into ImageKnife’s cache.
// Assume you already have a PixelMap
let localPixelmap: Pixelmap = GetLocalPixelmap();
// Add to cache using a URL as the key (defaults to memory + file cache)
ImageKnife.getInstance().putCacheImage("http://www.example.com/exampleJpg", localPixelmap)
// Specify cache strategy, signature, and small-end cache name
ImageKnife.getInstance().putCacheImage("http://www.example.com/exampleJpg", localPixelmap, CacheStrategy.FILE,
"signature_1", "small end")
Component Pre-Creation
Currently supports only
ImageKnifeComponent.
Pre-creates and starts loading images ahead of time, so when navigating to the target page, the component can bind and display immediately—reducing perceived load time.
Avoid excessive pre-creation.
Pre-created components are linked toImageKnifeComponentvia a matchingcustomId.
Once bound, they behave like regular components (update/destroy normally).
// Pre-create a component with specified image content
ImageKnife.getInstance().preCreateImageKnifeComponent("customId_1", {
loadSrc: "http://www.example.com/exampleJpg",
transformationOption: {
type: TransformationType.GRAY_SCALE
},
})
In the target page, use the same customId to bind:
import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'
@Entry
@Component
struct TestPage {
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: "http://www.example.com/exampleJpg",
transformationOption: {
type: TransformationType.GRAY_SCALE
},
}
build() {
Column() {
ImageKnifeComponent({
imageKnifeOption: this.imageKnifeOption,
customId: "customId_1" // Must match pre-created component's ID
}).width(200).height(200)
}
}
}
Pre-Created Component Management
Set a max limit to prevent memory leaks from unbound pre-created components.
Explicitly release unbound components; bound ones remain unaffected.
// Set max number of pre-created components (default: 10)
ImageKnife.getInstance().setMaxPreCreateNodeCount(5)
// Release all unbound pre-created components
ImageKnife.getInstance().releasePreCreatedNode()
Clear Invisible Component Memory When Moving to Background
ImageKnife provides an interface to clear the memory of images in invisible components when the application moves to the background, and reloads these cleared images when the app comes back to the foreground. This reduces the memory footprint of the app while it is in the background.
Does not work on API levels below 15.
Needs to be called within the ability's onBackground and onForeground events.
There is a one-time cost associated with moving to the background and returning to the foreground.
import { Configuration, ConfigurationConstant, AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { ImageKnife } from '@ohos/imageknifepro';
export default class EntryAbility extends UIAbility {
// ...
onForeground(): void {
// Reload images that were cleared upon entering the foreground; requires reloadOnForeground to be enabled.
ImageKnife.getInstance().reloadOnForeground();
}
onBackground(): void {
// Clear images when moving to the background; requires clearOnBackground to be enabled.
ImageKnife.getInstance().clearOnBackground();
}
}
V2 Component Usage
imageknifepro provides V2 components supporting ComponentV2 decorators, with the following key differences from V1:
V1 vs V2 Core Differences
| Feature | V1 Components | V2 Components |
|---|---|---|
| Component Decorator | @Component |
@ComponentV2 |
| State Decorator | @State / @Link |
@ObservedV2 / @Trace |
| State Synchronization | Watch all top-level properties | Only monitor changes to properties that affect the main image loading state |
OHPM HAR Package Trimming for Avif
The HAR package of imageknifepro includes full functionality. If you don't need Avif format, you can remove the related .so files (libavif.so.16, libyuv.so) to reduce your app's size.
In the build-profile.json5 of the module using imageknifepro, configure the filter rules:
"buildOption": {
"nativeLib": {
"filter": {
"excludes": [
"x86_64/*",
"arm64-v8a/libyuv.so",
"arm64-v8a/libavif.so.16"
]
}
}
}
After applying this filter, Avif image support will be disabled, while all remaining features remain unaffected. If you're using source-code dependency, you can choose not to compile the Avif-related code. For details, see C API Usage Instructions.
C API Usage Instructions
Please refer to the ImageKnifePro C API Usage Guide.
Image Loading Update Priority
A single request in ImageKnifePro can be configured with four image sources: Main Image, Placeholder, Thumbnail, and Error Image (set via imageKnifeOption).
All four sources supportstring,resource, andpixelmaptypes.
Priority: Main Image > Thumbnail > Placeholder / Error Image.
Only the Main Image is required; the others are optional.
Changing the Main Image content in the associatedImageKnifeOptionwill trigger a new loading request. If the previous request is still loading, it will be canceled, and its display will be discarded.
If the Main Image's request state remains unchanged, changing the content of the Placeholder, Thumbnail, or Error Image will NOT trigger an update or initiate a new loading request, as the final visual output remains unaffected.
- Main Image (
loadSrc): The final content to be displayed. It has the highest loading priority. If the Main Image has already been rendered, other images will not be applied. Once the Main Image is loaded, it will override any other displayed images. - Placeholder (
placeholderSrc): Displayed as a placeholder while the Main Image is loading. It will be ignored and discarded if either the Main Image or the Thumbnail has already been rendered. - Thumbnail (
thumbnailSrc): Displayed as a placeholder while the Main Image is loading. It will be ignored and discarded if the Main Image has already been rendered. Unlike the Placeholder, the Thumbnail is typically a low-resolution version of the Main Image, whereas the Placeholder is unrelated to the Main Image. Once loaded, the Thumbnail will override the Placeholder. - Error Image (
errorSrc): Loading begins only after both the Main Image and the Thumbnail (if used) fail to load. Once the Error Image is loaded, it will override the Placeholder.
API Reference
ImageKnifeComponent
A standard image component provided by imageknifepro, implemented as a wrapper around the system Image component. Supports both static and animated images.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| imageKnifeOption | ImageKnifeOption | Yes | Image loading configuration |
| animatorOption | AnimatorOption | No | Animated image playback control |
| imageDraggable | boolean | No | Whether draggable; defaults to false |
| contentTransition | ContentTransitionType | No | Content transition effect; no effect below API 21 |
| imageExpandSafeArea | ExpandSafeAreaOption | No | Extend image display into the safe area (optional) |
| syncLoad | boolean | No | Synchronous loading; defaults to false; use only for small local Resource images |
| customId | string | undefined | No | ID of an associated pre-created component; must be used together with the pre-creation API (optional) Do not use pure numeric strings or strings starting with C_ followed by digits as customId, as these formats are reserved by ImageKnife.When this property is non-empty, it will associate with a pre-created component. |
ImageKnifeComponentV2
The V2 version of ImageKnifeComponent, implemented using the @ComponentV2 decorator. Supports both static and animated images. Use ImageKnifeOptionV2 for configuration.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| imageKnifeOption | ImageKnifeOptionV2 | Yes | Image loading configuration (V2) |
| animatorOption | AnimatorOptionV2 | undefined | No | Animated image playback control (V2) |
| imageDraggable | boolean | No | Whether draggable; defaults to false |
| contentTransition | ContentTransitionType | No | Content transition effect; no effect below API 21 |
| imageExpandSafeArea | ExpandSafeAreaOption | No | Extend image display into the safe area (optional) |
| syncLoad | boolean | No | Synchronous loading; defaults to false; use only for small local Resource images |
| customId | string | undefined | No | ID of an associated pre-created component; must be used together with the pre-creation API (optional) Do not use pure numeric strings or strings starting with C_ followed by digits as customId, as these formats are reserved by ImageKnife.When this property is non-empty, it will associate with a pre-created component. |
ImageKnifeView
A self-rendered component using Custom Node. Supports both static and animated images.
Supported
ImageFitmodes:Contain,Cover,Fill,None,ScaleDown,Auto. Implicit animations,ResizableOption, and HDR images are not supported.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| imageKnifeOption | ImageKnifeOption | Yes | Image loading configuration |
| animatorOption | AnimatorOption | No | Animated image playback control |
| imageDraggable | boolean | No | Whether draggable; defaults to false |
| adaptable | boolean | No | Whether the component size adapts to the image aspect ratio; defaults to false |
| syncLoad | boolean | No | Synchronous loading; defaults to false |
ImageKnifeViewV2
The V2 version of ImageKnifeView, implemented using the @ComponentV2 decorator. Uses Custom Node for self-rendering. Supports both static and animated images. Use ImageKnifeOptionV2 for configuration.
Supported
ImageFitmodes:Contain,Cover,Fill,None,ScaleDown,Auto. Implicit animations,ResizableOption, and HDR images are not supported.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| imageKnifeOption | ImageKnifeOptionV2 | Yes | Image loading configuration (V2) |
| animatorOption | AnimatorOptionV2 | undefined | No | Animated image playback control (V2) |
| imageDraggable | boolean | No | Whether draggable; defaults to false |
| adaptable | boolean | No | Whether the component size adapts to the image aspect ratio; defaults to false |
| syncLoad | boolean | No | Synchronous loading; defaults to false |
ImageKnifeAnimatorComponent
Not recommended; no longer maintained. Use
ImageKnifeComponentinstead.
An animated image component. When displaying a static image, it is treated as a single-frame animation. Limited by the system Animator: does not support per-frame decoding, HDR, rounded borders, ImageFit, draggable, ColorFilter, or ResizableOption.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| imageKnifeOption | ImageKnifeOption | Yes | Image loading configuration |
| animatorOption | AnimatorOption | Yes | Animated image playback control |
AnimatorOption
Animated image playback control options.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| state | AnimationStatus | No | Playback state |
| iterations | number | No | Number of playback iterations; -1 means infinite loop |
| reverse | boolean | No | Whether to play in reverse |
| onStart | () => void | No | Triggered when animation starts |
| onFinish | () => void | No | Triggered when animation finishes or stops |
| onPause | () => void | No | Triggered when animation is paused |
| onCancel | () => void | No | Triggered when animation returns to initial state |
| onRepeat | () => void | No | Triggered when animation repeats |
AnimatorOptionV2
The V2 version of AnimatorOption, implemented using the @ObservedV2 decorator. All fields are identical to AnimatorOption; each field is decorated with @Trace to enable fine-grained reactivity.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| state | AnimationStatus | No | Playback state |
| iterations | number | No | Number of playback iterations; -1 means infinite loop |
| reverse | boolean | No | Whether to play in reverse |
| onStart | () => void | No | Triggered when animation starts |
| onFinish | () => void | No | Triggered when animation finishes or stops |
| onPause | () => void | No | Triggered when animation is paused |
| onCancel | () => void | No | Triggered when animation returns to initial state |
| onRepeat | () => void | No | Triggered when animation repeats |
ImageKnifeOption
Image loading configuration for ImageKnifeComponent, ImageKnifeView, and ImageKnifeAnimatorComponent.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| loadSrc | string | PixelMap | Resource | Yes | Main image source |
| placeholderSrc | string | PixelMap | Resource | No | Placeholder image |
| thumbnailSrc | string | PixelMap | Resource | No | Thumbnail image |
| errorSrc | string | PixelMap | Resource | No | Error image |
| imageKnifeLoader | string | No | Non-default custom image loader |
| headerOption | Array<HeaderOptions> | No | Custom HTTP request headers |
| dnsOption | DnsOption | No | Custom DNS settings |
| signature | string | No | Custom cache signature. |
| pixelName | string | No | PixelMap memory name for the main image |
| objectFit | ImageFit | No | Main image fit mode |
| placeholderObjectFit | ImageFit | No | Placeholder image fit mode |
| thumbnailObjectFit | ImageFit | No | Thumbnail image fit mode |
| errorObjectFit | ImageFit | No | Error image fit mode |
| objectRepeat | ImageRepeat | No | Main image repeat mode |
| orientation | Orientation | No | Desired display orientation for the main image |
| dynamicRange | DynamicRange | No | Desired dynamic range for the main image |
| resizeable | ResizableOption | No | Resizable area options when the image is stretched |
| border | BorderOptions | No | Border and rounded corner settings |
| fileCacheName | string | No | Small-end file cache instance name to use |
| writeCacheStrategy | CacheStrategyType | No | Cache write strategy |
| onlyRetrieveFromCache | boolean | No | Load only from cache without making network requests |
| priority | Priority | No | Request priority |
| transformationOption | TransformationOption | No | Single graphic transformation |
| multiTransformationOption | Array<TransformationOption> | No | Multiple graphic transformations applied in order |
| context | common.UIAbilityContext | No | Page context |
| progressListener | (progress: number) => void | No | Network download progress callback (cross-thread delay applies) |
| onLoadListener | OnLoadCallBack | No | Image loading state callbacks |
| onComplete | (event: EventImage | undefined) => void | No | Image render completion callback |
| httpOption | HttpRequestOption | No | HTTP request settings |
| drawingColorFilter | (common2D.Color, drawing.BlendMode) | No | Image color filter |
| animationDecodeMode | AnimationDecodeMode | No | Animated image decoding mode |
| allocationMode | AllocationMode | No | PixelMap memory allocation mode; API 15+ only |
| downSampling | DownSamplingStrategy | No | Downsampling strategy |
| desiredSize | image.Size | undefined | No | Specified target size |
| crc32 | number | No | CRC32 checksum for verifying main image data integrity |
| fallbackUrls | Array<string> | No | Fallback URLs tried in order when the main image fails |
| forceWatch | number | No | Modify this property to forcibly trigger the component's watch on ImageKnifeOption. This property is unrelated to image loading. |
ImageKnifeOptionV2
The V2 version of ImageKnifeOption, implemented using the @ObservedV2 decorator and used by ImageKnifeComponentV2 and ImageKnifeViewV2. All fields are identical to ImageKnifeOption. The following fields are additionally decorated with @Trace to enable fine-grained reactivity:
loadSrc · signature · objectFit · objectRepeat · border · transformationOption · multiTransformationOption · context · downSampling · desiredSize · forceWatch
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| loadSrc | string | PixelMap | Resource | Yes | Main image source |
| placeholderSrc | string | PixelMap | Resource | No | Placeholder image |
| thumbnailSrc | string | PixelMap | Resource | No | Thumbnail image |
| errorSrc | string | PixelMap | Resource | No | Error image |
| imageKnifeLoader | string | No | Non-default custom image loader |
| headerOption | Array<HeaderOptions> | No | Custom HTTP request headers |
| dnsOption | DnsOption | No | Custom DNS settings |
| signature | string | No | Custom cache signature |
| pixelName | string | No | PixelMap memory name for the main image |
| objectFit | ImageFit | No | Main image fit mode |
| placeholderObjectFit | ImageFit | No | Placeholder image fit mode |
| thumbnailObjectFit | ImageFit | No | Thumbnail image fit mode |
| errorObjectFit | ImageFit | No | Error image fit mode |
| objectRepeat | ImageRepeat | No | Main image repeat mode |
| orientation | Orientation | No | Desired display orientation for the main image |
| dynamicRange | DynamicRange | No | Desired dynamic range for the main image |
| resizeable | ResizableOption | No | Resizable area options when the image is stretched |
| border | BorderOptions | No | Border and rounded corner settings |
| fileCacheName | string | No | Small-end file cache instance name to use |
| writeCacheStrategy | CacheStrategyType | No | Cache write strategy |
| onlyRetrieveFromCache | boolean | No | Load only from cache without making network requests |
| priority | Priority | No | Request priority |
| transformationOption | TransformationOption | No | Single graphic transformation |
| multiTransformationOption | Array<TransformationOption> | No | Multiple graphic transformations applied in order |
| context | common.UIAbilityContext | No | Page context |
| progressListener | (progress: number) => void | No | Network download progress callback (cross-thread delay applies) |
| onLoadListener | OnLoadCallBack | No | Image loading state callbacks |
| onComplete | (event: EventImage | undefined) => void | No | Image render completion callback |
| httpOption | HttpRequestOption | No | HTTP request settings |
| drawingColorFilter | DrawingColorFilter | No | Image color filter |
| animationDecodeMode | AnimationDecodeMode | No | Animated image decoding mode |
| allocationMode | AllocationMode | No | PixelMap memory allocation mode; API 15+ only |
| downSampling | DownSamplingStrategy | No | Downsampling strategy |
| desiredSize | image.Size | undefined | No | Specified target size |
| crc32 | number | No | CRC32 checksum for verifying main image data integrity |
| fallbackUrls | Array<string> | No | Fallback URLs tried in order when the main image fails |
| forceWatch | number | No | Modify this property to forcibly trigger the component's watch on ImageKnifeOptionV2. This property is unrelated to image loading. |
ImageInfo
Contains detailed information about the image loading request.
| Member Name | Type | Description |
|---|---|---|
| requestId | string | Image request ID |
| isMergedRequest | boolean | Whether the request was merged (shares the same loading process with remaining requests) |
| imageSourceFrom | ImageSourceFrom | The source from which the image is loaded |
| imageWidth | number | Original image width |
| imageHeight | number | Original image height |
| componentWidth | number | Component measured width |
| componentHeight | number | Component measured height |
| bufSize | number | Original image file size in bytes |
| type | ImageFormat | Original image format |
| customFormat | string | Custom image format description |
| httpCode | number | HTTP status code |
| frameCount | number | Number of image frames |
| decodeImages | Array<DecodeImageInfo> | Decoded image info list |
| transformationInfos | Array<TransformationInfo> | Graphic transformation info list |
| timeInfo | TimeInfo | Loading phase time info |
| errorInfo | ErrorInfo | Error info when loading fails |
ImageFormat
| Enum Value | Number | Description |
|---|---|---|
| UNKNOWN | 0 | Unknown format |
| JPG | 1 | JPEG |
| PNG | 2 | PNG |
| WEBP | 3 | WebP |
| BMP | 4 | BMP |
| GIF | 5 | GIF |
| SVG | 6 | SVG |
| TIFF | 7 | TIFF |
| HEIC | 8 | HEIC |
| ICO | 9 | ICO |
| CUSTOM_FORMAT | 10 | Custom format |
| AVIF | 11 | AVIF |
Priority
| Enum Value | Number | Description |
|---|---|---|
| HIGH | 0 | High priority |
| MEDIUM | 1 | Medium priority |
| LOW | 2 | Low priority |
DecodeImageInfo
| Member Name | Type | Description |
|---|---|---|
| contentWidth | number | Image width after decoding |
| contentHeight | number | Image height after decoding |
ErrorInfo
| Member Name | Type | Description |
|---|---|---|
| phase | string | Loading phase description |
| code | number | Error code |
TimeInfo
| Member Name | Type | Description |
|---|---|---|
| executeTime | number | Time when request is created and starts processing. For merged requests, may be later than decode time since loading was done by another request. |
| requestStartTime | number | Time when request starts loading. Same merged-request note applies. |
| requestEndTime | number | Request end time |
| requestCancelTime | number | Request cancellation time |
| memoryCheckStartTime | number | Memory cache read start time |
| memoryCheckEndTime | number | Memory cache read end time |
| diskCheckStartTime | number | File cache read start time |
| diskCheckEndTime | number | File cache read end time |
| loadImageStartTime | number | Image loading start time |
| loadImageEndTime | number | Image loading end time |
| decodeStartTime | number | Image decoding start time |
| decodeEndTime | number | Image decoding end time |
TransformationInfo
| Member Name | Type | Description |
|---|---|---|
| desc | string | Transformation description including parameter info |
| isSuccess | boolean | Whether the transformation succeeded |
| startTime | number | Transformation execution start time |
| endTime | number | Transformation execution end time |
CacheStrategy
| Enum Value | Number | Description |
|---|---|---|
| DEFAULT | 0 | Memory and file cache |
| MEMORY | 1 | Memory cache only |
| FILE | 2 | File cache only |
| NONE | 3 | No cache |
Orientation
Describes the desired image content display orientation.
| Enum Value | Number | Description |
|---|---|---|
| AUTO | 0 | Use the EXIF metadata carried by the image as the display orientation, supporting rotation and mirroring. |
| UP | 1 | Display according to the current pixel data of the image without any processing. |
| RIGHT | 2 | Display the current image rotated 90 degrees clockwise. |
| DOWN | 3 | Display the current image rotated 180 degrees clockwise. |
| LEFT | 4 | Display the current image rotated 270 degrees clockwise. |
DynamicRange
Specifies the desired dynamic range.
| Enum Value | Number | Description |
|---|---|---|
| AUTO | 0 | Automatically adapt based on the image. |
| SDR | 1 | Standard dynamic range. |
| HDR | 2 | High dynamic range. |
ImageSourceFrom
The source from which the image is loaded.
| Enum Value | Number | Description |
|---|---|---|
| UNKNOWN | 0 | Image source location; loading failed or incomplete. |
| FROM_MEMORY_CACHE | 1 | Image loaded from memory cache. |
| FROM_FILE_CACHE | 2 | Image loaded from file cache. |
| FROM_LOCAL_FILE | 3 | Image loaded from local resource file (raw file). |
| FROM_NETWORK_DOWNLOAD | 4 | Image loaded via network download. |
| FROM_PIXELMAP | 5 | Image displayed directly using the provided PixelMap. |
AnimationDecodeMode
Animation decoding mode; does not affect single-frame static images.
| Enum Value | Number | Description |
|---|---|---|
| AUTO | 0 | Automatically select based on resolution and frame count: batch decoding if width × height × frame count < 720 × 720 × 32, otherwise frame-by-frame. |
| BATCH_MODE | 1 | Batch decoding: all frames are decoded into memory at once, no decoding overhead during playback, but higher memory usage. |
| FRAME_MODE | 2 | Frame-by-frame decoding: each frame is decoded in real-time during playback, resulting in lower memory usage. |
AllocationMode
PixelMap memory allocation mode.
| Enum Value | Number | Description |
|---|---|---|
| AUTO | 0 | Automatically select the allocation mode based on image format and size. |
| DMA | 1 | Create the PixelMap using a DMA buffer (SVG images do not support this mode). |
| SHARE_MEMORY | 2 | Create the PixelMap using shared memory. |
ContentTransitionType
Content transition effect (takes effect when the component's displayed image is updated; does not apply to devices with API version lower than 21).
| Enum Value | Number | Description |
|---|---|---|
| IDENTITY | 0 | Default value, no transition effect. |
| OPACITY | 1 | Fade-in and fade-out effect. |
ExpandSafeAreaOption
Extends the component's image into the safe area.
| Member Name | Type | Description |
|---|---|---|
| types | Array | Safe area types |
| edges | Array | Safe area edges |
StaticDnsRuleItem
An element in the static DNS rule list.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Matched host name; maximum 256 bytes. |
| port | number | Yes | Matched port number; range 0–65535. |
| ipAddresses | Array<string> | Yes | List of IP addresses expected when resolving host:port. |
DnsOption
Custom DNS settings.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| staticDnsRule | Array<StaticDnsRuleItem> | Yes | Static DNS rule list. |
HeaderOptions
HTTP request header entry.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Request header key name. |
| value | Object | Yes | Request header value. |
HttpRequestOption
HTTP request parameters.
| Member Name | Type | Mandatory | Default | Description |
|---|---|---|---|---|
| caPath | string | No | - | Path to the CA certificate. |
| connectTimeout | number | No | 60000 | Connection establishment timeout, in milliseconds. |
| readTimeout | number | No | 60000 | Download timeout, in milliseconds. |
| skipValidation | boolean | No | false | Whether to skip HTTPS server certificate validation. When set to true, TLS certificate verification is skipped during the download, allowing connections to servers with self-signed, expired, or mismatched certificates. |
Security warning:
skipValidation=truedisables remote server identity verification for HTTPS and introduces man-in-the-middle risks. Only use it for testing/debugging or in controlled intranet environments. It is generally not recommended, and must not be enabled by default in production.
DrawingColorFilter
Image color filtering.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| color | common2D.Color | Yes | Filter color. |
| mode | drawing.BlendMode | Yes | Blend mode. |
EventImage
Input parameter for the onComplete callback. Since ImageKnifePro only sets the PixelMap for the Image component, onComplete will be triggered twice consecutively, and the loadingStatus field is no longer meaningful in this case.
| Member Name | Type | Description |
|---|---|---|
| width | number | Image width. |
| height | number | Image height. |
| componentWidth | number | Component width. |
| componentHeight | number | Component height. |
| loadingStatus | number | Loading status: 0 for loading, 1 for decoding. |
| contentWidth | number | Width of the image drawing area, in pixels. |
| contentHeight | number | Height of the image drawing area, in pixels. |
| contentOffsetX | number | X-axis position of the image drawing area relative to the component, in pixels. |
| contentOffsetY | number | Y-axis position of the image drawing area relative to the component, in pixels. |
ResizableOption
Resizable image options when the image is stretched.
This setting takes no effect if top + bottom exceeds the original image height or left + right exceeds the original image width.
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| left | number | No | Width of the region on the left side where pixels remain unchanged when stretching, unit: vp. |
| top | number | No | Height of the region at the top where pixels remain unchanged when stretching, unit: vp. |
| right | number | No | Width of the region on the right side where pixels remain unchanged when stretching, unit: vp. |
| bottom | number | No | Height of the region at the bottom where pixels remain unchanged when stretching, unit: vp. |
CacheErrorCode
Cache operation error codes.
| Enum Value | Number | Description |
|---|---|---|
| SUCCESS | 0 | Operation succeeded |
| CACHE_NAME_EMPTY | 401 | Cache name is empty when adding a small-end cache |
| CACHE_NAME_OCCUPIED | 409 | Cache name is already in use when adding a small-end cache |
| FILE_PATH_INVALID | 503 | File path is invalid |
| FILE_PATH_OCCUPIED | 509 | Cache path is already in use when adding a small-end cache |
ImageKnifeData
Image memory cache data.
| Member Name | Type | Description |
|---|---|---|
| pixelmapList | Array<PixelMap> | List of image frames |
| delayTimeList | Array<number> | List of per-frame durations, unit ms |
| frameCount | number | Number of frames |
DownSamplingStrategy
Downsampling strategy.
| Enum Value | Number | Description |
|---|---|---|
| NONE | 0 | No downsampling |
| DEFAULT | 1 | Default: only downsample if resolution exceeds 7680×4320, scaling proportionally to 7680×4320 |
| FIT_CENTER_MEMORY | 2 | Fit center, memory priority |
| FIT_CENTER_QUALITY | 3 | Fit center, quality priority |
| CENTER_INSIDE_MEMORY | 4 | Scale to fit within bounds by larger aspect ratio, memory priority |
| CENTER_INSIDE_QUALITY | 5 | Scale to fit within bounds by larger aspect ratio, quality priority |
| AT_LEAST | 6 | Proportional scale using the smaller dimension ratio first |
| AT_MOST | 7 | Do not upscale if requested size exceeds actual size |
| DESIRED_SIZE_FILL | 8 | Scale to the specified size without preserving the source aspect ratio. Requires desiredSize; no processing when the given size is larger than the source image. |
| DESIRED_SIZE_ASPECT_FIT | 9 | Fit the largest inscribed rectangle within the specified size while preserving the source aspect ratio. Requires desiredSize; no processing when the given size is larger than the source image. |
| DESIRED_SIZE_ASPECT_FILL | 10 | Scale to the smallest bounding rectangle that covers the specified size while preserving the source aspect ratio. Requires desiredSize; no processing when the given size is larger than the source image. “Larger than the source image” means both target width and height exceed those of the source image. |
ImageKnifeRequest
| Member / Method | Type / Signature | Description |
|---|---|---|
| imageKnifeOption | ImageKnifeOption | ImageKnifeOptionV2 | The image loading option associated with this request |
| constructor | (option: ImageKnifeOption | ImageKnifeOptionV2) | Constructs a request with the given option |
ImageKnife APIs
| API Name | Parameters | Description |
|---|---|---|
| preCreateImageKnifeComponent | customId: string, imageKnifeOption: ImageKnifeOption | ImageKnifeOptionV2 | Pre-create a component; must be associated with an ImageKnifeComponent before use |
| setMaxPreCreateNodeCount | maxCount: number | Set the maximum number of pre-created components |
| releasePreCreatedNode | - | Clear all unassociated pre-created components |
| initFileCache | context: Context, size: number, memory: number | Initialize big-end file cache (count and size) |
| setMaxRequests | concurrency: number | Set maximum concurrent request count |
| preload | loadSrc: string | ImageKnifeOption | ImageKnifeOptionV2 | Preload an image |
| preloadCache | loadSrc: string | ImageKnifeOption | ImageKnifeOptionV2 | Preload and return file cache path |
| cancel | request: ImageKnifeRequest | Cancel a preload request |
| reload | requestId: string | Reload a request |
| addSmallEndFileCache | cacheName: string, context: Context, filePath: string, maxSize: number = 256, maxDiskUsage: number = 256 * 1024 * 1024 | Add and initialize a small-end file cache instance |
| isFileCacheInit | cacheName?: string | Check whether the specified file cache is initialized |
| fileCacheEnableExtension | cacheName?: string | Enable file extensions for the default file cache |
| getCacheLimitNum | cacheStrategy?: CacheStrategy, cacheName?: string | Get the image count limit for file or memory cache |
| getCacheLimitSize | cacheStrategy?: CacheStrategy, cacheName?: string | Get the size limit for disk or memory cache |
| getCurrentCacheNum | cacheStrategy?: CacheStrategy, cacheName?: string | Get the current image count in disk or memory cache |
| getCurrentCacheSize | cacheStrategy?: CacheStrategy, cacheName?: string | Get used space of disk or memory cache |
| getCacheImage | loadSrc: string | ImageKnifeOption | ImageKnifeOptionV2, cacheType: CacheStrategy = CacheStrategy.Default, signature: string = "", animator: boolean = false | Get image from cache; reload if not cached |
| setCacheLimit | strategy: CacheStrategy, maxSize: number, maxUsage: number, cacheName?: string | Set disk or memory cache limit |
| addHeader | key: string, value: Object | Globally add a single HTTP request header |
| setGlobalDnsOption | dnsOption: DnsOption | Set global custom DNS for default network downloads |
| setGlobalDynamicDns | dynamicDns:(host:string, port:number) => Promise<Array>, timeout:number = 50 | Set a global dynamic DNS callback for the default network download |
| setGlobalLoadEndCallback | loadEnd:(src:string, requestType:string, isSuccess:boolean, timeInfo?:TimeInfo, errorCode?:string, errorMessage?:string, requestHeader?:string, responseHeader?:string) => void |
Set a global image loading completion callback |
| setJpegOptimizeDecoding | enable: boolean | Enables or disables optimized JPEG decoding by default to reduce memory usage of decoded images. If not called, this optimization is disabled by default. If a transformation is applied to the JPEG image, this decoding optimization will not be applied, and the default decoding method will be used instead. When enabled, the GetCacheImage interface may return a PixelMap in a non-RGBA pixel format. |
| getJpegOptimizeDecoding | - | Get whether optimized JPEG decoding is enabled |
| setPngOptimizeDecoding | enable: boolean | Enables or disables optimized PNG decoding by default to reduce memory usage of decoded images. If not called, this optimization is disabled by default. If a transformation is applied to the PNG image, this decoding optimization will not be applied, and the default decoding method will be used instead. If the PNG may contain transparency/Alpha, this decoding optimization will not be applied, and the default decoding method will be used instead. When enabled, the GetCacheImage interface may return a PixelMap in a non-RGBA pixel format. |
| getPngOptimizeDecoding | - | Get whether optimized PNG decoding is enabled |
| setWebpOptimizeDecoding | enable: boolean | Enables or disables optimized WebP decoding by default to reduce memory usage of decoded images. If not called, this optimization is disabled by default. If a transformation is applied to the WebP image, this decoding optimization will not be applied, and the default decoding method will be used instead. If the WebP may contain transparency/Alpha (including animated frames), this decoding optimization will not be applied, and the default decoding method will be used instead. When enabled, the GetCacheImage interface may return a PixelMap in a non-RGBA pixel format. |
| getWebpOptimizeDecoding | - | Get whether optimized WebP decoding is enabled |
| setHeicOptimizeDecoding | enable: boolean | Enables or disables optimized HEIC decoding by default to reduce memory usage of decoded images. If not called, this optimization is disabled by default. If a transformation is applied to the HEIC image, this decoding optimization will not be applied, and the default decoding method will be used instead. If the HEIC may contain transparency/Alpha, this decoding optimization will not be applied, and the default decoding method will be used instead. When enabled, the GetCacheImage interface may return a PixelMap in a non-RGBA pixel format. |
| getHeicOptimizeDecoding | - | Get whether optimized HEIC decoding is enabled |
| setHeaderOptions | Array<HeaderOptions> | Globally set HTTP request headers |
| deleteHeader | key: string | Globally delete an HTTP request header |
| removeAllMemoryCache | - | Remove all memory cache |
| removeMemoryCache | url: string | ImageKnifeOption | ImageKnifeOptionV2 | Remove specified memory cache |
| removeAllFileCache | cacheName?: string | Remove all file cache |
| removeFileCache | url: string | ImageKnifeOption | ImageKnifeOptionV2 | Remove specified file cache |
| checkImageCache | loadSrc: string | ImageKnifeOption | ImageKnifeOptionV2, cacheStrategy: CacheStrategy = CacheStrategy.DEFAULT | Check if Cache Exists |
| putCacheImage | url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?: string | Write to memory/disk cache |
| clearOnBackground | - | Clears all memory caches, retains image memory for ImageKnife components within the visible area of the current page, and releases image memory held by all other ImageKnife components to reduce memory usage after the app moves to the background. Can be called in the onBackground callback of EntryAbility.Should be used together with reloadOnForeground. |
| reloadOnForeground | - | Reloads images for components whose image data was cleared when the app returns to the foreground. Can be called in the onForeground callback of EntryAbility.Should be used together with clearOnBackground. |
Callbacks
| Callback | Field | Description |
|---|---|---|
| onLoadStart | imageInfo: ImageInfo | Called when image request starts |
| onLoadSuccess | imageInfo: ImageInfo | Called when loading succeeds |
| onLoadFailed | err: string, imageInfo: ImageInfo | Called when loading fails; err is the error description |
| onLoadCancel | reason: string, imageInfo: ImageInfo | Called when loading is cancelled; reason is the cancellation cause |
| onMemorySuccess | imageInfo: ImageInfo | Called when memory cache is hit |
| onDownloadSuccess | imageInfo: ImageInfo | Called when download completes |
| onDecodeSuccess | imageInfo: ImageInfo | Called when decoding completes |
TransformationType
| Enum Value | Description |
|---|---|
| UNKNOWN | Unknown transformation |
| CUSTOM_TRANSFORMATION | Custom graphic transformation |
| BLUR | Blur effect |
| BRIGHTEN | Brightness effect |
| GRAY_SCALE | Grayscale effect |
| INVERT | Invert effect |
| KUWAHARA | Kuwahara filter effect |
| PIXELATION | Pixelation effect |
| SEPIA | Ink-black filter effect |
| SKETCH | Sketch effect |
| SWIRL | Swirl effect |
| TOON | Animation filter effect |
| VIGNETTE | Decorative effect |
| CROP_TOP | Scale and crop to top based on given dimensions |
| CROP_CENTER | Scale and crop to center based on given dimensions |
| CROP_BOTTOM | Scale and crop to bottom based on given dimensions |
| CROP_SQUARE | Center-crop into a square |
| CROP_CIRCLE | Crop to maximum inscribed circle |
| CROP_CIRCLE_WITH_BORDER | Crop to maximum inscribed circle (with border) |
| MASK | Mask effect |
| MIRROR | Horizontal mirror effect |
| CUSTOM_TRANSFORMATION_CONSTRUCTOR | Custom transformation constructor registered on C side; accepts ArkTS layer parameters |
| GAUSSIAN_BLUR | Gaussian blur; smoother blur effect |
| COMMON_CROP | General cropping; the specific algorithm is provided by a custom callback. Requires configuring the TransformationOption::onCommonCropScale callback, which returns the cropping region. |
| COMMON_SCALE | General scaling; the specific algorithm is provided by a custom callback. Requires configuring the TransformationOption::onCommonCropScale callback, which returns the scaling factor. |
| COMMON_CROP_SCALE | General crop-then-scale (crop first, then scale); the specific algorithm is provided by a custom callback. Requires configuring the TransformationOption::onCommonCropScale callback, which returns both the cropping region and the scaling factor. |
| COMMON_SCALE_CROP | General scale-then-crop (scale first, then crop); the specific algorithm is provided by a custom callback. Requires configuring the TransformationOption::onCommonCropScale callback, which returns both the cropping region and the scaling factor. |
Common Crop-Scale Callback Return Type CommonCropScaleData
| Member | Type | Required | Description |
|---|---|---|---|
| region | image.Region | No | The cropping region of the image |
| scaleX | number | No | The scaling factor of the image on the X-axis |
| scaleY | number | No | The scaling factor of the image on the Y-axis |
TransformationOption
| Member Name | Type | Mandatory | Description |
|---|---|---|---|
| type | TransformationType | Yes | Graphic transformation type |
| customTransformation | string | No | Name of the custom transformation object registered on C side |
| f32 | Array<number> | No | float32 parameters; defaults are used if count is insufficient |
| imageSrc | string | PixelMap | Resource | No | Mask image resource |
| signature | string | No | Signature info corresponding to imageSrc, or used to distinguish different custom algorithms for generic crop-and-scale type transformations |
| onCommonCropScale | (pixelmapWidth: number, pixelmapHeight: number, originWidth: number, originHeight: number)=>CommonCropScaleData | No | Callback for generic crop-and-scale transformation. Register this callback to specify the cropping region and scaling factors for the image transformation. |
Comparison with ImageKnife3.x
ImageKnifeOption Properties
| Name | ImageKnife3.x (JS API) | ImageKnifePro (JS API) | ImageKnifePro (C API) |
|---|---|---|---|
| Main image | loadSrc:string, PixelMap, Resource | Consistent | |
| Placeholder | placeholderSrc?: string, PixelMap, Resource | Consistent | |
| Error image | errorholderSrc?: string, PixelMap, Resource | errorSrc?: string, PixelMap, Resource | |
| HTTP request header | headerOption?: Array | Consistent | |
| Custom signature | signature?: string | Consistent | |
| Scaling effect of the main image | objectFit?: ImageFit | Consistent | |
| Scaling effect of the placeholder | placeholderObjectFit?: ImageFit | Consistent | |
| Scaling effect of the error image | errorholderObjectFit?: ImageFit | errorObjectFit?: ImageFit | |
| Custom download method | customGetImage:function | Inconsistent. Removed. | Implemented by the interceptor. |
| Rounded corner border | border?: BorderOptions | Consistent. | |
| Write cache strategy | writeCacheStrategy?: CacheStrategy | Consistent | |
| Image loading only from cache | onlyRetrieveFromCache?: boolean | Consistent | |
| Request priority | priority?: taskpool.Priority | priority?: Priority | |
| Page context | context?: common.UIAbilityContext | Consistent | Invalid. |
| Download progress listening | progressListener?: (progress: number) => void | Consistent, but with cross-thread delay | |
| Graphic transformation | transformation?: PixelMapTransformation | Inconsistent | |
| Request callback | onLoadListener?: OnLoadCallBack | undefined | Inconsistent. The internal callback function uses ImageInfo as the input parameter. | |
| Rendering completion callback | onComplete?:(event:EventImage, undefined) => void | Consistent | |
| Color change | drawingColorFilter?: (common2D.Color, drawing.BlendMode) | Inconsistent | |
| Downsampling strategy | downsampleOf?: DownsampleStrategy | Consistent | |
| HTTP CA certificate | caPath?: string | Consistent |
ImageKnife Global Methods
| Name | ImageKnife3.x (JS API) | ImageKnifePro (JS API) | ImageKnifePro (C API) |
|---|---|---|---|
| Initializing file cache | InitFileCache(context: Context, size: number = 256, memory: number = 256 * 1024 * 1024, path?: string) | Consistent | InitFileCacheAsync(std::string cachePath, size_t size, size_t memory, std::string path) |
| Checking whether the file cache has been initialized | isFileCacheInit(): boolean | Consistent | bool IsFileCacheInit() |
| Reloading | reload(request: ImageKnifeRequest) | reload(requestId: string) | void reload(std::string requestId) |
| Adding a single request header globally | addHeader(key: string, value: Object) | Consistent | void AddHeader(std::string, std::string) |
| Setting the request header globally | setHeaderOptions(options) | Consistent | AddHeader API |
| Deleting a single request header | deleteHeader(key: string) | Consistent | void DeleteHeader(std::string key) |
| Setting a custom memory cache | initMemoryCache(newMemoryCache: IMemoryCache) | Inconsistent (implemented by the interceptor) | |
| Preloading | preload(loadSrc:string | ImageKnifeOption) | Consistent | std::shared_ptr Preload(std::shared_ptr imageKnifeOption) |
| Canceling an image request | Cancel(request:ImageKnifeRequest) | Consistent | Cancel(std::shared_ptr request) |
| Preloading an image to the file cache and returning the file path | preLoadCache(loadSrc: string | ImageKnifeOption) | Consistent | std::shared_future<std::string> PreloadCache(std::shared_ptr option) |
| Obtaining image data from the memory or file cache | getCacheImage(loadSrc: string, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string) | loadSrc: string, cacheType: CacheStrategy = CacheStrategy.Default, signature: string = "", animator: boolean = false | std::shared_future<std::shared_ptr> GetCacheImage(std::string loadSrc, CacheStrategy cacheType = CacheStrategy::DEFAULT, std::string signature = "", bool animator = false) |
| Preloading cache (used when the PixelMap has been obtained externally and needs to be added to the imageknife cache) | PutCacheImage(url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string) | Consistent | |
| Removing all file cache | removeAllFileCache() | Consistent | RemoveAllFileAsync(void) |
| Removing a specified file cache | removeFileCache(url: string | ImageKnifeOption) | Consistent | RemoveFileAsync(std::string &url), RemoveFileAsync(std::shared_ptr option) |
| Removing all memory cache | removeAllMemoryCache() | Consistent | RemoveAllMemoryCache() |
| Removing a specified memory cache | removeMemoryCache(url: string | ImageKnifeOption) | Consistent | RemoveMemoryCache(std::string url), RemoveMemoryCache(std::shared_ptr imageKnifeOption) |
| Setting the number of concurrent requests | setMaxRequests(concurrency: number) | Consistent | SetMaxRequests(int concurrency) |
| Obtaining the maximum size of cache | getCacheLimitSize(cacheType?: CacheStrategy) | Consistent | GetCacheLimitSize(CacheStrategy cacheStrategy) |
| Obtaining the maximum number of cache. | getCurrentCacheNum(cacheType: CacheStrategy) | Consistent | GetCurrentCacheNum(CacheStrategy cacheStrategy) |
| Obtaining the current cache size | getCurrentCacheSize(cacheType: CacheStrategy) | Consistent | GetCurrentCacheSize(CacheStrategy cacheStrategy) |
| Customizing the cache key generation method | SetEngineKeyImpl(impl: IEngineKey) | Inconsistent | SetCacheKeyGenerator(CacheKeyGenerator *keyPtr) |
| Setting global custom download | setCustomGetImage(...) | Inconsistent | Implemented by the interceptor. |
| Obtaining global custom download | getCustomGetImage() | Inconsistent | Implemented by the interceptor. |
Other Properties
| Name | ImageKnife3.x (JS API) | ImageKnifePro (JS API) | ImageKnifePro (C API) |
|---|---|---|---|
| Synchronous loading | syncLoad: boolean | Consistent | |
| Animated image control and callback | animatorOption: AnimatorOption | Consistent | |
| Adaptive image width and height | ImageFit.Auto | Consistent |
About Obfuscation
- For details, see Code Obfuscation.
- To prevent the ImageKnifePro library from being obfuscated, add exclusion rules to the obfuscation-rules.txt configuration file.
-keep
./oh_modules/@ohos/imageknifepro
Benchmark
Test demo, test time: 2026-3-10.
- Load 8 images concurrently per batch, with a total of 256 images loaded per group.
- Test with image sizes of 20KB, 750KB, and 1.5MB, presenting two sets of data for each size.
- The total time covers the entire process, starting from component creation, request dispatching, image downloading, and decoding, up to display rendering.
- "Excluding Network" refers to the total time minus the time spent on network requests.
- For the system Image component, due to limited exposed APIs, only coarse-grained network download and decoding times can be captured for comparison. Note that the recorded network download time also includes other delays such as component creation.
- Network time data is subject to network fluctuations at the test location.
20kb Image Loading Test Result
| Component | NetWork Downloading Time | Image Decoding Time | Memory Reading Time | File Reading Time | Excluding NetWork | Total Time |
|---|---|---|---|---|---|---|
| ImageKnifePro | 72ms653us920ns | 6ms268us420ns | 4us744ns | 16us638ns | 10ms76us | 83ms416us542ns |
| ImageKnifePro | 56ms575us459ns | 5ms941us689ns | 4us785ns | 14us829ns | 10ms38us | 66ms953us175ns |
| ImageKnife | 57ms457us491ns | 8ms349us617ns | 22us312ns | 130us161ns | 46ms35us | 103ms805us572ns |
| ImageKnife | 64ms759us849ns | 8ms288us71ns | 20us267ns | 141us206ns | 45ms12us | 109ms872us823ns |
| System Image | 68ms283us422ns | 12ms915us511ns | - | - | 12ms94us | 81ms223us95ns |
| System Image | 68ms922us800ns | 12ms740us749ns | - | - | 12ms76us | 79ms687us760ns |
750kb Image Loading Test Result
| Component | NetWork Downloading Time | Image Decoding Time | Memory Reading Time | File Reading Time | Excluding NetWork | Total Time |
|---|---|---|---|---|---|---|
| ImageKnifePro | 4s115ms237us977ns | 6ms975us457ns | 5us375ns | 18us192ns | 17ms98us | 4s133ms216us647ns |
| ImageKnifePro | 4s100ms492us911ns | 6ms863us840ns | 5us318ns | 16us674ns | 18ms86us | 4s119ms357us777ns |
| ImageKnife | 4s94ms511us870ns | 9ms235us249ns | 25us806ns | 191us864ns | 64ms59us | 4s159ms147us853ns |
| ImageKnife | 4s94ms26us99ns | 9ms340us12ns | 26us575ns | 190us431ns | 65ms39us | 4s163ms416us218ns |
| System Image | 4s150ms769us251ns | 16ms205us570ns | - | - | 16ms27us | 4s167ms35us829ns |
| System Image | 4s130ms395us63ns | 17ms601us611ns | - | - | 17ms67us | 4s148ms67us258ns |
1.5mb Image Loading Test Result
| Component | NetWork Downloading Time | Image Decoding Time | Memory Reading Time | File Reading Time | Excluding NetWork | Total Time |
|---|---|---|---|---|---|---|
| ImageKnifePro | 7s981ms341us30ns | 97ms614us501ns | 7us299ns | 21us988ns | 107ms61us | 8s88ms915us924ns |
| ImageKnifePro | 7s933ms515us892ns | 99ms117us512ns | 4us817ns | 13us859ns | 110ms19us | 8s43ms694us66ns |
| ImageKnife | 7s886ms973us612ns | 97ms932us259ns | 19us159ns | 155us924ns | 157ms99us | 8s44ms961us317ns |
| ImageKnife | 8s8ms522us385ns | 102ms407us690ns | 21us930ns | 158us854ns | 158ms4us | 8s166ms921us873ns |
| System Image | 8s135ms240us184ns | 105ms608us227ns | - | - | 105ms66us | 8s240ms904us206ns |
| System Image | 7s974ms420us482ns | 98ms917us423ns | - | - | 98ms98us | 8s73ms401us97ns |
Directory Structure
The directory structure is briefly outlined below:
imageknifepro/
├── entry/ // Test module, provides examples and test cases
│ ├── src/
│ │ ├── main/
│ │ │ ├── cpp/ // C interface testing related code
│ │ │ ├── ets/ // ImageKnifePro ArkTs demo pages
│ │ │ └── resource/ // Local image resources for testing
│ │ └── ohosTest/ets/test/ // XTS test cases
│ ├── build-profile.json5
│ └── oh-package.json5 // Test module dependency description
├── library/ // ImageKnifePro HAR package module
│ ├── src/main/
│ │ ├── cpp/ // ImageKnifePro code directory
│ │ │ ├── include/ // C interfaces provided by ImageKnifePro
│ │ │ ├── thirdparty/
│ │ │ ├── README.md
│ │ │ └── README_zh.md // C interface usage instructions
│ │ └── ets/ // ArkTs interfaces provided by ImageKnifePro
│ ├── build-profile.json5
│ └── oh-package.json5
├── sharedlibrary/ // Used only to verify cross-module image reading; this module itself is empty
│ ├── src/main/resource/ // Local image resources for testing
│ ├── build-profile.json5
│ └── oh-package.json5
├── CHANGELOG.md
├── LICENSE
├── README.md
├── README_zh.md
└── README.OpenSource
Contributing
If you encounter any issues, please submit an Issue. Pull Requests are also welcome — see Pull Requests.
License
This project is licensed under Apache License 2.0. You are free to use it and contribute to open source.
Introduction
用户可用于高效加载和缓存图片,支持本地、网络图片及动图展示。项目提供ArkTs和C两种API,具备自定义缓存策略、图片变换、进度监听等功能,加载速度快且支持生命周期管理。
https://gitcode.com/openharmony-sig/imageknifeproCustomize your domain