是否有办法更改某些数据 - 更具体地说:图像 - 在缓存之前?
我从一个非常大的api下载图像。我想在它们到达时将它们缩小,以便它们需要更少的空间,并且每次从缓存加载时我都不必缩放它们。
我可以在AFImageResponseSerializer
的子类或STAHTTPRequestOperation
的子类中进行缩放。但在任何一种情况下,图像都已经以原始大小缓存。
如何在将数据写入缓存之前访问和更改数据?
答案 0 :(得分:0)
回答我自己的问题:我通过在操作类中覆盖connection:willCacheResponse:
来实现它。
@implementation MYImageRequestOperation
-(CGSize)size
{
return CGSizeZero; // overwritten in subclasses
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
UIImage *image = [UIImage imageWithData:cachedResponse.data];
GPUImageLanczosResamplingFilter *resizingFilter = [[GPUImageLanczosResamplingFilter alloc] init];
CGFloat scale = [UIScreen mainScreen].scale;
CGSize size = [self size];
[resizingFilter forceProcessingAtSizeRespectingAspectRatio: CGSizeMake(size.width * scale, size.height * scale)];
GPUImagePicture *gpuImage = [[GPUImagePicture alloc] initWithImage:image];
[gpuImage addTarget:resizingFilter];
[gpuImage processImage];
UIImage *smallImage = [resizingFilter imageFromCurrentlyProcessedOutput];
NSData *data;
if([[cachedResponse.response.MIMEType lowercaseString] isEqualToString:@"image/png"])
{
data = UIImagePNGRepresentation(smallImage);
} else {
data = UIImageJPEGRepresentation(smallImage, .9);
}
NSCachedURLResponse *response = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:data];
return response;
}
@end