imageknifepro:基于 OpenHarmony 的图像加载缓存库项目

用户可用于高效加载和缓存图片,支持本地、网络图片及动图处理。该项目提供ArkTs和C两种API,具备自定义缓存策略、图片变换、网络下载进度监听等功能,加载速度快且支持多种自定义拓展。【此简介由AI生成】

Branch3Tags0

ImageKnifePro

ImageKnifePro is a specially crafted image loading and caching library for OpenHarmony, optimized for efficiency, lightness, and simplicity.

Introduction

This library is the C implementation of ImageKnife and has the following features:

  • Custom memory cache strategy and adjustable cache size (LRU strategy by default)
  • Disk L2 cache for downloaded images
  • Custom implementation of image obtaining and network download
  • 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
  • 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
  • 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.

Future features:

  • Image scaling through transformation

Compared to the ImageKnife ArkTS version, ImageKnifePro:

  • Supports the use of ArkTS APIs for ArkTS applications and C APIs for non-ArkTS applications.
  • Enhances image loading performance through built-in system APIs (network C APIs and image C APIs).
  • Allows you to customize C API extensions only, including network download, decoding, file caching, and memory caching by using interceptors and the responsibility chain pattern, catering to diverse scenarios.

How to Install

ohpm install @ohos/imageknifepro

// If file caching is required, initialize the file cache in advance.
await ImageKnife.getInstance().initFileCache(context, 256, 256 * 1024 * 1024)

Directory Introduction

The directory structure is outlined below:

imageknifepro/
├── entry/                          // Test modudle, provide example and test cases
│   ├── src/
│   │   ├── main/
│   │   │   ├── cpp/                // C interface testing relate codes 
│   │   │   ├── ets/                // ImageKnifePro ArkTs demo page
│   │   │   └── resource/           // Local image resource for test
│   │   └── ohosTest/ets/test/      // XTS test case
│   ├── build-profile.json5
│   └── oh-package.json5            // Test module dependence
├── library/                        // Module of ImageKnifePro HAR package provider
│   ├── src/main/
│   │   ├── cpp/                    // ImageKnifePro codes 
│   │   │   ├── include/            // ImageKnifePro C interfaces
│   │   │   ├── thirdparty/
│   │   │   ├── README.md
│   │   │   └── README_zh.md        // C interfaces introduction
│   │   └── ets/                    // ImageKnifePro ArkTs interfaces
│   ├── build-profile.json5
│   └── oh-package.json5
├── sharedlibrary/                  // This module is empty, only for reading image test
│   ├── src/main/resource/          // Local image resource for test
│   ├── build-profile.json5
│   └── oh-package.json5
├── CHANGELOG.md
├── LICENSE
├── README.md
├── README_zh.md
└── README.OpenSource

How to Use

Displaying a Local Resource Image

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@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'

@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'

@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'

@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

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@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'

@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

ImageKnifeComponent({
  imageKnifeOption: {
   loadSrc: $r("app.media.test"),
  },
  contentTransition:ContentTransitionType.OPACITY
}).width(100).height(100)

Listening for Image Loading Success and Failure

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@Component
struct ExamplePage {
    @State imageKnifeOption:ImageKnifeOption = { imageKnifeOption: 
    {
       loadSrc: $r("app.media.rabbit"),
       onLoadListener:{
        onLoadStart:(imageInfo)=>{
         console.info("Load start, requestId:" + imageInfo.requestId);
        },
        onLoadFailed: (err, imageInfo) => {
         console.error("Load Failed Reason: " + err);
        },
        onLoadSuccess: (imageInfo) => {
         console.info("Load Successful");
        },
        onLoadCancel(reason, imageInfo){
          console.info(reason)
        }
       }
     }
    }

    build() {
    Column() {
      ImageKnifeComponent({
        imageKnifeOption:this.imageKnifeOption
      }).width(200).height(200)
    }
    }
}

Using syncLoad

syncLoad sets whether to load images synchronously. By default, images are loaded asynchronously. When loading a small image, you are advised to set syncLoad to true so that the image loading can be quickly completed on the main thread.

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@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'

@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'

@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) => {
        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'

@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'

@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'

@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)
    }
  }
}

CRC32 Checking And Fallback Urls

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@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'

@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)
    }
  }
}

Using Small End File Cache

The default file cache interceptor adds a little-endian file cache instance, which resides in a separate LRU space from the big-endian file cache and does not affect each other.

ImageKnife.getInstance().addSmallEndFileCache("small end", this.context, "small_end")

using in component.

import { ImageKnifeComponent, ImageKnifeOption } from '@ohos/imageknifepro'

@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)
    }
  }
}

Customizing Network Requests

Currently, you can only implement C++ custom download, cache, and graphics change methods in the C++ child thread.

For details about the custom network interceptor implemented on the C side, see the example.

Customizing File Format

Currently, you can only implement C++ custom download, cache, and graphics change methods in the C++ child thread.

For details about the custom image format implemented on the C side, see the example

Customizing Key Generator Object

Currently, you can only implement C++ custom download, cache, and graphics change methods in the C++ child thread.

For details about the custom key generator object on the C side, see the example

Reuse Scenario

Clear the component content in the aboutToRecycle lifecycle and trigger image loading through watch listening.

Available APIs

ImageKnifeComponent

A standard image component provided by ImageKnifePro, implemented as a wrapper around the system Image component.
Supports both static images and animated images.

Member Name Type Description
imageKnifeOption ImageKnifeOption Image loading configuration options
animatorOption AnimatorOption Animated image control options (optional)
imageDraggable boolean Whether the image is draggable; defaults to false (optional)
contentTransition ContentTransitionType Transition effect for component content (optional)
syncLoad boolean Whether to load synchronously; defaults to false (optional)
customId string | undefined 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 implemented by ImageKnifePro using Custom Node.

  • Supports both static and animated images.
  • Currently supported ImageFit modes: Contain, Cover, Fill, None, ScaleDown, Auto.
  • Implicit animations on the component are not supported.
  • ResizeableOption is not supported.
  • HDR images are not supported.
Member Name Type Description
imageKnifeOption ImageKnifeOption Image loading configuration options
animatorOption AnimatorOption Animated image control options (optional)
imageDraggable boolean Whether the image is draggable; defaults to false (optional)
syncLoad boolean Whether to load synchronously; defaults to false (optional)

ImageKnifeAnimatorComponent

An animated image component provided by ImageKnifePro for displaying animated images (not recommended, no longer maintained).
When displaying a static image, it treats it as a single-frame animated image.

Capabilities are limited by the system Animator component:

  • Does not support per-frame decoding mode.
  • Does not support HDR images.
  • Updating the loaded image resource is not recommended.
  • Cannot use border to set rounded corners.
  • Cannot use ImageFit to configure scaling/fill behavior.
  • Cannot use OnComplete callback for render completion notification.
  • Does not support draggable functionality.
  • Cannot apply ColorFilter for color adjustments.
  • Does not support ResizeableOption.
Member Name Type Description
imageKnifeOption ImageKnifeOption Image loading configuration options
animatorOption AnimatorOption Animated image control options

AnimatorOption Parameters

Name Type Description
state AnimationStatus Playback status. Optional.
iterations number Number of playback times. Optional.
reverse boolean Playback order. Optional.
onStart ()=>void Triggered when the animation starts. Optional.
onFinish ()=>void Triggered when the animation finishes or stops. Optional.
onPause ()=>void Triggered when the animation pauses. Optional.
onCancel ()=>void Triggered when the animation is canceled, that is, when it is reset to its initial state. Optional.
onRepeat ()=>void Triggered when the animation repeats. Optional.

ImageKnifeOption Parameters

Name Type Description
loadSrc string | PixelMap | Resource Main image. Mandatory.
placeholderSrc string | PixelMap | Resource Placeholder image.
thumbnailSrc string | PixelMap | Resource Thumbnail image
errorSrc string | PixelMap | Resource Error image.
imageKnifeLoader string Custom image load.
headerOption Array Request headers.
dnsOption DnsOption Custom Dns option.
signature String Custom cache signature.
pixelName string Set main image pixelmap memory name
objectFit ImageFit How the main image is resized to fit its container.
placeholderObjectFit ImageFit How the placeholder image is resized to fit its container.
thumbnailObjectFit ImageFit How the thumbnail image is resized to fit its container.
errorObjectFit ImageFit How the error image is resized to fit its container.
orientation Orientation The desired image content orientation for the main image.
dynamicRange DynamicRange The desired image content dynamic range for the main image.
resizeable ResizableOption Set the resizable image options when the image is stretched.
border BorderOptions Rounded corner border.
fileCacheName string Select small file cache for main image by cache name.
writeCacheStrategy CacheStrategyType Cache writing strategy.
onlyRetrieveFromCache boolean Image loading only from cache.
priority Priority Load priority.
transformationOption TransformationOption Graphic transformation.
multiTransformationOption Array Multi-graphic transformation
context common.UIAbilityContext Context.
progressListener (progress: number)=>void Callback for image download progress.
onLoadListener OnLoadCallBack Callback for image loading events.
onComplete (event:EventImage | undefined) => void Callback for image loading completion.
httpOption HttpRequestOption http request configuration.
drawingColorFilter (common2D.Color, drawing.BlendMode) Drawing color filter.
animationDecodeMode AnimationDecodeMode Animate image decode mode.
allocationMode AllocationMode PixelMap memory allocation mode for decoded images (This property only takes effect in API 15 and above).
downSampling DownSamplingStrategy Down sampling strategy.
crc32 number Checking download data of crc32 for main image.
fallbackUrls Array fallback urls for retry downloading main image.
forceWatch number Modify this property to forcibly trigger the component's watch on ImageKnifeOption. This property is unrelated to image loading.

ImageInfo Parameters

Name Type Description
requestId string Image request ID.
isMergedRequest boolean Whether the request was merged.
imageSourceFrom ImageSourceFrom The source from which the image is loaded.
imageWidth number Original image width.
imageHeight number Original image height.
componentWidth number Component measure width.
componentHeight number Component measure height.
bufSize number Number of original image bytes.
type ImageFormat Original image format.
customFormat string The string which describe specific custom image format.
httpCode number HTTP status code.
frameCount number Number of image frames.
decodeImages Array Image information after decoding.
decodeImages Array Information after image decoding, including the width and height of each frame of image after decoding.
timeInfo TimeInfo Time when images are loaded.
errorInfo ErrorInfo Error information during image loading.

ImageFormat Enums

Name Value
UNKNOWN 0
JPG 1
PNG 2
WEBP 3
BMP 4
GIF 5
SVG 6
TIFF 7
HEIC 8
ICO 9
CUSTOM_FORMAT 10
AVIF 11

Priority

Enumeration Name Value Description
HIGH 0 High queue priority
MEDIUM 1 Medium queue priority
LOW 2 Low queue priority

DecodeImageInfo Parameters

Name Type Description
contentWidth number Image width after decoding.
contentHeight number Image height after decoding.

ErrorInfo Parameters

Name Type Description
phase string Image loading information.
code number Error code.

TimeInfo Parameters

Name Type Description
executeTime number Time when a request is created and starts to be processed.
For a merged request, this time may be later than the loading and decoding time, because the loading process was performed by another request, and the merged request reused the result.
requestStartTime number Time when a request starts to be loaded.
For a merged request, this time may be later than the loading and decoding time, because the loading process was performed by another request, and the merged request reused the result.
requestEndTime number Request end time.
requestCancelTime number Request cancellation time.
memoryCheckStartTime number Time when memory cache read starts.
memoryCheckEndTime number Time when memory cache read ends.
diskCheckStartTime number Time when file cache read starts.
diskCheckEndTime number Time when file cache read ends.
loadImageStartTime number Time when image loading starts.
loadImageEndTime number Time when image loading ends.
decodeStartTime number Time when image decoding starts.
decodeEndTime number Time when image decoding ends.

TransformationInfo

Records information about the executed graphic transformation object.

Member Name Type Description
desc string Description of the transformation object, including its parameter information
isSuccess boolean Indicates whether the transformation was successful
startTime number Start time of the transformation object execution
endTime number End time of the transformation object execution

CacheStrategy Enums

Name Value 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.

Enumeration Name Value 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

Describes the desired dynamic range of image content.

Enumeration Name Value Description
AUTO 0 Automatic chose dynamic range mode.
UP 1 Standard dynamic range.
RIGHT 2 High dynamic range.

ImageSourceFrom

The source from which the image is loaded.

Enumeration Name Value Description
AUTO 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.

Enumeration Name Value Description
AUTO 0 Automatically select the decoding mode based on image resolution and frame count.
Batch decoding is chosen for images where width * height * frame count < 720 * 720 * 32; otherwise, frame-by-frame decoding is used.
BATCH_MODE 1 Batch decoding mode.
All frames of the image are decoded into memory at once, eliminating decoding overhead during playback but resulting in higher memory usage.
FRAME_MODE 2 Frame-by-frame decoding mode.
Each frame is decoded in real-time during animation playback, resulting in lower memory usage.

AllocationMode

Memory allocation mode for the decoded image PixelMap.

Enumeration Name Value Description
AUTO 0 Automatically select the memory allocation mode based on image format, size, and width.
BATCH_MODE 1 Create the PixelMap using a DMA buffer.
SVG images do not support this mode.
FRAME_MODE 2 Create the PixelMap using shared memory.

ContentTransitionType

Content transition effect
When the image displayed by the component is updated, this transition effect is shown.
This feature does not take effect on devices with an API version lower than 21.

Enum Name Value Description
IDENTITY 0 Default value, no transition effect
OPACITY 1 Fade-in and fade-out effect

StaticDnsRuleItem

An element in the static DNS rule list.

Member Name Type Description
host string The matched host name; maximum length: 256 bytes.
port number The matched port number; range: 0-65535.
ipAddresses Array The list of IP addresses expected when resolving host:port.

DnsOption

Custom DNS settings.

Member Name Type Description
staticDnsRule Array The static DNS rules.

HeaderOptions

HTTP header configuration options.

Member Name Type Description
key string The request header key name.
value Object The request header value.

HttpRequestOption

HTTP request configuration options.

Member Name Type Description
caPath string Path to the CA certificate.
connectTimeout number Connection establishment timeout, default is 60 seconds.
readTimeout number Download timeout, default is 60 seconds.

DrawingColorFilter

Image color filtering.

Member Name Type Description
color common2D.Color The filter color.
mode drawing.BlendMode The blend mode.

EventImage

Input parameter for the onComplete callback.
The OnComplete callback of the ImageKnifeComponent is passed to the system's Image. Since ImageKnifePro only sets the PixelMap for the Image, this callback will be triggered twice consecutively.
In this case, the loadingStatus member is no longer meaningful because the loading and decoding processes have already been completed beforehand.

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 Description
left number When stretching the left side of the image, the pixel value remains unchanged, unit: vp.
top number When stretching the top of the image, the pixel value remains unchanged, unit: vp.
right number When stretching the right side of the image, the pixel value remains unchanged, unit: vp.
bottom number When stretching the bottom of the image, the pixel value remains unchanged, unit: vp.

CacheErrorCode

Cache error codes.

Enumeration Name Value Description
SUCCESS 0 Operation succeeded.
CACHE_NAME_EMPTY 401 Cache name is empty when adding a small-end cache.
CACHE_NAME_OCCUPIED 409 Cache path is invalid.
FILE_PATH_INVALID 503 The image is displayed after being rotated 180 degrees clockwise. (Note: This description seems incorrect for a file path error; it might be a copy-paste mistake.)
FILE_PATH_OCCUPIED 509 The cache path is already in use when adding a small-end cache.

ImageKnifeData

Image memory PixelMap data.

Member Name Type Description
pixelmapList Array List of image PixelMaps.
delayTimeList Array List of playback durations for each image frame.
frameCount number Number of image frames.

DownSamplingStrategy

Downsampling strategy.

Enumeration Name Value Description
NONE 0 No downsampling.
DEFAULT 1 Default value. Only downsamples images with resolution exceeding 7680 * 4320, proportionally scaling width and height down 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 based on the larger aspect ratio, memory priority.
CENTER_INSIDE_QUALITY 5 Scale to fit within bounds based on the larger aspect ratio, quality priority.
AT_LEAST 6 Proportionally scale width and height, first fitting the smaller dimension, then adapting based on the original image's scale ratio.
AT_MOST 7 Do not upscale if the requested size is larger than the actual size.

ImageKnife APIs

Name Parameter Description
preCreateImageKnifeComponent customId: string, imageKnifeOption: ImageKnifeOption Pre-created components require association with the ImageKnifeComponent to be used.
setMaxPreCreateNodeCount maxCount: number Set the maximum number of pre-created components.
releasePreCreatedNode Clear all pre-created components that are not associated.
initFileCache context: Context, size: number, memory: number Initialize the file cache count and size.
setMaxRequests concurrency: number Sets the maximum number of concurrent requests.
preload loadSrc: string | ImageKnifeOption Preloads images.
preLoadCache loadSrc: string | ImageKnifeOption Preloads and returns the file cache path.
cancel request: ImageKnifeRequest Cancels image preloading.
reload requestId: string Reloads requests.
addSmallEndFileCache cacheName:string, context:Context, filePath:string, maxSize: number = 256, maxDiskUsage: number = 256 * 1024 * 1024 添加小端文件缓存,并进行初始化
isFileCacheInit cacheName?:string Checks whether file cache initialization is complete.
fileCacheEnableExtension cacheName?:string Default file cache enabled file extensions.
getCacheLimitNum cacheStrategy?: CacheStrategy, cacheName?:string Get the maximum number of images allowed in file or memory cache.
getCacheLimitSize cacheStrategy?: CacheStrategy, cacheName?:string Obtains the upper limit of the disk or memory cache.
getCurrentCacheNum cacheStrategy?: CacheStrategy, cacheName?:string Obtains the number of images cached in the disk or memory.
getCurrentCacheSize cacheStrategy?: CacheStrategy, cacheName?:string Obtains the used space of the disk or memory cache. The functionality for obtaining memory usage will be updated following the release of the relevant system APIs.
getCacheImage loadSrc: string, cacheType: CacheStrategy = CacheStrategy.Default, signature: string = "", animator: boolean = false Obtains resources from memory or file cache.
setCacheLimit strategy: CacheStrategy, maxSize: number, maxUsage: number Sets the upper limit of the disk or memory cache.
addHeader key: string, value: Object Adds a global HTTP request header.
setGlobalDnsOption dnsOption: DnsOption Set global custom DNS rules for default network downloads.
setHeaderOptions Array Sets a global HTTP request header.
deleteHeader key: string Deletes a global HTTP request header.
removeMemoryCache url: string | ImageKnifeOption Removes the specified memory cache.
removeAllMemoryCache Removes all disk cache.
removeMemoryCache url: string | ImageKnifeOption Removes all memory cache.
removeAllFileCache cacheName?:string Removes the specified disk cache.
removeFileCache cacheName?:string Clear the specified file cache.
putCacheImage url: string, pixelMap: PixelMap, cacheType: CacheStrategy = CacheStrategy.Default, signature?: string, cacheName?:string Writes data to the memory disk cache.

Callbacks

Name Field Description
onLoadStart imageInfo: ImageInfo imageInfo: image request information. For details, please refer to "ImageInfo Parameters".
onLoadSuccess imageInfo: ImageInfo imageInfo: image request information. For details, please refer to "ImageInfo Parameters".
onLoadFailed err: string, imageInfo: ImageInfo err: error information.
imageInfo: image request information. For details, please refer to "ImageInfo Parameters".
onLoadCancel reason: string, imageInfo: ImageInfo reason: reason for canceling the callback.
imageInfo: image request information. For details, please refer to "ImageInfo Parameters".
onMemorySuccess imageInfo: ImageInfo The returned imageInfo field contains information about the image request. For details, refer to ImageInfo Member List
onDownloadSuccess imageInfo: ImageInfo The returned imageInfo field contains information about the image request. For details, refer to ImageInfo Member List
onDecodeSuccess imageInfo: ImageInfo The returned imageInfo field contains information about the image request. For details, refer to ImageInfo Member List

TransformationType Enums

Name Description
UNKNOWN Unknown graphic transformation.
CUSTOM_TRANSFORMATION Custom graphic transformation.
BLUR Blur effect.
BRIGHTEN Brightness effect.
GRAY_SCALE Grayscale effect.
INVERT Invert effect.
KUWAHARA Kuwahara filter effect.
PIXELATION Pixelization effect.
SEPIA Sepia filter effect.
SKETCH Sketch effect.
SWIRL Swirl effect.
TOON Cartoon filter effect.
VIGNETTE Vignette effect.
CROP_TOP Image top is scaled and cropped based on the given width and height.
CROP_CENTER Image center is scaled and cropped based on the given width and height.
CROP_BOTTOM Image bottom is scaled and cropped based on the given width and height.
CROP_SQUARE Image is cropped at the center into a square.
CROP_CIRCLE Image is cropped into the maximum inscribed circle.
CROP_CIRCLE_WITH_BORDER Image is cropped into the maximum inscribed circle.
MASK Mask effect.
MIRROR Horizontal mirror effect.
CUSTOM_TRANSFORMATION_CONSTRUCTOR Custom graphic transformation constructor, registered on the C side, capable of receiving parameters from the ArkTS layer.
GAUSSIAN_BLUR Gaussian blur, providing a smoother blurring effect.

TransformationOption Parameters

Name Type Description
type TransformationType Default transformation type.
customTransformation String Name of the custom transformation object registered in C implementation.
f32 Array Parameter of the float32 type. If the number of parameters does not meet the requirements of the corresponding transformation type, the default value is used.
imageSrc String | Pixelmap | Resource Mask image resource.
signature string Signature information corresponding to imageSrc.

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. (Currently, the radius and border width of the number type are implemented.)
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
Component scaling Transform(matrix:object) Consistent (to be implemented)
Adaptive image width and height ImageFit.Auto Consistent

How to Use

For details, see ImageKnifePro (C API)

Constraints

This project has been verified in the following version:

  • DevEco Studio: 5.0.5.315; SDK: 5.0.1 (API 13)

About Obfuscation

  • For details, see Code Obfuscation.
  • To prevent the imageknife library from being obfuscated, add exclusion rules to the obfuscation-rules.txt configuration file.

-keep
./oh_modules/@ohos/imageknifepro

Benchmark

The image loading speed and white block rate of ImageKnife3.x, ImageKnifePro, System Image, and Android Fresco/Glide are to be tested and compared.

License

This project is licensed under Apache License 2.0.

Introduction

用户可用于高效加载和缓存图片,支持本地、网络图片及动图处理。该项目提供ArkTs和C两种API,具备自定义缓存策略、图片变换、网络下载进度监听等功能,加载速度快且支持多种自定义拓展。【此简介由AI生成】

Customize your domain