Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

ios - 快速获取图像文件类型(Get image file type programmatically in swift)

I am downloading images from parse with file totes PNG and JPEG.

(我正在从解析器下载带有文件手提包PNG和JPEG的图像。)

When image is downloaded to the app I need to determine what the file type is so I can handle image accordingly.

(将图像下载到应用程序后,我需要确定文件类型是什么,以便可以相应地处理图像。)

Had a look at API for uiimageview and did a search but can't find any solution in swift.

(看过uiimageview的API并进行了搜索,但没有迅速找到任何解决方案。)

Any input appreciated

(任何输入表示赞赏)

Trying to get url from PFFIle §:

(尝试从PFFIle§获取网址:)

let imageURLFromParse = NSURL(string : caseImageFile2.url);

// Error here: 'NSURL?' does not have a member named 'pathExtension'                   
if(imageURLFromParse.pathExtension!.lowercaseString == ".jpg" || imageURLFromParse.pathExtension.lowercaseString == ".jpeg"){

  println("Parse image ext is a jpg: (imageURLFromParse.pathExtension.lowercaseString)");

  fileExtenion = ".jpg";

} else {                        
  println("Parse image is a png: (imageURLFromParse.pathExtension.lowercaseString)");

  fileExtenion = ".png";                           
}
  ask by dancingbush translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update for Swift 3.0.2

(Swift 3.0.2更新)

Based on Hoa's answer and Kingfisher library

(基于Hoa的答案和Kingfisher库)

import UIKit
import ImageIO

struct ImageHeaderData{
    static var PNG: [UInt8] = [0x89]
    static var JPEG: [UInt8] = [0xFF]
    static var GIF: [UInt8] = [0x47]
    static var TIFF_01: [UInt8] = [0x49]
    static var TIFF_02: [UInt8] = [0x4D]
}

enum ImageFormat{
    case Unknown, PNG, JPEG, GIF, TIFF
}


extension NSData{
    var imageFormat: ImageFormat{
        var buffer = [UInt8](repeating: 0, count: 1)
        self.getBytes(&buffer, range: NSRange(location: 0,length: 1))
        if buffer == ImageHeaderData.PNG
        {
            return .PNG
        } else if buffer == ImageHeaderData.JPEG
        {
            return .JPEG
        } else if buffer == ImageHeaderData.GIF
        {
            return .GIF
        } else if buffer == ImageHeaderData.TIFF_01 || buffer == ImageHeaderData.TIFF_02{
            return .TIFF
        } else{
            return .Unknown
        }
    }
}

Usage

(用法)

let imageURLFromParse = NSURL(string : "https://i.stack.imgur.com/R64uj.jpg")
let imageData = NSData(contentsOf: imageURLFromParse! as URL)
print(imageData!.imageFormat)

You can use this with Both local and online images.

(您可以将其与本地和在线图像一起使用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...