ios - 下载图像编辑图像然后缓存
<p><p>UIImageview + afnetworking 下载图片并缓存图片。</p>
<p>但在某些情况下,服务器图像 = 15mb。所以我需要根据一些因素对它们进行压缩并使其达到 1mb,然后需要缓存它们。</p>
<p>另一方面,SDWebImageCache 让您定义自己的缓存并存储它们</p>
<p>是否有任何内置机制用于下载、编辑然后保存到缓存中?</p>
<pre><code>[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
{
if (image && finished)
{
// do something with image
}
}];
</code></pre>
<p>然后使用
[ storeImage:myImage forKey:myCacheKey]</p>
<p>除了做这样的事情还有其他选择吗?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您使用 <code>SDWebImage</code> 的场景是正确的。<br/>
出于编辑目的,您需要将委托(delegate)设置为 <code>SDWebImageManager</code> 对象并实现必要的方法:</p>
<pre><code>// Set delegate
.delegate = self;
// Implement delegate method
- (UIImage *)imageManager:(SDWebImageManager *)imageManager
transformDownloadedImage:(UIImage *)image
withURL:(NSURL *)imageURL {
UIImage scaledImage = ... // Make scale based on 'image' object
return scaledImage;
}
</code></pre>
<p>请注意,此方法在图像下载后立即调用,但在将其存储到内存缓存之前以及调用完成 block 之前。<br/>
此方法的文档:</p>
<blockquote>
<p>Allows to transform the image immediately after it has been downloaded
and just before to cache it on disk and memory. NOTE: This method is
called from a global queue in order to not to block the main thread.</p>
</blockquote>
<p>之后,您将能够在您的问题中使用 <code>SDWebImageDownloader</code> 和 <code>SDImageCache</code>:</p>
<pre><code>[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
// progression tracking code
}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (image && finished) {
[ storeImage:image forKey:myCacheKey];
}
}];
</code></pre>
<p>然后就可以使用<code>SDImageCache</code>类的方法来管理缓存了:</p>
<pre><code>- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
</code></pre>
<p>如果您需要最大数据大小的图像缩放算法,请查看 <a href="https://stackoverflow.com/questions/20403805/how-to-downscale-a-uiimage-in-ios-by-the-data-size" rel="noreferrer noopener nofollow">this</a>回答。</p></p>
<p style="font-size: 20px;">关于ios - 下载图像编辑图像然后缓存,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/31500960/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/31500960/
</a>
</p>
页:
[1]