Caching images on iOS4

Posted by acidjunk on March 9, 2011

Saving and caching images in the iphone app sandbox can be done in a number of ways

UIImage to array:

public byte[] ByteArrayFromUIImage(UIImage image)
	{
		NSData imageData = image.AsJPEG();
		image.Dispose();
		image = null;
		Byte[] retVal = new Byte[imageData.Length];
		System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, retVal, 0, Convert.ToInt32(imageData.Length));
		imageData.Dispose();
		imageData = null;
		return retVal;
	}

URL to UIImage->

UIImage image =  UIImage.LoadFromData(NSData.FromUrl(new NSUrl("http://www.example.com/image.jpg")));

Saving:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
string filePath = Path.Combine(path, tu.ImgUrl);
System.IO.File.WriteAllBytes(path, ByteArrayFromUIImage(uiImage));

If you need it for many pics you could use a sqlite DB as an backend; so far I only needed to save one pic.