jamshed jamshed - 1 year ago 127
iOS Question

iOS UIImage dimension change not working

I am resizing a

by changing the dimension. But it shows different dimension. For iPhone 6, I choose 1.25 time than the screen dimension which should come 937*1667. But after completing my resize operation is becomes 938*1251. I need it in declared dimension.

My code is :

NSData *imageData;
imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];

CGSize sz;

if([imageData length]/1024>400)
image=[self resizeImage:image scaledToSize:sz];

//function call

-(UIImage *)resizeImage:(UIImage *)image scaledToSize:(CGSize)targetSize
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = targetSize.height;
float maxWidth = targetSize.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.50;//50 percent compression

if (actualHeight > maxHeight || actualWidth > maxWidth)
if(imgRatio < maxRatio)
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
else if(imgRatio > maxRatio)
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
actualHeight = maxHeight;
actualWidth = maxWidth;

CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
return [UIImage imageWithData:imageData];


What could be solution for correct dimension ?

Answer Source

Yes, finally i solved it after few hours. I tried in a wrong way. Actually, the dimension can not be fixed when we resize in a particular memory size. The following method convert the image into ranged size (Byte) and the dimension will be define by the method itself.

     NSData *imageData;
    imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];
    CGFloat scale= (400*1024)/(CGFloat)[imageData length];
    UIImage *small_image=[UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
    imageData = UIImageJPEGRepresentation(small_image, scale);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download