티스토리 뷰

카테고리 없음

Image Resize

Chasomin 2024. 4. 16. 16:50

사진을 메인으로하는 SNS 앱을 만들다가 이미지가 메모리를 너무 많이 차지해서 앱이 죽는 문제가 발생했다

❗️ 우선 알아야 할 점

   메모리가 이미지의 파일의 크기로 계산되는 것이 아니라 이미지의 해상도 (크기)로 계산이 된다는 점이다.

이미지를 서버에 올릴 때 압축해서 5MB 이하 크기로 만들었기 때문에 메모리도 적게 먹는 거 아냐? 했지만 해상도는 줄어들지 않았기 때문에 메모리를 매우매우 많이 차지하고 있었다,,,

무려 1GB......

 

UIGraphicsBeginImageContext 와 UIGraphicsImageRenderer 

두가지 방법이 존재하던데 신식 방법인 UIGraphicsImageRenderer를 사용했다

UIGraphicsimagerenderer

extension UIImage {
    func resize(newWidth: CGFloat) -> UIImage {
        let scale = newWidth / self.size.width
        let newHeight = self.size.height * scale

        let size = CGSize(width: newWidth, height: newHeight)
        let render = UIGraphicsImageRenderer(size: size)
        let renderImage = render.image { context in
            self.draw(in: CGRect(origin: .zero, size: size))
        }
        return renderImage
    }
}

비율은 유지하고 줄이기 위해 width만 받아서 비율을 계산하여 size를 정했다

95MB 로 감소

 

 

+ 추가로 Kingfisher와 함께 사용하기

self.kf.setImage(with: url, placeholder: placeHolderImage, options: [.requestModifier(modifier)]) { result in
    switch result {
    case .success(let imageResult):
        let resizedImage = imageResult.image.resize(newWidth: 150)
        self.image = resizedImage
        self.isHidden = false
    case .failure(_):
        self.image = UIImage.emptyProfile
        self.isHidden = false
    }
}

setImage CompletionHandler를 열어서 구성해둔 resize 메서드를 사용했다.

댓글
최근에 올라온 글
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함