[Swift] Image Resize

PHOTO EMBED

Thu Mar 24 2022 01:42:37 GMT+0000 (Coordinated Universal Time)

Saved by @hsleedevelop

// 원하는 해상도에 맞게 조절
func downSample1(scale: CGFloat) -> UIImage {
    let imageSourceOption = [kCGImageSourceShouldCache: false] as CFDictionary
    let data = self.pngData()! as CFData
    let imageSource = CGImageSourceCreateWithData(data, nil)!
    let maxPixel = max(self.size.width, self.size.height) * scale
    let downSampleOptions = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceShouldCacheImmediately: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maxPixel
    ] as CFDictionary

    let downSampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downSampleOptions)!

    let newImage = UIImage(cgImage: downSampledImage)
    printDataSize(newImage)
    return newImage
}


// 이미지뷰 크기에 맞게 조절
func downSample2(size: CGSize, scale: CGFloat = UIScreen.main.scale) -> UIImage {
    let imageSourceOption = [kCGImageSourceShouldCache: false] as CFDictionary
    let data = self.pngData()! as CFData
    let imageSource = CGImageSourceCreateWithData(data, imageSourceOption)!

    let maxPixel = max(size.width, size.height) * scale
    let downSampleOptions = [
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceShouldCacheImmediately: true,
        kCGImageSourceCreateThumbnailWithTransform: true,
        kCGImageSourceThumbnailMaxPixelSize: maxPixel
    ] as CFDictionary

    let downSampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downSampleOptions)!

    let newImage = UIImage(cgImage: downSampledImage)
    printDataSize(newImage)
    return newImage
}
content_copyCOPY

https://nsios.tistory.com/154?category