Skip to content

Commit 7c7d8fc

Browse files
committed
Upgrade the encode ICCData logic
1 parent bc5f74d commit 7c7d8fc

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

SDWebImageAVIFCoder/Classes/SDImageAVIFCoder.m

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -310,9 +310,27 @@ - (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image format:(SDIm
310310
avifImageRGBToYUV(avif, &rgb);
311311
free(dest.data);
312312

313-
NSData *iccProfile = (__bridge_transfer NSData *)CGColorSpaceCopyICCProfile([SDImageCoderHelper colorSpaceGetDeviceRGB]);
314-
315-
avifImageSetProfileICC(avif, (uint8_t *)iccProfile.bytes, iccProfile.length);
313+
// We must prefer the input CGImage's color space, which may contains ICC profile
314+
CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
315+
// We only supports RGB colorspace, filter the un-supported one (like Monochrome, CMYK, etc)
316+
if (CGColorSpaceGetModel(colorSpace) != kCGColorSpaceModelRGB) {
317+
// Ignore and convert, we don't know how to encode this colorspace directlly to WebP
318+
// This may cause little visible difference because of colorpsace conversion
319+
colorSpace = NULL;
320+
}
321+
if (!colorSpace) {
322+
colorSpace = [SDImageCoderHelper colorSpaceGetDeviceRGB];
323+
}
324+
// Add ICC profile if present
325+
CFDataRef iccData = NULL;
326+
if (colorSpace) {
327+
if (@available(iOS 10, tvOS 10, macOS 10.12, watchOS 3, *)) {
328+
iccData = CGColorSpaceCopyICCData(colorSpace);
329+
}
330+
}
331+
if (iccData && CFDataGetLength(iccData) > 0) {
332+
avifImageSetProfileICC(avif, CFDataGetBytePtr(iccData), CFDataGetLength(iccData));
333+
}
316334

317335
double compressionQuality = 1;
318336
if (options[SDImageCoderEncodeCompressionQuality]) {

0 commit comments

Comments
 (0)