简体   繁体   中英

How to reduce size of image display on UIImageView

My problem is that, in my app I have UIImageview , button1 , button2 . button1 is used to access images from saved photolibrary and button2 is used to store image in database,

But image size is (800x800) which is very large, I want to store it at (50x50) size

How to reduce size of image when button2 is clicked?

// grab the original image
UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];

UIImage *scaledImage = [UIImage imageWithCGImage:[originalImage CGImage] scale:50/800 orientation:UIImageOrientationUp];

This category will do the job for you -

UIImage+Additions.h -

@interface UIImage (UIImageAdditions)
- (UIImage*)scaleToSize:(CGSize)size;
@end

UIImage+Additions.m -

@implementation UIImage (UIImageAdditions)

- (UIImage*)scaleToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;
}
@end
+ (UIImage*)imageWithImage:(UIImage*)image 
               scaledToSize:(CGSize)newSize;
{
   UIGraphicsBeginImageContext( newSize );
   [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
   UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   return newImage;
}

Pls see this previous SO question What's the easiest way to resize/optimize an image size with the iPhone SDK? for further reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM