0

I want to convert an image to either

UIImagePNGRepresentation
UIImageJPEGRepresentation

however I do not know the file type. I've just got a URL with no extension. Is there anyway to save the image from the URL to the filesystem?

// 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])
}
fes
  • 2,465
  • 11
  • 40
  • 56

2 Answers2

4

Get the imageData from URL and then check the image type as below from that data object

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

After checking above you can store the image with selected extension

For getting extension from data you can check from here also

Community
  • 1
  • 1
Vandit Mehta
  • 2,572
  • 26
  • 41
  • Please add proper attribution if code from other answers: http://stackoverflow.com/a/5042365/1187415, http://stackoverflow.com/a/40317201/1187415. – Martin R Mar 29 '17 at 10:05
  • if you taken the code from another place please mention in your answer, – Anbu.Karthik Mar 29 '17 at 10:12
0

Use that method to check the extension of your image by using the NSData of your image.

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
}
handiansom
  • 783
  • 11
  • 27
  • That is Objective-C, not Swift. And it looks like a verbatim copy of http://stackoverflow.com/a/5042365/1187415, without attribution. – Martin R Mar 29 '17 at 10:00