Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Image to certain size while retaining aspect ratio, crop image if necessary (iOS)

Tags:

ios

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"];
}
like image 654
chrisbedoya Avatar asked Jul 30 '15 14:07

chrisbedoya


People also ask

How do I resize an image without changing the aspect ratio?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

How do I crop a picture to a specific size or aspect ratio?

Crop Image to an Aspect Ratio Click Upload an image and select the image you want to crop. Under step 2, click the Fixed Aspect Ratio button, then enter that ratio, such as 5 and 2, and click Change. Drag a rectangle over the image to select the area you want. Move the selection as needed, then click Crop.

How do I resize a photo on my iPhone without cropping it?

To get started, open the Shortcuts app on your iPhone or iPad. In the “My Shortcuts” tab, tap the Plus (“+”) button in the top-right corner to create a new shortcut. Tap the “Add Action” button. Search for and then add the “Resize Image” action.


Video Answer


2 Answers

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;
}
like image 92
Vlad Papko Avatar answered Oct 12 '22 23:10

Vlad Papko


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 :)

like image 33
Adela Toderici Avatar answered Oct 13 '22 00:10

Adela Toderici