Resize Image to scale for a given max dimension in iphone

Generally , It is required to resize image for a given max size. the ratio of the image width and height is called Aspect ratio. If resized image aspect ratio is different from original image then it is distorted. So, It is required to resize the image in such a way that it must be in the given max size keeping same aspect ratio.
Suppose our image object is selImage to be resized in iPhone app. See following code for this:
CGFloat newWidth = selImage.size.width;
 CGFloat newHeight = selImage.size.height;
 CGFloat maxWidth = [[dict valueForKey:@"MaxWidth"] floatValue];
 CGFloat maxHeight = [[dict valueForKey:@"MaxHeight"] floatValue]; 
 //Scale the Image
 CGFloat scale = 0.0;
 if (newWidth > maxWidth || newHeight > maxHeight)
  if (maxWidth/newWidth < maxHeight/newHeight)
   scale = maxWidth/newWidth;
   scale = maxHeight/newHeight;
  newWidth = newWidth*scale;
  newHeight = newHeight*scale;
selImage = [self resizedImage:selImage Rect:CGRectMake(0.0, 0.0, newWidth, newHeight)];

- (UIImage *) resizedImage:(UIImage *)inImage Rect:(CGRect)thumbRect

 [inImage drawInRect:thumbRect];
 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
 return newImage;

Hope, It helps.

No comments:

Post a Comment