So I am cropping an image with a UIImageView which may or may not be very efficient. I'm some what a n00b when it comes to Graphics programming. When all my code runs I am stuck with a white image and I'm not quite sure why.
I took a look at this: Crop and save visible region of UIImageView using AspectFill and have had no success. Here is my code:
imageFile = [info objectForKey:UIImagePickerControllerOriginalImage];
selectedImage.hidden = false; //selectedImage is my UIImageView
selectedImage.image = imageFile;
UIGraphicsBeginImageContext(selectedImage.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGBitmapContextCreateImage(context);
float width = CGImageGetWidth(image);
float height = CGImageGetHeight(image);
CGImageRef cropped_img = CGImageCreateWithImageInRect(image, CGRectMake(0, 0, width, height));
imageFile = [UIImage imageWithCGImage:cropped_img];
imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];
selectedImage.image = imageFile; //Final product is white
So selectedImage
is my UIImageView
and that is what ends up being white. Any help would greatly be appreciated.
Maybe this line?
imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];
If you are getting a UIImage from the line directly above it I would not think you would then need to pass it through at an extremely low JPEG compression rate. 0 being the lowest quality, maybe it's so low it looks white. Try removing that line and or changing the compression.
In these lines
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGBitmapContextCreateImage(context);
you create a new context, that will be blank (white) and then create an image from this. So your resulting image will just be white.
The function CGImageCreateWithImageInRect
needs a CGImageRef
, which you can get from a UIImage
easily with
CGImageCreateWithImageInRect(imageFile.CGImage, CGRectMake(0, 0, width, height));
Not sure why you are doing this line
imageFile = [UIImage imageWithData:UIImageJPEGRepresentation(imageFile, 0.05f)];
This will just give you a poor quality image :/
I found the solution from this SO post: Creating UIImage from context of UIImageView
Here's the solution:
I needed to import the Quartz Core Framework: #import <QuartzCore/QuartzCore.h>
Then I used the following method:
- (UIImage*)imageFromImageView:(UIImageView*)imageView
{
UIGraphicsBeginImageContext(imageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRotateCTM(context, 2*M_PI);
[imageView.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.