LoginSignup
22
15

More than 5 years have passed since last update.

UIImageJPEGRepresentationを使う際の注意点

Posted at

はじめに

画像サイズが一定以上の際は、リサイズしてサーバーにアップロードするという仕様がありました。しかし、リサイズしていない画像をサーバーにアップロードした際に、iPhone上でのデータサイズよりもサーバーにアップロードしたデータサイズが大きくなってしまうという現象に遭遇しました。

実際に

H:512px W:320pxの下記の画像をUIImageJPEGRepresentationNSDataに変換したいと思います。
wallpaper.jpg

もともとのサイズは34KBになります。

Playgound上で上記の画像を10.750.50.25compressionQualityNSDataにしていきます。

//: Playground - noun: a place where people can play

import UIKit

let image = UIImage(named: "wallpaper.jpg")!

let fileManager = NSFileManager.defaultManager()
let documentPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

var isDirectory: ObjCBool = false
if !fileManager.fileExistsAtPath("\(documentPath)/Images", isDirectory: &isDirectory) {
    try! fileManager.createDirectoryAtPath("\(documentPath)/Images", withIntermediateDirectories: true, attributes: nil)
}

let maxQualityImageData = UIImageJPEGRepresentation(image, 1)
fileManager.createFileAtPath("\(documentPath)/Images/maxQualityImage.jpg", contents: maxQualityImageData, attributes: nil)
// 123KBになる

let threeQuartersQualityImageData = UIImageJPEGRepresentation(image, 0.75)
fileManager.createFileAtPath("\(documentPath)/Images/threeQuartersQualityImage.jpg", contents: threeQuartersQualityImageData, attributes: nil)
// 46KBになる

let halfQualityImageData = UIImageJPEGRepresentation(image, 0.5)
fileManager.createFileAtPath("\(documentPath)/Images/halfQualityImage.jpg", contents: halfQualityImageData, attributes: nil)
// 30KBになる

let quarterQualityImageData = UIImageJPEGRepresentation(image, 0.25)
fileManager.createFileAtPath("\(documentPath)/Images/quarterQualityImage.jpg", contents: quarterQualityImageData, attributes: nil)
// 13KBになる

最後に

10.750.50.25で指定していくので一瞬倍率に見えてしまうのですが、11倍ではなくて、クオリティが最大になります。

どの程度のクオリティで出力するかはデザイナーの方と実際に圧縮率の違う出力された画像を比較して、決めるのが良いかもしれません。

22
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
15