CGImageRef thumbnailImage = NULL;
CGImageSourceRef imageSource = NULL;
CFDictionaryRef createOptions = NULL;
CFStringRef createKeys[3];
CFTypeRef createValues[3];
CFNumberRef thumbnailSize = 0;
UIImage * thumbnail;
NSData * squareData = UIImagePNGRepresentation(sourceImage);
NSData * thumbnailData = nil;
imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)squareData,NULL);
if (imageSource)
{
thumbnailSize = CFNumberCreate(NULL, kCFNumberIntType, &imageSize);
if (thumbnailSize)
{
createKeys[0] = kCGImageSourceCreateThumbnailWithTransform;
createValues[0] = (CFTypeRef)kCFBooleanTrue;
createKeys[1] = kCGImageSourceCreateThumbnailFromImageIfAbsent;
createValues[1] = (CFTypeRef)kCFBooleanTrue;
createKeys[2] = kCGImageSourceThumbnailMaxPixelSize;
createValues[2] = (CFTypeRef)thumbnailSize;
createOptions = CFDictionaryCreate(NULL, (const void **) createKeys,
createValues, sizeof(createValues)/ sizeof(createValues[0]),
&kCFTypeDictionaryKeyCallBacks,
& kCFTypeDictionaryValueCallBacks);
if (createOptions)
{
thumbnailImage = CGImageSourceCreateThumbnailAtIndex(imageSource,0,createOptions);
if(thumbnailImage)
{
thumbnail = [UIImage imageWithCGImage:thumbnailImage];
if (thumbnail)
{
thumbnailData = UIImagePNGRepresentation(thumbnail);
}
}
}
}
}
在iOS12中为同一图像获取不同的thumbnailData.length
值。我正在尝试使用CGImageSourceCreateThumbnailAtIndex()
创建缩略图图像并将sourceImage
作为参数传递。这是iOS12的错误吗?它有解决方法吗?我正在使用iOS12 beta4。
数据大小不同,但生成的图像很好。他们显然对算法进行了一些非常适度的改动。但这里没有错误。
就个人而言,我注意到两个变化:
UInt8
值)。这是相同的delta图像,这次是水平爆炸,所以你可以看到差异:
最重要的是,算法显然有一些变化,但我不认为它是一个错误。它只是不同,但它工作正常。
在一个不相关的观察中,您的代码有一些泄漏。如果Core Foundation方法在名称中包含Create
或Copy
,则您负责释放它(或者,在桥接类型中,将所有权转移到ARC,这不是一个选项)。静态分析器shift + command + B非常适合识别这些问题。
FWIW,这是我的演绎:
- (UIImage * _Nullable)resizedImage:(UIImage *)sourceImage to:(NSInteger)imageSize {
NSData *squareData = UIImagePNGRepresentation(sourceImage);
UIImage *thumbnail = nil;
CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)squareData, NULL);
if (imageSource) {
NSDictionary *createOptions = @{
(id)kCGImageSourceCreateThumbnailWithTransform: @true,
(id)kCGImageSourceCreateThumbnailFromImageIfAbsent: @true,
(id)kCGImageSourceThumbnailMaxPixelSize: @(imageSize)
};
CGImageRef thumbnailImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (CFDictionaryRef)createOptions);
if (thumbnailImage) {
thumbnail = [UIImage imageWithCGImage:thumbnailImage];
if (thumbnail) {
NSData *data = UIImagePNGRepresentation(thumbnail);
// do something with `data` if you want
}
CFRelease(thumbnailImage);
}
CFRelease(imageSource);
}
return thumbnail;
}