<문제>
- UIImage객체를 downsampling 작업을 통해 메모리 사용량을 줄이는 작업을 하는 중, downsampling된 UIImage를 UIImageView에 렌더링 하면 이미지 방향이 원본과 다른 문제가 발생했다.
- 세로로 표현되어야 할 이미지가 downsampling 후 가로로 표현되었다.
<원인>
func downSample(scale: CGFloat) -> UIImage {
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: false, kCGImageSourceThumbnailMaxPixelSize: maxPixel ] as CFDictionary
let downSampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downSampleOptions)! // UIImage -> CGImage
let newImage = UIImage(cgImage: downSampledImage, scale: scale, orientation: self.imageOrientation) // CGImage -> UIImage
return newImage
}
downsampling 과정 중 UIImage -> CGImage로 변환하는데, 변환 중 일부의 경우 UIImage의 방향 정보가 손실된다. (https://stackoverflow.com/questions/28478293/losing-image-orientation-while-converting-an-image-to-cgimage)
<해결>
CGImage -> UIImage로 변환할 때 원본 이미지의 방향정보를 설정해준다.
let newImage = UIImage(cgImage: downSampledImage, scale: scale, orientation: self.imageOrientation)
'iOS > Swift' 카테고리의 다른 글
[iOS] Safe Area란? (0) | 2022.01.12 |
---|---|
[iOS] sqlite에 UIImage 저장 / 로딩하기 (0) | 2022.01.10 |
[iOS] UIImagePickerController에서 가져온 이미지에서 GPS 정보 파싱하기 (0) | 2021.12.25 |
[iOS] 함수형 언어 Swift - 일급 함수 (0) | 2021.12.22 |
[iOS] 프로토콜 (Protocol ) (0) | 2021.12.19 |