1

This is how I set images to UIImageView from a web url:

import UIKit

extension UIImageView {
    private var storage: Storageable {
        Assembler.shared.resolve(Storageable.self)!
    }

    private var imageDownloader: ImageDownloaderable {
        Assembler.shared.resolve(ImageDownloaderable.self)!
    }

    // MARK: - Internal

    func setImage(with url: URL) {
        downloadImage(with: url) { [weak self] image in
            self?.image = image
        }
    }

    func downloadImage(with url: URL, completion: @escaping ImageHandler) {
        imageDownloader.setAuthorization(withToken: storage.bearerToken)
        sd_setImage(with: url, placeholderImage: nil,
                    options: [.allowInvalidSSLCertificates, .avoidAutoSetImage]) { image, _, _, _ in
            completion(image)
        }
    }
}

How do I tell SDWebImage library to downsample an image to specific size, to reduce memory usage. Is it possible?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

1

From SDWebImage's Wiki on Github, you can use Image Transformers to do some image processing on the downloaded image.

let transformer = SDImageResizingTransformer(size: CGSize(300, 300), scaleMode: .fill)
let imageView: UIImageView
imageView.sd_setImage(with: url, placeholderImage: nil, context: [.imageTransformer: transformer])
atahhan
  • 211
  • 2
  • 6
  • I will check it, but will it reduce memory usage? ;) Because I need to use it in share extension and currently looking for a way to resolve it. – Bartłomiej Semańczyk Jan 15 '22 at 17:30
  • Supposedly this transforms the image _on load_ as it is mentioned under **"Transformer during loading"** section. You should give it a try and see if the memory usage is changing with this transformer applied. – atahhan Jan 15 '22 at 17:37
  • I tried and I think documentation is outdated, becasue there is no such method anymore on UIImageView. There is only sd_setImage with options of type SDWebImageOptions. No any method with context‍♂️ You have an idea why? – Bartłomiej Semańczyk Jan 15 '22 at 23:42
  • @BartłomiejSemańczyk I just tried it on `5.12.1` version of `SDWebImage` and it worked for me. – atahhan Jan 16 '22 at 17:59
  • Oww... I was on 5.12.0 and it wasnt there;) Need to check it on newer version. – Bartłomiej Semańczyk Jan 16 '22 at 18:09
  • I have run the app, but it doesnt work because it is still loaded into memory...‍♂️ – Bartłomiej Semańczyk Jan 16 '22 at 18:51
  • If original "data" being downloaded is bigger than what can be handled in your piece of code, than I don't believe there is a client side solution to this. You'll probably be better off to have the backend serve you a thumbnail or a smaller version of this image. – atahhan Jan 16 '22 at 19:20
  • I think you are right… it is backends issue;) – Bartłomiej Semańczyk Jan 16 '22 at 19:21