AVIF encoding support is currently in an experimental phase and may be updated or changed. Monitor this page for updates before using AVIF encoding in a production environment.
AV1 Image File Format (AVIF) is an image format based on AV1 video encoding. It supports HDR (high dynamic range) and alpha channel transparency, and delivers higher compression efficiency than JPEG and PNG at comparable visual quality. OSS provides full support for AVIF encoding and decoding.
The examples below cover only essential code snippets. For complete integration samples, download the example projects:
iOS
Prerequisites
iOS does not provide native AVIF encoding support. Add the following third-party libraries using CocoaPods: libavif and SVT-AV1.
The open-source builds of libavif and SVT-AV1 have two known limitations: low encoding performance, and no support for odd-sized image dimensions. Use the Alibaba Cloud-optimized builds provided below to avoid these issues.
Add dependencies
Add the Alibaba Cloud specs repository to your Podfile:
source 'https://github.com/aliyun/aliyun-specs.git'Add the AVIF encoding and decoding dependencies:
pod 'SDWebImage' pod 'SDWebImageAVIFCoder', '0.12.1' pod 'libavif/svt-av1', '1.1.1' pod 'svt-av1', '1.2.2' pod 'libdav1d', '1.2.0'
Encode images
SDWebImageAVIFCoder is a codec plugin for SDWebImage that enables AVIF encoding and decoding.
Step 1. Register the AVIF coder in your AppDelegate.m file:
SDImageAVIFCoder *avifCoder = [SDImageAVIFCoder sharedCoder];
[[SDImageCodersManager sharedManager] addCoder:avifCoder];Step 2. Encode an image to AVIF:
// Load the source image
UIImage *image = [UIImage imageNamed:@"test-image.jpg"];
// Encode to AVIF
id<SDImageCoder> coder = [SDImageCodersManager sharedManager];
NSData *encodedData = [coder encodedDataWithImage:image format:SDImageFormatAVIF options:nil];After encoding completes, save encodedData to your local device.
Android
Prerequisites
Download and add the AAR file to your project: avifandroidjni-release.aar.
Encode images
Use the encodeRGBA8888 method of the AvifDecoder class to encode RGBA image data to AVIF.
Method signature:
/**
* Encode RGBA data to AVIF.
* @param rgbaData RGBA8888 byte buffer.
* @param length Buffer length.
* @param width Image width.
* @param height Image height.
* @return Byte array of the encoded AVIF image.
*/
public static native byte[] encodeRGBA8888(ByteBuffer rgbaData, int length, int width, int height);Example — encode a Bitmap to AVIF:
// Copy bitmap pixels into a direct ByteBuffer
val pixelBuffer = ByteBuffer.allocateDirect(bitmap.width * bitmap.height * 4)
bitmap.copyPixelsToBuffer(pixelBuffer)
// Encode to AVIF; avifBytes contains the encoded image data
val avifBytes = AvifDecoder.encodeRGBA8888(
pixelBuffer,
bitmap.width * bitmap.height * 4,
bitmap.width,
bitmap.height
)Next steps
To add AVIF decoding support to your app, see: