diff --git a/SDWebImage/SDWebImageDownloaderOperation.m b/SDWebImage/SDWebImageDownloaderOperation.m index 1ab77134a..74571b330 100644 --- a/SDWebImage/SDWebImageDownloaderOperation.m +++ b/SDWebImage/SDWebImageDownloaderOperation.m @@ -32,6 +32,7 @@ @interface SDWebImageDownloaderOperation () @implementation SDWebImageDownloaderOperation { size_t width, height; + UIImageOrientation orientation; BOOL responseFromCached; } @@ -216,12 +217,22 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if (width + height == 0) { CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); if (properties) { + NSInteger orientationValue = -1; CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); if (val) CFNumberGetValue(val, kCFNumberLongType, &height); val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); if (val) CFNumberGetValue(val, kCFNumberLongType, &width); + val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); + if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); CFRelease(properties); + + // When we draw to Core Graphics, we lose orientation information, + // which means the image below born of initWithCGIImage will be + // oriented incorrectly sometimes. (Unlike the image born of initWithData + // in connectionDidFinishLoading.) So save it here and pass it on later. + orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; } + } if (width + height > 0 && totalSize < self.expectedSize) { @@ -249,7 +260,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { #endif if (partialImageRef) { - UIImage *image = [UIImage imageWithCGImage:partialImageRef]; + UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; UIImage *scaledImage = [self scaledImageForKey:self.request.URL.absoluteString image:image]; image = [UIImage decodedImageWithImage:scaledImage]; CGImageRelease(partialImageRef); @@ -269,6 +280,29 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { } } ++ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { + switch (value) { + case 1: + return UIImageOrientationUp; + case 3: + return UIImageOrientationDown; + case 8: + return UIImageOrientationLeft; + case 6: + return UIImageOrientationRight; + case 2: + return UIImageOrientationUpMirrored; + case 4: + return UIImageOrientationDownMirrored; + case 5: + return UIImageOrientationLeftMirrored; + case 7: + return UIImageOrientationRightMirrored; + default: + return UIImageOrientationUp; + } +} + - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { return SDScaledImageForKey(key, image); }