I am trying to add image to cell, it works, but the scaling is not really working, the image is scaled to some size, and stay in that size, numbers i enter to the scale function don't change a thing .(image is auto scale to some constant size)
NSURL *url = [NSURL URLWithString:icon];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *logo=[UIImage imageWithData:data scale:4];
cell.imageView.layer.masksToBounds = YES;
cell.imageView.layer.cornerRadius = 10.0;
cell.imageView.image=logo;
Implement this method and use it:
/*! Returns a UIImage which is resized image of the image provided.
#param image
The image to be resized.
#param size
The size of the image to be resized.
*/
+ (UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size {
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat requiredWidth = (imageWidth * size.height) / imageHeight;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(requiredWidth, size.height), NO, [UIScreen mainScreen].scale);
[image drawInRect:CGRectMake(0, 0, requiredWidth, size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//here is the scaled image which has been changed to the size specified
UIGraphicsEndImageContext();
return newImage;
}
Just write your masking function inside the custom cell class method declared as below.
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
[self.imageView.layer setCornerRadius:10.0];
self.imageView.layer.masksToBounds = YES;
}
Use this function to scale the images as per your requirement.
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
float theScaleFactor = 0.0f;
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
theScaleFactor = 2.0f;
} else {
theScaleFactor = 0.0f;
}
} else {
theScaleFactor = 0.0f;
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, theScaleFactor);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Hope this will help you.
Related
I'm using UIImagePickerController to choose an image from my Camera Roll and resizing it before uploading it to Parse.
I want to resize an image to certain size (let's say 750x1000) while retaining the aspect ratio of the original image. If necessary, I want to crop the image. I also want it to be easy to have different versions of the image (full size, thumbnail size). Right now I'm resizing only the height of the image. How can I achieve what I'm looking for?
Thanks.
NewProductViewController.h
#interface NewProductViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>
#property (nonatomic, strong) UIImage *image;
#property (nonatomic, strong) UIImagePickerController *imagePicker;
#property (nonatomic, weak) IBOutlet UIImageView *imageView;
- (UIImage *)imageWithImage:(UIImage *)sourceImage scaledToHeight:(float) i_height;
#end
NewProductViewController.m
- (IBAction)addImage:(id)sender {
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePicker.delegate = self;
self.imagePicker.allowsEditing = NO;
[self presentViewController:self.imagePicker animated:NO completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was selected
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
[self.imageView setImage:self.image];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage *)imageWithImage:(UIImage *)sourceImage scaledToHeight:(float) i_height {
float oldHeight = sourceImage.size.height;
float scaleFactor = i_height / oldHeight;
float newWidth = sourceImage.size.width* scaleFactor;
float newHeight = oldHeight * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (IBAction)createProduct:(id)sender {
PFObject *newProduct = [PFObject objectWithClassName:#"Product"];
UIImage *newImage = [self imageWithImage:self.image scaledToHeight:1000.f];
UIImage *thumbnailImage = [self imageWithImage:self.image scaledToHeight:410.f];
NSData *imageData = UIImageJPEGRepresentation(newImage, 0.8f);
NSData *thumbnailData = UIImageJPEGRepresentation(thumbnailImage, 0.8f);
PFFile *imageFile = [PFFile fileWithName:#"image.jpg" data:imageData];
PFFile *thumbnailFile = [PFFile fileWithName:#"thumbnail.jpg" data:thumbnailData];
newProduct[#"imageFile"] = imageFile;
newProduct[#"thumbnailFile"] = thumbnailFile;
[newProduct setObject:[PFUser currentUser] forKey:#"user"];
}
Try this one, it crops source image proportionally and then scales it to necessary size:
- (UIImage *)imageWithImage:(UIImage *)sourceImage size:(CGSize)size {
CGSize newSize = CGSizeZero;
if ((sourceImage.size.width / size.width) < (sourceImage.size.height / size.height)) {
newSize = CGSizeMake(sourceImage.size.width, size.height * (sourceImage.size.width / size.width));
} else {
newSize = CGSizeMake(size.width * (sourceImage.size.height / size.height), sourceImage.size.height);
}
CGRect cropRect = CGRectZero;
cropRect.origin.x = (sourceImage.size.width - newSize.width) / 2.0f;
cropRect.origin.y = (sourceImage.size.height - newSize.height) / 2.0f;
cropRect.size = newSize;
CGImageRef croppedImageRef = CGImageCreateWithImageInRect([sourceImage CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:croppedImageRef];
CGImageRelease(croppedImageRef);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), NO, 0.0);
[croppedImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
This code can help you:
UIImage *originalImage = [UIImage imageNamed:#"minions.png"];
CGSize destination = CGSizeMake(750, 1000);
UIGraphicsBeginImageContext(destination);
[originalImage drawInRect:CGRectMake(0,0,destination.width,destination.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *new = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 750, 1000)];
new.image = newImage;
[self.view addSubview:New];
Let me know if it works for you :)
When scaling to precise width or height you may lose image resolution. So my solution is to crop to aspect ratio:
Swift 3
func cropImage(image: UIImage, to aspectRatio: CGFloat) -> UIImage {
let imageAspectRatio = image.size.height/image.size.width
var newSize = image.size
if imageAspectRatio > aspectRatio {
newSize.height = image.size.width * aspectRatio
} else if imageAspectRatio < aspectRatio {
newSize.width = image.size.height / aspectRatio
} else {
return image
}
let center = CGPoint(x: image.size.width/2, y: image.size.height/2)
let origin = CGPoint(x: center.x - newSize.width/2, y: center.y - newSize.height/2)
let cgCroppedImage = image.cgImage!.cropping(to: CGRect(origin: origin, size: CGSize(width: newSize.width, height: newSize.height)))!
let croppedImage = UIImage(cgImage: cgCroppedImage, scale: image.scale, orientation: image.imageOrientation)
return croppedImage
}
This is a simple method I created
-(UIImage *)getRescaledImage:(UIImage *)image{
int height = image.size.height;
int width = image.size.width;
int max = MOImageMaxHeightWidth;
float divideFactor = 0;
if(!(height > max) || !(width > max)){
return image;
}
if(height > width){
divideFactor = height/max;
}else{
divideFactor = width/max;
}
height = height/divideFactor;
width = width/divideFactor;
return [self imageWithImage:image scaledToSize:CGSizeMake(width, height)];
}
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
MOImageMaxHeightWidth is a constant float value which you can give define for the max width/height. The aspect ratio of the image will be maintained. The variable divideFactor will take care of it and is self explanatory.
I have used below UIImage Categories. Hope this will work for you too.
https://github.com/mbcharbonneau/UIImage-Categories
CGFloat scale = .5f;
CGFloat maxSize = 1632 * 1224;
CGFloat currentSize = croppedImage.size.width * croppedImage.size.height;
if ((currentSize / 2) > maxSize) {
scale = maxSize / currentSize;
}
CGSize size = CGSizeMake(croppedImage.size.width * scale, croppedImage.size.height * scale);
__block UIImage *imageToSave = [croppedImage resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:size interpolationQuality:kCGInterpolationLow];
I'm adding the overlay using pickerController's view and the uinavigationcontrollerdelegate as below.
-(void)navigationController:(UINavigationController *)navigationController didShowViewController: (UIViewController *)viewController animated:(BOOL)animated{
if ([navigationController.viewControllers count] == 3)
{
CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
UIView *plCropOverlay = [[[viewController.view.subviews objectAtIndex:1]subviews] objectAtIndex:0];
plCropOverlay.hidden = YES;
int position = 0;
if (screenHeight == 568)
{
position = 124;
}
else
{
position = 80;
}
CAShapeLayer *circleLayer = [CAShapeLayer layer];
UIBezierPath *path2 = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0.0f, position, 320.0f, 320.0f)];
[path2 setUsesEvenOddFillRule:YES];
[circleLayer setPath:[path2 CGPath]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 320, screenHeight-72) cornerRadius:0];
[path appendPath:path2];
[path setUsesEvenOddFillRule:YES];
CAShapeLayer *fillLayer = [CAShapeLayer layer];
fillLayer.path = path.CGPath;
fillLayer.fillRule = kCAFillRuleEvenOdd;
fillLayer.fillColor = [UIColor blackColor].CGColor;
fillLayer.opacity = 0.8;
[viewController.view.layer addSublayer:fillLayer];
}
}
When the overlay defined above is added, I tend to get this view:
I can crop the image exactly to a square using a defined CGRect.
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
How about approaching this problem where there is a circular overlay and imagePickers editing property is YES? I can zoom in and zoom out of the pic. How can i make use of the BezierPath here?
the short answer to your question addClip , but you mention you're a beginner, so here's all the steps from A to Z!!
Firstly, try this category, see if it helps. (If you're not familiar w/ categories have a google or just ask here in a comment.)
-(UIImage *)doMask
{
UIImage *maskImage = [UIImage imageNamed:#"yourMask.png"];
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef maskedImageRef = CGImageCreateWithMask([self CGImage], mask);
UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
CGImageRelease(mask);
CGImageRelease(maskedImageRef);
return maskedImage;
}
just create (I mean in photoshop) a png mask, and get familiar with that process.
I encourage you to master that process first...
Here are critical categories that will help...
-(UIImage *)becomeSquare
{
CGSize imageSize = self.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
UIImage *result = self;
if (width != height)
{
CGFloat newDimension = MIN(width, height);
CGFloat widthOffset = (width - newDimension) / 2;
CGFloat heightOffset = (height - newDimension) / 2;
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(newDimension, newDimension), NO, 0. );
[result drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
blendMode:kCGBlendModeCopy alpha:1. ];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return result;
}
and a couple more ...
-(UIImage *)doScale
{
UIImage *result = self;
CGSize size = CGSizeMake(320,320);
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[result drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
-(UIImage *)scaled640AnyShape
{
if ( self.size.height < 5.0 ) return nil;
if ( self.size.width < 5.0 ) return nil;
UIImage *result = self;
float widthShouldBe = 640.0;
float heightShouldBe = widthShouldBe * ( self.size.height / self.size.width );
CGSize size = CGSizeMake( widthShouldBe ,heightShouldBe );
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[result drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
(obviously change the hard-coded output sizes as you wish.)
Note that your final result, will be achieved, by a combination in the appropriate order, such as:
yourImage = [yourImage doSquare];
yourImage = [yourImage doMask];
once you've got that working ...
Then ....
for LITERALLY what you ask, there are many example codes about .. e.g., what about https://stackoverflow.com/a/13870097/294884
As you can see, you fundamentally...
UIGraphicsBeginImageContextWithOptions(...);
UIBezierPath * path = [UIBezierPath
bezierPathWithRoundedRect:imageRect cornerRadius:10.f];
[path addClip];
[yourImage drawInRect:imageRect];
... then ... UIGraphicsGetImageFromCurrentImageContext();
.. see the extensive code above for how to save it and so on.
You just have to get the zoom right with the scaling examples above.
Also note this, when you are changing the "area cropped"... https://stackoverflow.com/a/17884863/294884
here's an example of that critical technique...
-(UIImage *)squareAndSmall
{
// genius credits: https://stackoverflow.com/a/17884863/294884
CGSize finalsize = CGSizeMake(640,640);
CGFloat scale = MAX(
finalsize.width/self.size.width,
finalsize.height/self.size.height);
CGFloat width = self.size.width * scale;
CGFloat height = self.size.height * scale;
// for example, the central area....
CGRect imageRect = CGRectMake(
(finalsize.width - width)/2.0f,
(finalsize.height - height)/2.0f,
width, height);
// or, the top area... CGRect imageRect = CGRectMake( 0, 0, width, height);
UIGraphicsBeginImageContextWithOptions(finalsize, NO, 0);
[self drawInRect:imageRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Hope it all helps!
Found this blog post entry very interesting, neat and simple to follow by Nimit Parekh.
Following code is copy/paste into your “viewcontroller.h” file:
#import <UIKit/UIKit.h>
#interface UIImagePickerDemoViewController : UIViewController< UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property(nonatomic,retain) UIImagePickerController *imgPicker;
#property(nonatomic,retain) IBOutlet UIImageView *image_view;
//- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect;
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage;
#end
Following Code copy/paste into “viewcontroller.m” file:
// Following method is use for the mask the image.
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
// Following method is use for Cropping the image for a perticular size.
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 0.0, rect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);
CGRect drawRect = CGRectMake(rect.origin.x * -1,rect.origin.y * -1,imageToCrop.size.width,imageToCrop.size.height);
CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
CGContextScaleCTM(currentContext, 1.0, -1.0);
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cropped;
}
// Calling the method of maskimage.
//=============================Camera Enable(display)============================================
-(IBAction)next:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:self.imgPicker animated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *img = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
self.image_view.image=[self maskImage:img withMask:[UIImage imageNamed:#"frame.png"]];
}
//===============================================================================================
// Calling the method of cropping the image.
//=============================Camera Enable(display)============================================
-(IBAction)next:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:self.imgPicker animated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage *img = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
self.image_view.image = [self imageByCropping:img toRect:CGRectMake(0, 0, 420, 40)];
}
//===============================================================================================
Output:
Grab the source code here.
Im having exactly the same profile image picker controller as your. Here is my code from delegate. I don't think you need everything but you can find some useful information here
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString *) kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
UIImage *editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
CGRect croppingRect = [info[UIImagePickerControllerCropRect] CGRectValue];
if (editedImage) {
image = editedImage;
} else {
CGFloat smaller = 1;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
smaller = 0.9;
}
CGFloat width = MIN(image.size.width * smaller, image.size.height * (smaller * 0.95));
croppingRect = CGRectMake(0 + (image.size.width - width) / 2,
0 + (image.size.height - width) / 2,
width, width);
}
UIImage *finalImage = nil;
if (editedImage) {
finalImage = [UIImage image:editedImage byScalingAndCroppingForSize:kCroppedImageSize];
} else {
finalImage = [UIImage image:image byScalingAndCroppingForSize:kCroppedImageSize];
}
if ([self.imagePickerDelegate respondsToSelector:#selector(profileImagePicker:didSelectImage:)]) {
[self.imagePickerDelegate profileImagePicker:self didSelectImage:finalImage];
} else {
NSAssert(nil, #"Delegate should confirm ProfileImagePickerControllerDelegate protocol");
}
} else if ([mediaType isEqualToString:(NSString *) kUTTypeVideo]) {
NSAssert(nil, #"Movie is not supported");
}
}
After going through this link, issue with my code is that output image is unable to set proper x and y values as cropped image seems to have 0 and 0 in the resultant image irrespective to where I zoom (or where the scroll offset is calculated). Here's what I tried.
- (IBAction)crop:(id)sender
{
float zoomScale = 1.0f / [self.scroll zoomScale];
CGRect rect;
NSLog(#"contentOffset is :%f,%f",[self.scroll contentOffset].x,[self.scroll contentOffset].y);
rect.origin.x = self.scroll.contentOffset.x * zoomScale;
rect.origin.y = self.scroll.contentOffset.y * zoomScale;
rect.size.width = self.scroll.bounds.size.width * zoomScale;
rect.size.height = self.scroll.bounds.size.height * zoomScale;
UIGraphicsBeginImageContextWithOptions( CGSizeMake(rect.size.width, rect.size.height),
NO,
0.);
NSLog(#"rect offset is :%f,%f",rect.origin.x,rect.origin.y);
CGPoint point = CGPointMake(-rect.origin.x, -rect.origin.y); **//even though above NSLog have some values, but output image is unable to set proper x and y values as cropped image seems to have 0 and 0 in the resultant image.**
[[self.imagV image] drawAtPoint:point
blendMode:kCGBlendModeCopy
alpha:1];
self.croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
DTImageViewController *imageViewController = [[DTImageViewController alloc] initWithNibName:#"DTImageViewController" bundle:nil];
imageViewController.image = self.croppedImage;
[self.navigationController pushViewController:imageViewController animated:YES];
}
Similar code as already posted but just taking whole UIScrollView bounds without passing a CGRect
-(void)takeScreenShotOfScrollView
{
UIGraphicsBeginImageContextWithOptions(scrollView.bounds.size, YES, [UIScreen mainScreen].scale);
CGPoint offset = scrollView.contentOffset;
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y);
[scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
img = [SDImageHelper imageWithImage:img_image scaledToSize:CGSizeMake(769, 495)];
}
BONUS:
The cropping method
+(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
I'm using the following code for this and it does exactly what expected:
- (UIImage *) croppedImageOfView:(UIView *) view withFrame:(CGRect) rect
{
UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -rect.origin.x, -rect.origin.y);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return visibleScrollViewImage;
}
- (void) crop
{
CGRect neededRect = CGRectMake(50,50,100,100);
UIImage *image = [self croppedImageOfView:_scrollView withFrame:neededRect];
}
Works well even if content is zoomed, the only thing that must be calculated wisely is needed area CGRect.
How can I crop my imageView into a bubble shape which I have the image in my project.
Following is simple code for resizing or crop image, you need to just pass height or width for image as you want:
For Get Croped Image:
UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS YOu Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
Use following method that return UIImage (as You want size of image)
- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
Here you get Croped Image that return by above method;
OR RESIZING
And also Use following method for specific hight and width with image for Resizing UIImage:
+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
CGSize newSize = CGSizeMake(width, height);
float widthRatio = newSize.width/image.size.width;
float heightRatio = newSize.height/image.size.height;
if(widthRatio > heightRatio)
{
newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
}
else
{
newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
This method return NewImage, with specific size that you want.
I am in trouble with my App and expecting your help. I want to upload photo with specific size**(1200*1800)** from library to server,and I need to get original image then compress it.
UIImage *image = [UIImage imageWithCGImage:[asset fullResolutionImage] scale:[asset scale] orientation:0];
Unfortunately my app will get crashed if the original image size is large than 20M. So is there any way to get the image with specific size from AssetsLibrary directly?
I just Put some Helpful code, i am not sure but might be helpful in your case:
For Get Crop Image:
UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS YOu Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
Use following method that return UIImage (as You want size of image)
- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
Here you get Croped Image that return by above method;
OR RESIZING
And also Use following method for specific hight and width with image for Resizing UIImage:
+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
CGSize newSize = CGSizeMake(width, height);
float widthRatio = newSize.width/image.size.width;
float heightRatio = newSize.height/image.size.height;
if(widthRatio > heightRatio)
{
newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
}
else
{
newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
}
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
This method return NewImage, with specific size that you want.