NSData and UIImage

2019-01-21 12:20发布

I am trying to load UIImage object from NSData, and the sample code was to NSImage, I guess they should be the same. But just now loading the image, I am wondering what's the best to troubleshoot the UIImage loading NSData issue.

5条回答
Animai°情兽
2楼-- · 2019-01-21 12:45

I didn't try UIImageJPEGRepresentation() before, but UIImagePNGRepresentation works fine for me, and conversion between NSData and UIImage is dead simple:

NSData *imageData = UIImagePNGRepresentation(image);
UIImage *image=[UIImage imageWithData:imageData];
查看更多
祖国的老花朵
3楼-- · 2019-01-21 12:48

For safe execution of code, use if-let block with Data, as function UIImagePNGRepresentation returns, optional value.

if let img = UIImage(named: "Hello.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3 class. Use Data instead of NSData with Swift 3

Generic image operations (like png & jpg both):

if let img = UIImage(named: "Hello.png") {
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(img)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "Hello.png") {
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}
查看更多
地球回转人心会变
4楼-- · 2019-01-21 12:59

theData should be a NSData object which already contains the data. You need to do the file loading/downloading to the NSData object before it is used. You can inspect it by using NSLog on theData and see if it contains the valid data.

查看更多
等我变得足够好
5楼-- · 2019-01-21 13:02

UIImage has an -initWithData: method. From the docs: "The data in the data parameter must be formatted to match the file format of one of the system’s supported image types."

查看更多
聊天终结者
6楼-- · 2019-01-21 13:06

Try this to convert an image to NSdata:

UIImage *img = [UIImage imageNamed:@"image.png"];
NSData *data1 = UIImagePNGRepresentation(img);
查看更多
登录 后发表回答