UIImage AsPNG and AsJPEG not working

I am using MonoTouch and I have UIImage (displayed in UIImageView and it looks good) and I am trying to convert it to NSData , but AsJPEG and AsPNG returns null . What could be the problem?

My code is as follows:

 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); } 
+4
source share
3 answers

AsJPEG returned null because the image size was too large (it was taken from the iPhone 5). After I reduced it by 2, it generates the data correctly.

+1
source

The AsJPEG method calls UIImageJPEGRepresentation , and its return value is documented as:

A data object containing JPEG data, or nil if there is a problem creating the data. This function can return zero if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.

Like many APIs on iOS (and OSX), where the exception is usually not used (and null used to report any error).

In any case, you should check your image sizes and properties - they may give you a hint that it does not translate into a JPEG bitmap.

In addition, since NSData can represent a very large amount of memory, you should try to limit its life, for example:

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

It looks like you are writing a file in the current application directory, this is read-only.

You should use:

var path = System.IO.Path.GetTempFilename();

or

var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "tmp.png");

Like on other platforms, and use the file there.

You can also use Environment.SpecialFolder.MyDocuments .

+1
source

All Articles