In iOS, how to convert a web image into a less-qua

2019-08-20 02:40发布

问题:

The app downloads images from the web and shows them in a table view as thumbnails. However, the quality of these image are "too good". They are HD quality and if there are too many images in a table view, it might slow down the UI a bit.

Before I set the image to a cell, how to make it "less quality"? (occupying less memory & requiring less processing power to show them)

I tried something like this:

let smallerImage = UIImage(CGImage: image.CGImage!, scale: 0.2, orientation: image.imageOrientation)

but it's not working as expected. What's the right way to do it?

回答1:

Here is my working code from an old project from before the Swift era. An extra parameter maxLength passes the maximum height and width to use (for portrait it's max height, for landscape it's max width). Hope you know how to translate from Ojbective-C to Swift:

- (UIImage *) scaleImage: (UIImage *) image toMax: (float) maxLength
{
    //scale down image to fit withing square of maxLength x maxLength
    CGSize size = image.size;
    printf("scaleImage source size: %f, %f\n", size.width, size.height);
    float scaleX = size.width / maxLength;
    float scaleY = size.height / maxLength;
    float scale = scaleX > scaleY ? scaleX : scaleY;
    int newWidth = round(size.width / scale);
    int newHeight = round(size.height / scale);
    CGSize newSize = CGSizeMake(size.width / scale, size.height / scale);
    printf("scaleImage new size: %d, %d\n", newWidth, newHeight);
    UIGraphicsBeginImageContext( newSize );// a CGSize that has the size you want
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    //image is the original UIImage
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    
    return newImage;
}

Applying such scaling does indeed limit the total memory consumed by the thumbnails.