UIImage Compression

I need help resizing UIImage.

For example: I show a lot of images in the UICollection view, but the size of these images is 2 to 4 MB. I need to compress or resize these images.

I found this: How to compress / resize images on iPhone OS SDK before uploading to server? but I don’t understand how to implement it.

+4
source share
4 answers

Not quite sure if you want to resize or compress, or both.

Below is the code for simple compression:

Use JPEG Compression in two simple steps:

1) Convert UIImage to NSData strong>

UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *imgData= UIImageJPEGRepresentation(rainyImage,0.1 /*compressionQuality*/);

.

2) UIImage;

UIImage *image=[UIImage imageWithData:imgData];

, . . , .

+14

:

- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
    CGSize actSize = image.size;
    float scale = actSize.width/actSize.height;

    if (scale < 1) {
        newSize.height = newSize.width/scale;
    } else {
        newSize.width = newSize.height*scale;
    }


    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

, :

[self scaleImage:yourUIImage toSize:CGMakeSize(300,300)];
+3
lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];
+3
 -(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
 {
CGFloat actualHeight = orginalImage.size.height;
CGFloat actualWidth = orginalImage.size.width;

float oldRatio = actualWidth/actualHeight;
float newRatio = size.width/size.height;
if(oldRatio < newRatio)
{
    oldRatio = size.height/actualHeight;
    actualWidth = oldRatio * actualWidth;
    actualHeight = size.height;
}
else
{
    oldRatio = size.width/actualWidth;
    actualHeight = oldRatio * actualHeight;
    actualWidth = size.width;
}

CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
UIGraphicsBeginImageContext(rect.size);
[orginalImage drawInRect:rect];
orginalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return orginalImage;
 }
      //this image you can add it to imageview.....  
0

All Articles