我想将图片转换为
UIImagePNGRepresentation
UIImageJPEGRepresentation
但是我不知道文件类型。我刚刚获得了一个没有扩展名的网址。有没有将图像从URL保存到文件系统?
// got the data from the URL
let imageData = UIImage(data: data!)
// now I want to write to the filesystem but only way was with a representation as UIImage has no write
if let saveImageData = UIImageXXXXXXRepresentation(imageData!) {
try saveImageData.write(to: URL(fileURLWithPath: localFilename), options: [.atomic])
}
答案 0 :(得分:4)
从URL获取imageData,然后从该数据对象中检查下面的图像类型
Swift 3
let data: Data = UIImagePNGRepresentation(yourImage)!
extension Data {
var format: String {
let array = [UInt8](self)
let ext: String
switch (array[0]) {
case 0xFF:
ext = "jpg"
case 0x89:
ext = "png"
case 0x47:
ext = "gif"
case 0x49, 0x4D :
ext = "tiff"
default:
ext = "unknown"
}
return ext
}
}
目标C
+ (NSString *)contentTypeForImageData:(NSData *)data {
uint8_t c;
[data getBytes:&c length:1];
switch (c) {
case 0xFF:
return @"image/jpeg";
case 0x89:
return @"image/png";
case 0x47:
return @"image/gif";
case 0x49:
case 0x4D:
return @"image/tiff";
}
return nil;
}
上面检查后,您可以存储具有所选扩展名的图像
要从数据中获取扩展程序,您可以从here检查
答案 1 :(得分:0)
使用该方法通过使用图像的NSData检查图像的扩展名。
func contentTypeForImageData(data: NSData) -> String {
var c: UInt8
data.getBytes(c, length: 1)
switch c {
case 0xFF:
return "image/jpeg"
case 0x89:
return "image/png"
case 0x47:
return "image/gif"
case 0x49, 0x4D:
return "image/tiff"
}
return nil
}