24
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]画像形式をNSDataと拡張子から判別する

Last updated at Posted at 2016-07-31

画像バイナリデータ(NSData)から画像形式を判別

//NSDataを拡張
extension NSData {
	func imageTypeForImageData() -> String? {
		var c = [UInt32](count: 1, repeatedValue: 0)
		self.getBytes(&c, length: 1)
		switch (c[0]) {
		case 0xFF:
			return "jpeg"
		case 0x89:
			return "png"
		case 0x47:
			return "gif"
		case 0x42:
			return "bmp"
		default:
			return nil
		}
	}
}

画像ファイル名の拡張子から画像形式を判別

//NSURLを拡張
extension NSURL {
	func imageTypeForExtention() -> String? {
		let ext = self.pathExtension!.lowercaseString
		switch ext {
		case ".jpg" , ".jpeg":
			return "jpeg"
		case ".png":
			return "png"
		case ".gif":
			return "gif"
		case ".bmp":
			return "bmp"
		default:
			return nil
		}
	}	
}

例:Alamofireでmimetypeを指定して画像アップロードする

// imageData:NSData?
// fileUrl:NSURL?
// image:UIImage
Alamofire.upload(
    .POST,
    "https://httpbin.org/post",
    multipartFormData: { multipartFormData in
      if let imageType = imageData?.imageTypeForImageData() {
          //バイナリから画像形式の判別
          multipartFormData.appendBodyPart(data: imageData!, name: "file", fileName: "IMG."+imageType, mimeType: "image/"+imageType)
      } else if let imageType = fileUrl?.imageTypeForExtention() {
          //拡張子から画像形式の判別
          multipartFormData.appendBodyPart(data: imageData!, name: "file", fileName: "IMG."+imageType, mimeType: "image/"+imageType)
      } else {
          // 判別できないものはJPEG形式の画像フォーマットとしてNSDataに変換
          let data:NSData = UIImageJPEGRepresentation(image , 1.0)!
          multipartFormData.appendBodyPart(data: data, name: "file", fileName: "IMG.jpg", mimeType: "image/jpeg")
      }
    },
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    }
)

参考

Finding image type from NSData or UIImage
Path extension and MIME type of file in swift
Alamofire

24
20
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
24
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?