以编程方式快速获取图像文件类型

Get image file type programmatically in swift(以编程方式快速获取图像文件类型)

本文介绍了以编程方式快速获取图像文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从带有 PNG 和 JPEG 文件的解析器中下载图像.

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

当图像下载到应用程序时,我需要确定文件类型,以便我可以相应地处理图像.

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

查看了 uiimageview 的 API 并进行了搜索,但在 swift 中找不到任何解决方案.

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

任何意见表示赞赏

试图从 PFFIle 获取 url §:

Trying to get url from 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";                           
}

推荐答案

更新 Swift 3.0.2

Update for Swift 3.0.2

基于 Hoa 的回答和 Kingfisher 库

Based on Hoa's answer and Kingfisher library

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
        }
    }
}

用法

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.

这篇关于以编程方式快速获取图像文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:以编程方式快速获取图像文件类型

基础教程推荐