@@ -32,6 +32,7 @@ @interface SDWebImageDownloaderOperation ()
3232
3333@implementation SDWebImageDownloaderOperation {
3434 size_t width, height;
35+ UIImageOrientation orientation;
3536 BOOL responseFromCached;
3637}
3738
@@ -216,12 +217,22 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
216217 if (width + height == 0 ) {
217218 CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex (imageSource, 0 , NULL );
218219 if (properties) {
220+ NSInteger orientationValue = -1 ;
219221 CFTypeRef val = CFDictionaryGetValue (properties, kCGImagePropertyPixelHeight );
220222 if (val) CFNumberGetValue (val, kCFNumberLongType , &height);
221223 val = CFDictionaryGetValue (properties, kCGImagePropertyPixelWidth );
222224 if (val) CFNumberGetValue (val, kCFNumberLongType , &width);
225+ val = CFDictionaryGetValue (properties, kCGImagePropertyOrientation );
226+ if (val) CFNumberGetValue (val, kCFNumberNSIntegerType , &orientationValue);
223227 CFRelease (properties);
228+
229+ // When we draw to Core Graphics, we lose orientation information,
230+ // which means the image below born of initWithCGIImage will be
231+ // oriented incorrectly sometimes. (Unlike the image born of initWithData
232+ // in connectionDidFinishLoading.) So save it here and pass it on later.
233+ orientation = [[self class ] orientationFromPropertyValue: (orientationValue == -1 ? 1 : orientationValue)];
224234 }
235+
225236 }
226237
227238 if (width + height > 0 && totalSize < self.expectedSize ) {
@@ -249,7 +260,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
249260#endif
250261
251262 if (partialImageRef) {
252- UIImage *image = [UIImage imageWithCGImage: partialImageRef];
263+ UIImage *image = [UIImage imageWithCGImage: partialImageRef scale: 1 orientation: orientation ];
253264 UIImage *scaledImage = [self scaledImageForKey: self .request.URL.absoluteString image: image];
254265 image = [UIImage decodedImageWithImage: scaledImage];
255266 CGImageRelease (partialImageRef);
@@ -269,6 +280,29 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
269280 }
270281}
271282
283+ + (UIImageOrientation)orientationFromPropertyValue : (NSInteger )value {
284+ switch (value) {
285+ case 1 :
286+ return UIImageOrientationUp;
287+ case 3 :
288+ return UIImageOrientationDown;
289+ case 8 :
290+ return UIImageOrientationLeft;
291+ case 6 :
292+ return UIImageOrientationRight;
293+ case 2 :
294+ return UIImageOrientationUpMirrored;
295+ case 4 :
296+ return UIImageOrientationDownMirrored;
297+ case 5 :
298+ return UIImageOrientationLeftMirrored;
299+ case 7 :
300+ return UIImageOrientationRightMirrored;
301+ default :
302+ return UIImageOrientationUp;
303+ }
304+ }
305+
272306- (UIImage *)scaledImageForKey : (NSString *)key image : (UIImage *)image {
273307 return SDScaledImageForKey (key, image);
274308}
0 commit comments