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.
Asked
Active
Viewed 7.6k times
60

Alireza Fallah
- 4,609
- 3
- 31
- 57

BlueDolphin
- 9,765
- 20
- 59
- 74
5 Answers
106
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];

Ajay Kumar
- 1,807
- 18
- 27

b123400
- 6,138
- 4
- 27
- 27
44
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."

logancautrell
- 8,762
- 3
- 39
- 50

Noah Witherspoon
- 57,021
- 16
- 130
- 131
-
Yes, that's what I am using. The NSData has address, while after call UIImaeg -initWithData:theData, the point become 0. I am not sure where to see the error message. – BlueDolphin Nov 03 '08 at 00:24
21
Try this to convert an image to NSdata:
UIImage *img = [UIImage imageNamed:@"image.png"];
NSData *data1 = UIImagePNGRepresentation(img);

Mundi
- 79,884
- 17
- 117
- 140
-1
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...
}
}

Krunal
- 77,632
- 48
- 245
- 261