ios - UIImage AsPNG 和 AsJPEG 失败

标签 ios uiimage nsdata xamarin.ios

我正在使用 MonoTouch,我有一个 UIImage(显示在 UIImageView 中,看起来不错),我正在尝试将其转换为 NSData ,但 AsJPEGAsPNG 返回 null。可能是什么问题?

我的代码是这样的:

NSError err;
NSData imageData = CroppedImageView.Image.AsJPEG(); // imageData is null!

if (!imageData.Save ("tmp.png", true, out err)) {
  Console.WriteLine("Saving of file failed: " + err.Description);
}

最佳答案

AsJPEG 方法调用UIImageJPEGRepresentation 返回值为documented作为:

A data object containing the JPEG 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.

这类似于 iOS(和 OSX)中的许多 API,其中异常不常用(null 用于报告某种错误)。

无论如何,您应该检查您的图像尺寸和属性 - 它们可能会提示您一些无法转换为 JPEG 位图的内容。

此外,由于 NSData 可以代表非常大量的内存,您应该尝试限制它的生命周期,例如:

using (NSData imageData = CroppedImageView.Image.AsJPEG ()) {
   NSError err;
   if (!imageData.Save ("tmp.jpg", true, out err)) {
      Console.WriteLine("Saving of file failed: " + err.Description);
   }
}

关于ios - UIImage AsPNG 和 AsJPEG 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15120589/

相关文章:

swift - 以错误的顺序解析到 collectionview 图像

iphone - 如何在 iPhone 应用程序中为 pdf 文件添加背景颜色

ios - 在 iOS 中使用 NSFileManager 写入文件

ios - 如何使用字符串数组将结构转换为 NSData,反之亦然 Swift

ios - Firebase 身份验证和 Swift : Check if email already in database

ios - UItextfield 不渲染背景颜色

ios - Swift:键值观察集合

ios - 将 GMSPanoramaView 转换为 UIImage?

objective-c - MD5没有为iOS中的在线文件提供正确的哈希

ios - Web 服务器响应失败后应用程序崩溃