Thursday, August 29, 2013

Shrinking an image in iOS with Xamarin.iOS and C#

Images taken with the camera are rather large in the iPhone.  How do you shrink them down?  I need to shrink them because I am going to send them to a web service and I want to spend as little time as possible in the upload process.  While I am not sure that this is the best code, it seems to be working for me.  I want to put this out for sharing and if you have a suggestion on how to make it better, please let me know.
                UIImage img = UIImage.FromFile (fileName);
                var width = img.Size.Width;
                var height = img.Size.Height;
                var newWidth = defaultImageWidth;
                var newHeigth = height * newWidth / width; // I always hope I get this scaling thing right. #crossedfingers
                UIGraphics.BeginImageContext (new SizeF (newWidth, newHeigth));
                img.Draw (new RectangleF (0, 0, newWidth, newHeigth));
                img = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext ();
  

No comments: