8

我正在尝试使用CGImageSourceCreateThumbnailAtIndex有效地创建图像的调整大小版本。我有一些现有代码可以使用磁盘中的图像执行此操作,现在我正在尝试使用来自ALAssetsLibrary.

这是我的代码:

ALAsset *asset;
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];

CGDataProviderRef provider = CGImageGetDataProvider(imageRef);
CGImageSourceRef sourceRef = CGImageSourceCreateWithDataProvider(provider, NULL);

NSDictionary *resizeOptions = @{
  kCGImageSourceCreateThumbnailWithTransform : @YES,
  kCGImageSourceCreateThumbnailFromImageAlways : @YES,
  kCGImageSourceThumbnailMaxPixelSize : @(2100) 
};

CGImageRef resizedImage = CGImageSourceCreateThumbnailAtIndex(source, 0, resizeOptions);

问题是它resizedImage为空,并CGImageSourceGetCount(sourceRef)返回 0。不过,数据提供程序中确实有相当多的数据,而且这些数据看起来确实是有效的图像数据。来自ALAssetiPhone 4S 相机胶卷。

我错过了什么?为什么要CGImageSourceCreateWithDataProvider()创建一个包含 0 个图像的图像源?

4

4 回答 4

4

CGImageSource 用于反序列化序列化图像,例如 JPEG、PNG 等。

CGImageGetDataProvider返回(提供者)图像的原始像素数据。它不会以某种外部格式返回序列化字节。CGImageSource 无法知道任何给定的原始像素数据的像素格式(颜色空间、每个组件的位数、alpha 布局等)。

您可以尝试获取资产代表的 URL 并将其提供给CGImageSourceCreateWithURL. 如果这不起作用(例如,不是文件 URL),您将不得不通过 CGImageDestination 运行图像,并在您放置输出的任何位置创建一个 CGImageSource。

(要尝试的另一件事是查看代表filename是否实际上是一条完整的路径,这是 Cocoa 经常滥用该术语的方式。但您可能不应该指望这一点。)

于 2013-06-26T23:59:01.150 回答
2

One thing you might try is the asset rep's CGImageWithOptions: method.

The documentation claims that:

This method returns the biggest, best representation available, unadjusted in any way.

But it says that about fullResolutionImage, too, and I'm not sure why this class would have both methods if they both do the same thing. I wonder if it's a copy-and-paste error.

Try CGImageWithOptions: with a bunch of thumbnail-creating options and see what happens.

于 2013-06-27T00:00:58.770 回答
1

Option #3 would be the rep's fullScreenImage. Depending on what sort of “thumbnail” you need, it may be cheaper and/or simpler to just use this, which will be no bigger than (approximately) the size of the device's screen.

于 2013-06-27T00:02:37.540 回答
0

这也可以帮助...

ALAssetRepresentation* rep = [asset defaultRepresentation];

NSDictionary* options = [[NSDictionary alloc] initWithObjectsAndKeys:
                     (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
                     (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageAlways, 
                     (id)[NSNumber numberWithDouble:400], (id)kCGImageSourceThumbnailMaxPixelSize, 
                     nil];

CGImageRef image = [rep CGImageWithOptions:options];
于 2015-03-29T16:27:52.617 回答