gpt4 book ai didi

ios - 从 Parse.com 下载图像并检查图像是否损坏

转载 作者:可可西里 更新时间:2023-11-01 04:56:54 27 4
gpt4 key购买 nike

mM 应用程序从我的 Parse.com 后端下载一些新图像。示例代码:

//Where object is a downloaded PFObject
PFFile *image = object[@"image"];
[image getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {

if(!error) {
UIImage *image = [UIImage imageWithData:data];
//Do more work here…
}
}

但是我注意到,如果连接出现问题或出现某种一般性错误,图像将被下载(没有错误),但图像将被黑色锯齿状线条扭曲并且不完整。有没有办法检查下载的图片是否完好无损?

最佳答案

我之前也遇到过这个问题,我检查了一个header并将Content-Length与下载完成的数据进行了比较。

如果 Web 服务器正常工作并且可以返回正确的 Content-Length 响应,您可以使用它来检查数据。

这是一个仅下载请求 header 的片段:

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
request.HTTPMethod = @"HEAD";
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];

if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary header = [response allHeaderFields];
NSString *rawContentLength = [header objectForKey:@"Content-Length"];
NSNumber *contentLength = [NSNumber numberWithInt:[rawContentLength intValue]];
// Convert contentLength to NSUInteger and use to compare with you NSData length.
}

您还可以将它与用于下载图像以保存 HTTP 请求的 NSHTTPURLResponse 一起使用。

接下来是获取 NSData 的长度。您可以使用方法:

NSUInteger dataLength = [downloadedData length];

然后比较两个值,如果两个长度相等,则下载完成,否则需要重新下载。

您还可以通过读取 Content-Type header 并检查数据的一些第一个和最后一个字节来检查图像是否已损坏。

对于 PNG How to check if downloaded PNG image is corrupt?不要忘记将“byte”转换为“char”,无论如何你都会看到警告。

对于 JPEG Catching error: Corrupt JPEG data: premature end of data segment

希望对您有所帮助。 :)

关于ios - 从 Parse.com 下载图像并检查图像是否损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954350/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com