如何检查下载的PNG图像是否已损坏

如何检查下载的PNG图像是否已损坏

本文介绍了如何检查下载的PNG图像是否已损坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从下面的代码下载多个图像并保存到数据库。但对于某些图像,我的误差低于此值。

I am downloading multiple images from below code and saving to the DB. But for some images I am getting below error.

错误:ImageIO:PNG无效距离太远
错误:ImageIO:PNG错误数据检查

Error: ImageIO: PNG invalid distance too far backError: ImageIO: PNG incorrect data check

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
    NSString *imgStr = [dict  objectForKey:@"image"];
    imgStr = [imgStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgStr]];
    UIImage *image = [UIImage imageWithData:imgData];

    dispatch_sync(dispatch_get_main_queue(), ^{
       mYImageView.image = image;
    });
});

如何检查存储的图像是否有效,以便我可以再次下载图像?

How to check stored image is valid or not, so I can download image again?

推荐答案

对于PNG图像,检查它们的前两个字节和最后两个字节。以下是方法,希望它有所帮助。

For PNG images, check their first two bytes and last two bytes. Below is the method, hope it helps.

谢谢。 :)

- (BOOL)isImageValid:(NSData *)data
{
    BOOL val = YES;

    if ([data length] < 4)
        val = NO;

    const char * bytes = (const char *)[data bytes];

    if (bytes[0] != 0x89 || bytes[1] != 0x50)
        val = NO;
    if (bytes[[data length] - 2] != 0x60 ||
        bytes[[data length] - 1] != 0x82)
        val = NO;

    return val;
}

这篇关于如何检查下载的PNG图像是否已损坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:18