jamshed jamshed - 4 months ago 29
iOS Question

iOS UIImage dimension change not working

I am resizing a

UIImage
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;
sz.width=((isIphone4||isIphone5)?320*2.3:iPhone6?750*1.25:414*1.8);
sz.height=((isIphone4||isIphone5)?568*2.3:iPhone6?667*1.25:768*1.8);

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;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}

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

}


What could be solution for correct dimension ?

Answer

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