Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating thumbnail -> ugly quality (Swift - preparingThumbnail)

Tags:

swift

This is how I create a thumbnail from Data:

let image = UIImage(data: data)!
    .preparingThumbnail(of: .init(width: size, height: size))!

try image.pngData()!.write(to: url)

The data variable contains the original image. That looks good, but I want to create thumbnails from lists.

The size variable holds a value which is the same height as my Image in SwiftUI. The problem is, it looks horrible:

Thumbnail:

enter image description here

Original:

enter image description here

The 'thumbnail' is the same size as the image above, it really looks that bad on the device, it is not stretched out. What is the correct way to create a thumbnail of the same quality in iOS 15.0>?

like image 343
NoKey Avatar asked Oct 26 '25 15:10

NoKey


1 Answers

Have you tried to consider the aspect ratio as well instead of just the size? Pass in the data (your let image = UIImage(data: data)! and see if that works)

func resizeImageWithAspect(image: UIImage,scaledToMaxWidth width:CGFloat,maxHeight height :CGFloat)->UIImage? {
    let oldWidth = image.size.width;
    let oldHeight = image.size.height;
    
    let scaledBy = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
    
    let newHeight = oldHeight * scaledBy;
    let newWidth = oldWidth * scaledBy;
    let newSize = CGSize(width: newWidth, height: newHeight)
    
    UIGraphicsBeginImageContextWithOptions(newSize,false,UIScreen.main.scale);
    
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height));
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage
}
like image 104
Justeen Avatar answered Oct 28 '25 03:10

Justeen