Detect if PNG file is corrupted in Objective C

后端 未结 3 2051
渐次进展
渐次进展 2021-01-03 06:43

I\'m downloading jpgs and pngs using NSURLRequest. This works ok but sometimes the files are corrupted. I have seen Catching error: Corrupt JPEG data: premature end of data

3条回答
  •  礼貌的吻别
    2021-01-03 06:49

    Nicer version of dataIsValidPNG:

    BOOL dataIsValidPNG(NSData *data) {
    
        if (!data) {
            return NO;
        }
    
        const NSInteger totalBytes = data.length;
        const char *bytes = (const char *)[data bytes];
        const char start[] = { '\x89',  'P',  'N',  'G', '\r', '\n', '\x1a', '\n' };
        const char end[]   = {   '\0', '\0', '\0', '\0',  'I',  'E',    'N',  'D', '\xAE', 'B', '`', '\x82' };
    
        if (totalBytes < (sizeof(start) + sizeof(end))) {
            return NO;
        }
    
        return (memcmp(bytes, start, sizeof(start)) == 0) &&
               (memcmp(bytes + (totalBytes - sizeof(end)), end, sizeof(end)) == 0);
    }
    

提交回复
热议问题