我正在使用 MonoTouch,我有一个 UIImage
(显示在 UIImageView
中,看起来不错),我正在尝试将其转换为 NSData
,但 AsJPEG
和 AsPNG
返回 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/