convert UIImage to NSData and back to UIImage

前端 未结 5 1467
难免孤独
难免孤独 2020-12-31 15:13

I have to populate table cell from database and images are on device. I\'ve to store that image in imageDataObject, how to convert that UIImage to

5条回答
  •  迷失自我
    2020-12-31 15:32

    Convert Data from Image:

    Try JPEG or PNG representation depending on your image format:

    UIImageJPEGRepresentation

    Returns the data for the specified image in JPEG format.

    NSData * UIImageJPEGRepresentation (
       UIImage *image,
       CGFloat compressionQuality
    );
    

    UIImagePNGRepresentation

    Returns the data for the specified image in PNG format

    NSData * UIImagePNGRepresentation (
       UIImage *image
    );
    

    Example:

    extension UIImage {
    
        var pngRepresentationData: Data? {
            return UIImagePNGRepresentation(img)
        }
    
        var jpegRepresentationData: Data? {
            return UIImageJPEGRepresentation(self, 1.0)
        }
    }
    

    Use:

    let data = myImage.jpegRepresentationData
    let data1 = myImage.pngRepresentationData
    

    Convert Image from Data:

    let image = UIImage(data: data)
    

提交回复
热议问题