无法使用 UIImage 形成 NSData

unable to form NSData using UIImage

我有一个 UIImage,我想从中制作 NSData,然后保存到文件中。

问题是我能够生成 UIImage,但是当将它传递给 NSData 时,我得到的是 nil 值。 UIImagePNGRepresentationUIImageJPEGRepresentation

我都试过了

这是我的代码,经过详细调试:

UIImage *img  = [self.mImagesArray objectAtIndex:index];
NSData *imageData = UIImagePNGRepresentation(img);  //nil
NSData *imgData2 = UIImageJPEGRepresentation(img, 50); //nil  i tried chaning 50 to 0.5 it also not working
[imageData writeToFile:imagePath atomically:YES];

这是显示我正在获取 UIImage 但无法形成的图像 NSData:

编辑

I am getting image from UIImagePicker and adding it in Array:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

if (!self.mImagesArray)
    self.mImagesArray = [[NSMutableArray alloc] init];

[self.mImagesArray addObject:[info objectForKey:UIImagePickerControllerOriginalImage]];

}

来自文档 UIImagePNGRepresentation

Return Value A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.


你有 UIImage 但这并不能保证它有数据,例如

UIImage *img = [[UIImage alloc] init];
NSData *data = UIImagePNGRepresentation(img);

在这种情况下,您拥有非 nil UIImage 对象,但它不包含任何数据,因此它将 return nil NSData

试试这个。

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

这条线适合我。

UIImage *img  = [UIImage imageNamed:@"oval.png"];//[self.mImagesArray objectAtIndex:index];
NSData *imageData = UIImagePNGRepresentation(img);

所以,你的图片有问题。

UIImagePNGRepresentation 可能 return 如果图像没有 CGImageRef 或无效位图格式

请检查

首先检查您的索引,您在哪个索引处没有获得图像或没有得到图像。因为每次选择图像时,您都在为数组分配内存。所以首先在视图中分配数组是否加载或视图将根据需要出现。并尝试通过考虑这一点来调试您的代码。

希望对您有所帮助!!