在swift中以编程方式获取图像文件类型 [英] Get image file type programmatically in swift
本文介绍了在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获取网址§:
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的回答和翠鸟图书馆
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.
这篇关于在swift中以编程方式获取图像文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文