0

I'm using the UIImagePickerController to chose an image from my library and uploading it to Parse. How can I resize my image's height only? I want the image to keep it's aspect ratio but I don't want the height to be taller than 1000px.

Right now I'm resizing both the width and height to a fixed number with this code:

ViewController.h

- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height;

ViewController.h

- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
    CGSize newSize = CGSizeMake(width, height);
    CGRect newRectangle = CGRectMake(0, 0, width, height);
    UIGraphicsBeginImageContext(newSize);
    [self.image drawInRect:newRectangle];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

- (IBAction)createProduct:(id)sender {
    UIImage *newImage = [self resizeImage:self.image toWidth:750.0f andHeight:1000.0f];
    NSData *imageData = UIImagePNGRepresentation(newImage);
    PFFile *imageFile = [PFFile fileWithName:@"image.jpg" data:imageData];
}

Thanks.

chrisbedoya
  • 820
  • 7
  • 22

2 Answers2

1
+(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;
}
Alaeddine
  • 6,104
  • 3
  • 28
  • 45
0

You will have to get the aspect ration of the original dimensions and multiply that with your new height

Pseudocode

if (height > 1000){
    aspectRatio = width/height;
    height = 1000;
    width = height * aspectRatio
}

- (IBAction)createProduct:(id)sender {
    UIImage *newImage;
    if (self.image.size.height > 1000){
        CGFloat aspectRatio = self.image.size.width/self.image.size.height;
        CGFloat height = 1000;
        CGFloat width = height * aspectRatio;
        newImage = [self resizeImage:self.image toWidth:width andHeight:height];
    } else {
        newImage = self.image;
    }


    NSData *imageData = UIImagePNGRepresentation(newImage);
    PFFile *imageFile = [PFFile fileWithName:@"image.jpg" data:imageData];
}
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178