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.
这篇关于以编程方式快速获取图像文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式快速获取图像文件类型
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01