我想将图像转换为
UIImagePNGRepresentation
UIImageJPEGRepresentation
但是我不知道文件类型。我刚得到一个没有扩展名的 URL。有没有办法将图像从 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])
}
最佳答案
从 URL 中获取图像数据,然后从该数据对象中检查图像类型,如下所示
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
}
}
objective-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 查看还有
关于ios - UIImage 作为表示但没有文件扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090043/