Using CoreImage to filter an image results in image rotation
Asked Answered
G

2

9

Thanks for reading.

I'm trying to use CoreImage in iOS 5 to alter the appearance of an image. The problem is that the existing image appears to lose its orientation information during the process and ends up rotated by 90 degrees.

Here is the code:

CIContext *context = [CIContext contextWithOptions:nil];
CIImage *img = [CIImage imageWithCGImage:imageView.image.CGImage];
CIFilter *adjustFilter = [CIFilter filterWithName:@"CIHighlightShadowAdjust"];

[adjustFilter setDefaults];
[adjustFilter setValue:img forKey:kCIInputImageKey];
[adjustFilter setValue:[NSNumber numberWithFloat:0.3] forKey:@"inputShadowAmount"];
CIImage *adjustedImage = [adjustFilter valueForKey:kCIOutputImageKey];
UIImage *newPtImage = [UIImage imageWithCGImage:[context adjustedImage fromRect:adjustedImage.extent]];

imageView.image = newPtImage;

The original image generally comes from one taken by the camera, but not always.

Hope someone can help.

Rob.

Greenburg answered 10/11, 2011 at 6:5 Comment(0)
G
40

Actually, the solution to my issue turned out to be quite simple. Since the CGImage loses its orientation and scale factors, I simply needed to add

UIImageOrientation originalOrientation = imageView.image.imageOrientation;
CGFloat originalScale = imageView.image.scale;

early in the code and then used this instead of [UIImage imageWithCGImage:]

    UIImage *newPtImage = [UIImage imageWithCGImage:img2 scale:originalScale orientation:originalOrientation];

Thanks for the suggestions too.

Greenburg answered 24/11, 2011 at 5:8 Comment(0)
C
3

Have a look at this answer https://mcmap.net/q/364279/-uiimagepickercontroller-camera-preview-is-portrait-in-landscape-app/871102

You can solve your problem passing the image to the method of the previous answer. So instead of:

CIImage *img = [CIImage imageWithCGImage:imageView.image.CGImage];

write:

UIImage *fixedImage = [self scaleAndRotateImage:imageView.image];
CIImage *img = [CIImage imageWithCGImage:fixedImage.CGImage];

UPDATE:

There is a more elegant answer without image scaling here: iOS UIImagePickerController result image orientation after upload.

Complexion answered 22/11, 2011 at 15:57 Comment(3)
This didn't work. It ran through the code but nothing happened. And it is way too long and is hacky.Gabi
How would it be in Swift? Please someone tell me!Radbourne
actual solution was bellowMonomial

© 2022 - 2024 — McMap. All rights reserved.