0

In my app I import an image from either the camera or the photo library using a UIImagePickerController. Than I save the imported image to the app documents directory. This all works fine, however I would like to save the image cropped as a square(like on instagram) instead of it's original size.The square should be the size of either the width of the image or the height of it(depending on which is the smaller one). I figured that maybe a CGRect would be useful here, but I have no idea how to crop a CGRect out of an image..I have looked at countless tutorials but none of them seemed to work or they were all too complicated..

1

1 Answer 1

0
-(UIImage *)squareImage:(UIImage *)image
{
    if (image.size.width>=image.size.height)
    {
        image=[self imageWithImage:image scaledToHeight:100];
    }
    else
    {
    image=[self imageWithImage:image scaledToWidth:100];
    }

    return image;
}

-(UIImage*)imageWithImage:(UIImage*)sourceImage scaledToWidth:(float)width
{
    float oldWidth = sourceImage.size.width;
    float scaleFactor = width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newWidth));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

-(UIImage*)imageWithImage:(UIImage*)sourceImage scaledToHeight:(float)height
{
    float oldHeight = sourceImage.size.height;
    float scaleFactor = height / oldHeight;

    float newWidth = sourceImage.size.width * scaleFactor;
    float newHeight = oldHeight * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newHeight, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

above method will help you to scale image proportionately and scaling image in square..for rotation you can search on google.

3
  • @BalázsVincze Thank you. If you found any problem for rotation let me know. i will search some of my project for rotation code, if you want to speed up your task. Apr 28, 2015 at 20:09
  • I have solved the rotation problem with this very easy function: -(UIImage *)normalizeImage:(UIImage *)raw { if (raw.imageOrientation == UIImageOrientationUp){ return raw; } else{ UIImage* flippedImage = [UIImage imageWithCGImage:raw.CGImage scale:raw.scale orientation:-90]; return flippedImage; } } Apr 28, 2015 at 20:15
  • @BalázsVincze oh thats great. Apr 28, 2015 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.