質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Core Data

Core DataはAppleのOS X and iOSのためのオブジェクトモデリングと持続性を持ったフレームワークです。Xcodeはエンティティー、属性そして関係性を特定するためのオブジェクトモデルの編集機能を提供します。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1274閲覧

【Swift】CoreDataから読み込んだ画像の向きの制御方法

sai0001

総合スコア9

Core Data

Core DataはAppleのOS X and iOSのためのオブジェクトモデリングと持続性を持ったフレームワークです。Xcodeはエンティティー、属性そして関係性を特定するためのオブジェクトモデルの編集機能を提供します。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/10/19 04:54

編集2021/02/24 02:18

前提・実現したいこと

SwiftでCoreDataに保存した画像を、撮影したカメラの向きのままImageViewに表示したいです。

発生している問題

画像をImageVIewに表示する際に、カメラ縦向きで保存された画像が左に90度回転してしまいます。
横向きの画像は横のまま表示されます。

###わからないこと
下記の通り、調べられる限りの方法を試しましたが解決できませんでした。使い方が間違っているのか、別の方法があるのかをご教授いただければと思います。

該当のソースコード

Swift

1import UIKit 2import CoreData 3 4class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate { 5 6 @IBOutlet weak var imageView: UIImageView! 7 @IBAction func actionSheet(_ sender: UIButton) { 8 9 let actionSheet = UIAlertController(title: "", message: "画像を選んでください", preferredStyle: UIAlertController.Style.actionSheet) 10 11 let tappedCamera = UIAlertAction(title: "カメラで撮影する", style: UIAlertAction.Style.default, handler: {(action: UIAlertAction!) in self.takePhotos() 12 }) 13 14 let tappedLibrary = UIAlertAction(title: "ライブラリから選択する", style: UIAlertAction.Style.default, handler: {(action: UIAlertAction!) in self.choosePhotos() 15 }) 16 17 let cancel = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler: {(action: UIAlertAction!) in print("キャンセル") 18 }) 19 20 actionSheet.addAction(tappedCamera) 21 actionSheet.addAction(tappedLibrary) 22 actionSheet.addAction(cancel) 23 24 present(actionSheet, animated: true, completion: nil) 25 } 26 27 func takePhotos() { 28 //画像の取得方法を設定 29 let camera = UIImagePickerController.SourceType.camera 30 31 if UIImagePickerController.isSourceTypeAvailable(camera){ 32 let picker = UIImagePickerController() 33 picker.sourceType = camera 34 picker.delegate = self 35 self.present(picker, animated: true, completion: nil) 36 } 37 } 38 39 func choosePhotos() { 40 let photoPick = UIImagePickerController() 41 photoPick.sourceType = .photoLibrary 42 photoPick.delegate = self 43 self.present(photoPick, animated: true, completion: nil) 44 } 45 46 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){ 47 48 let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage 49 self.imageView.image = image 50 51 //画像の保存 52 let photoCore = Photo(context: self.conText) 53 let imageData = UIImage.pngData(image) 54 photoCore.picture = imageData() 55 (UIApplication.shared.delegate as! AppDelegate).saveContext() 56 57 self.dismiss(animated: true, completion: nil) 58 } 59 60 var photo01:[Photo] = [] 61 var conText = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 62 63 override func viewDidLoad() { 64 super.viewDidLoad() 65 // Do any additional setup after loading the view. 66 67 //保存した画像の取り出し 68 let fetchRequest = NSFetchRequest<Photo>(entityName: "Photo") 69 do{ 70 photo01 = try conText.fetch(fetchRequest) 71 let image = photo01.last?.picture 72 73 if let validImage = image { 74 let imageData = UIImage(data: validImage) 75 self.imageView.image = imageData?.fixedOrientation() 76 }else{ 77 //処理なし 78 } 79 80 }catch{ 81 print(error) 82 } 83 } 84 85} 86 87//画像の向きを制御 88extension UIImage{ 89 func reSizeImage(size: CGSize) -> UIImage?{ 90 91 UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) 92 self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) 93 guard let image = UIGraphicsGetImageFromCurrentImageContext() else { 94 return nil 95 } 96 UIGraphicsEndImageContext() 97 98 let originalWidth = image.size.width 99 let originalHeight = image.size.height 100 101 var resizeWidth: CGFloat = 0 102 var resizeHeight: CGFloat = 0 103 104 if(originalWidth <= originalHeight){ 105 resizeWidth = size.width 106 resizeHeight = size.height 107 }else{ 108 resizeHeight = size.height 109 resizeWidth = originalWidth * resizeHeight / originalHeight 110 } 111 112 let resizeSize = CGSize(width: resizeWidth, height: resizeHeight) 113 UIGraphicsBeginImageContext(resizeSize) 114 115 image.draw(in: CGRect(x: 0, y: 0, width: resizeWidth, height: resizeHeight)) 116 117 let resizeImage = UIGraphicsGetImageFromCurrentImageContext() 118 UIGraphicsEndImageContext() 119 120 let cropRect = CGRect(x: (resizeWidth - size.width) / 2, y: (resizeHeight - size.height) / 2, width: size.width, height: size.height) 121 122 if let cropRef = resizeImage?.cgImage{ 123 if(resizeWidth > resizeHeight){ 124 cropRef.cropping(to: cropRect) 125 let cropImage = UIImage(cgImage: cropRef, scale: 0, orientation: .right) 126 return cropImage 127 }else{ 128 cropRef.cropping(to: cropRect) 129 let cropImage = UIImage(cgImage: cropRef) 130 return cropImage 131 } 132 }else{ 133 print("error") 134 return nil 135 } 136 } 137 138} 139

試したこと

・保存した画像を読み込む際にリサイズする方法を試しました。【swift】カメラで撮影した画像を用いた時に向きがを参考にしましたが、変化なしでした。

・上記コードのようにリサイズした画像の縦横を比べて、右に90度回転させる処理を考えました。しかし、横向きの画像も回転してしまうことに気づき、なしとしました。

GitHubのコードがいくつかのサイトで使われていたので試しましたが、画像のorientationは.upになっているようで、変化なしでした。

補足情報(FW/ツールのバージョンなど)

Swift: version 5.1
Xcode: Version 11.1
Mac OS: Mojave 10.14.6

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

MasakiHori

2019/10/25 06:44

pngに変換するときにメタデータが吹き飛んでるような気がします。(向きがメタデータに入っている) 保存を行う前にreSizeImage(size:)と同じ方法でサイズと向きを変えずにContext上にUIImageを描画してUIImageを再生成してやるとうまくいく気がします。
sai0001

2019/10/25 11:34

MasakiHori様 コメントいただきありがとうございます。 ご指摘いただいた方法を試させていただきます。
sai0001

2019/10/27 05:45

MasakiHori様 実現したいことを達成することができました。 コメントいただきありがとうございました。 次回も質問の際は、ご指導いただけると幸いです。
guest

回答1

0

自己解決

解決しましたので、変更点を載せます。
width、heightは任意の値です。

【変更前】
let imageData = UIImage.pngData(image)

【変更後】
let imageData = UIImage.pngData(image.reSizeImage(size: CGSize(width: 500, height: 500))!)

以下、全コードになります。

Swift

1import UIKit 2import CoreData 3 4class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 5 6 @IBOutlet weak var imageView: UIImageView! 7 @IBAction func actionSheet(_ sender: UIBarButtonItem) { 8 let actionSheet = UIAlertController(title: "", message: "画像を選んでください", preferredStyle: UIAlertController.Style.actionSheet) 9 10 let tappedCamera = UIAlertAction(title: "カメラで撮影する", style: UIAlertAction.Style.default, handler: {(action: UIAlertAction!) in self.takePhotos() 11 }) 12 13 let tappedLibrary = UIAlertAction(title: "ライブラリから選択する", style: UIAlertAction.Style.default, handler: {(action: UIAlertAction!) in self.choosePhotos() 14 }) 15 16 let cancel = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler: {(action: UIAlertAction!) in print("キャンセル") 17 }) 18 19 actionSheet.addAction(tappedCamera) 20 actionSheet.addAction(tappedLibrary) 21 actionSheet.addAction(cancel) 22 23 present(actionSheet, animated: true, completion: nil) 24 } 25 26 func takePhotos() { 27 let camera = UIImagePickerController.SourceType.camera 28 29 if UIImagePickerController.isSourceTypeAvailable(camera){ 30 let picker = UIImagePickerController() 31 picker.sourceType = camera 32 picker.delegate = self 33 self.present(picker, animated: true, completion: nil) 34 } 35 } 36 37 var photo01:[Photo] = [] 38 var conText = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 39 40 func choosePhotos() { 41 let photoPick = UIImagePickerController() 42 photoPick.sourceType = .photoLibrary 43 photoPick.delegate = self 44 self.present(photoPick, animated: true, completion: nil) 45 } 46 47 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { 48 49 let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage 50 self.imageView.image = image 51 52 let photoCore = Photo(context: self.conText) 53 54     //変更点 55 let imageData = UIImage.pngData(image.reSizeImage(size: CGSize(width: 500, height: 500))!) 56 57 photoCore.picture = imageData() 58 (UIApplication.shared.delegate as! AppDelegate).saveContext() 59 self.dismiss(animated: true, completion: nil) 60 } 61 62 override func viewDidLoad() { 63 super.viewDidLoad() 64 // Do any additional setup after loading the view. 65 66 let fetchRequest = NSFetchRequest<Photo>(entityName: "Photo") 67 do{ 68 photo01 = try conText.fetch(fetchRequest) 69 let image = photo01.last?.picture 70 71 //画像が保存されていなければ表示処理をしない 72 if let validImage = image { 73 let imageData = UIImage(data: validImage) 74 self.imageView.image = imageData 75 }else{ 76 //処理なし 77 } 78 79 }catch{ 80 print(error) 81 } 82 } 83} 84 85//画像の向きを制御 86extension UIImage{ 87 func reSizeImage(size: CGSize) -> UIImage?{ 88 89 UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0) 90 self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) 91 guard let image = UIGraphicsGetImageFromCurrentImageContext() else { 92 return nil 93 } 94 UIGraphicsEndImageContext() 95 96 let originalWidth = image.size.width 97 let originalHeight = image.size.height 98 99 let resizeSize = CGSize(width: originalWidth, height: originalHeight) 100 UIGraphicsBeginImageContext(resizeSize) 101 102 image.draw(in: CGRect(x: 0, y: 0, width: originalWidth, height: originalHeight)) 103 104 let resizeImage = UIGraphicsGetImageFromCurrentImageContext() 105 UIGraphicsEndImageContext() 106 107 return resizeImage 108 } 109} 110

投稿2019/10/27 05:40

sai0001

総合スコア9

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問