B.S.
B.S.

Reputation: 21726

UIImage strange scaling

I have some file with size (1000x1000 for example).

I want to load it and make it smaller

UIImage *newImage = [UIImage imageWithCGImage:[UIImage imageWithContentsOfFile:filename].CGImage scale:(1.0f / scale) orientation:UIImageOrientationUp];
NSLog(newImage size: %f, %f", newImage.size.width, newImage.size.height);
// shows correct scaled size -> 50, 50

Then i want to save this scaled image

NSData* imageData = UIImageJPEGRepresentation(newImage, 1.0);
[imageData writeToFile:otherFileName atomically:NO];

I was confused to see that new image was saved with first start size(1000x1000).

How can it be possible and what to do with this?

Upvotes: 0

Views: 212

Answers (2)

Shah Paneri
Shah Paneri

Reputation: 739

Just make one method:

-(UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {

    float width = newSize.width;
    float height = newSize.height;

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect: CGRectMake(0, 0, width, height)];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return smallImage;
}

And set your required size like this:

UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)]; // i have taken 150 you can change value here

Upvotes: 2

Nitin Gohel
Nitin Gohel

Reputation: 49710

you can create Image With smaller size witout scratch image Using Bellow Method:-

you can called bellow method like:-

newImage=[self scaleImage:newImage toSize:CGSizeMake(250, 250)];


- (UIImage*) scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize scaledSize = newSize;
    float scaleFactor = 2.0;
    if( image.size.width > image.size.height ) {
        scaleFactor = image.size.width / image.size.height;
        scaledSize.width = newSize.width;
        scaledSize.height = newSize.height / scaleFactor;
    }
    else {
        scaleFactor = image.size.height / image.size.width;
        scaledSize.height = newSize.height;
        scaledSize.width = newSize.width / scaleFactor;
    }

    UIGraphicsBeginImageContextWithOptions( scaledSize, NO, 0.0 );
    CGRect scaledImageRect = CGRectMake( 0.0, 0.0, scaledSize.width, scaledSize.height );
    [image drawInRect:scaledImageRect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return scaledImage;
}

Upvotes: 1

Related Questions