Authored by Bogdan Poplauschi

Refactored NSData ImageContentType category, instead of returning the contentTyp…

…e as a string, the new added method `sd_imageFormatForImageData` will return a `SDImageFormat` enum value
... ... @@ -79,8 +79,8 @@ static char imageURLKey;
completedBlock(image, error, cacheType, url);
return;
} else if (image) {
NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
if ([imageContentType isEqualToString:@"image/gif"]) {
SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data];
if (imageFormat == SDImageFormatGIF) {
wself.animatedImage = [FLAnimatedImage animatedImageWithGIFData:data];
wself.image = nil;
} else {
... ...
... ... @@ -9,15 +9,24 @@
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, SDImageFormat) {
SDImageFormatUndefined = -1,
SDImageFormatJPEG = 0,
SDImageFormatPNG,
SDImageFormatGIF,
SDImageFormatTIFF,
SDImageFormatWebP
};
@interface NSData (ImageContentType)
/**
* Compute the content type for an image data
* Return image format
*
* @param data the input data
* @param data the input image data
*
* @return the content type as string (i.e. image/jpeg, image/gif)
* @return the image format as `SDImageFormat` (enum)
*/
+ (nullable NSString *)sd_contentTypeForImageData:(nullable NSData *)data;
+ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data;
@end
... ...
... ... @@ -12,37 +12,35 @@
@implementation NSData (ImageContentType)
+ (nullable NSString *)sd_contentTypeForImageData:(nullable NSData *)data {
+ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data {
if (!data) {
return nil;
return SDImageFormatUndefined;
}
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
return SDImageFormatJPEG;
case 0x89:
return @"image/png";
return SDImageFormatPNG;
case 0x47:
return @"image/gif";
return SDImageFormatGIF;
case 0x49:
case 0x4D:
return @"image/tiff";
return SDImageFormatTIFF;
case 0x52:
// R as RIFF for WEBP
if (data.length < 12) {
return nil;
return SDImageFormatUndefined;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return @"image/webp";
return SDImageFormatWebP;
}
return nil;
}
return nil;
return SDImageFormatUndefined;
}
@end
... ...
... ... @@ -23,12 +23,12 @@
}
UIImage *image;
NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
if ([imageContentType isEqualToString:@"image/gif"]) {
SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data];
if (imageFormat == SDImageFormatGIF) {
image = [UIImage sd_animatedGIFWithData:data];
}
#ifdef SD_WEBP
else if ([imageContentType isEqualToString:@"image/webp"])
else if (imageFormat == SDImageFormatWebP)
{
image = [UIImage sd_imageWithWebPData:data];
}
... ...