iOS/Swift

[iOS] UIImage -> CGImage 변환시 이미지 방향이 변하지 않게 하기

2022. 1. 9. 22:23
목차
  1. <문제>
  2. <원인>
  3. <해결>

<문제>

- 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
  1. <문제>
  2. <원인>
  3. <해결>
'iOS/Swift' 카테고리의 다른 글
  • [iOS] Safe Area란?
  • [iOS] sqlite에 UIImage 저장 / 로딩하기
  • [iOS] UIImagePickerController에서 가져온 이미지에서 GPS 정보 파싱하기
  • [iOS] 함수형 언어 Swift - 일급 함수
듀IT
듀IT
듀IT
듀 IT
듀IT
전체
오늘
어제
  • 분류 전체보기 (55)
    • iOS (50)
      • iOS 앱 개발 올인원 패키지 Online (34)
      • Swift (16)
    • 자격증 (0)
      • 정보처리기사 (0)
    • 컴퓨터공학 (4)
      • 운영체제 (3)
      • 네트워크 (1)
    • 프로젝트 (1)
      • 환경설정 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • ios
  • enum
  • Convenience
  • swift
  • 구조체
  • 직장인자기계발
  • 패스트캠퍼스후기
  • 패캠챌린지
  • UITableView
  • 생성자
  • UIImage
  • closure
  • 패스트캠퍼스
  • structure
  • iOS 앱 개발 올인원 패키지 Online
  • 직장인인강
  • 열거형
  • Optional
  • ViewController
  • 상속

최근 댓글

최근 글

hELLO · Designed By 정상우.
듀IT
[iOS] UIImage -> CGImage 변환시 이미지 방향이 변하지 않게 하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.