Mobile Zone is brought to you in partnership with:

Den is a DZone Zone Leader and has posted 460 posts at DZone. You can read more from them at their website. View Full User Profile

Operating with image files in a Windows Phone 7 application

08.15.2010
| 18287 views |
  • submit to reddit

Images are one thing that is quite interesting to work with in a Windows Phone 7 application. In fact, for some specific applications manipulating image files can be a necessity (for example, when the application saves and loads edited photos).

As you probably already know, the files that are created by a Windows Phone 7 application are stored inside the isolated storage – a storage unit designated for the current application that no other application can access.

Unlike regular text files that can be read as plain string units, images are handled in a different way. Even if you used Silverlight before, opening image files in a Windows Phone 7 application will require you to use a different approach, since you won’t be directly in control of the storage space.

Basically, saving an image locally (for example, from a web site) is quite easy. If you’ve read my previous article on file handling , then I can say that the same principles are applied here.

To show an example, I am going to use a WebClient to download an image and store it locally.

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

I am referencing the OpenReadCompleted event handler that will be triggered when the data from the specified resource will be completely cached. Therefore, all I will have to do is store it for permanent access. Here is how the actual event handler looks like:

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var resInfo = new StreamResourceInfo(e.Result, null);
var reader = new StreamReader(resInfo.Stream);

byte[] contents;
using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
{
contents = bReader.ReadBytes((int)reader.BaseStream.Length);
}

IsolatedStorageFileStream stream = file.CreateFile("file.jpg");
stream.Write(contents, 0, contents.Length);
stream.Close();
}

This way, I am converting the downloaded stream to a byte array and I am storing it in the root folder as a JPEG image. The actual image download is triggered via OpenReadAsync:

client.OpenReadAsync(new Uri("http://www.google.com/images/srpr/nav_logo14.png"));

Here I am passing a sample image URL (feel free to change it to whatever image you want). So it is downloaded and stored. Now it’s time to read the contents.

To test this, I inserted an Image control on the page that will display the stored image. To retrieve the image, an instance of IsolatedStorageFileStream is used:

IsolatedStorageFileStream stream = new IsolatedStorageFileStream("filet.jpg", FileMode.Open, file);

var image = new BitmapImage();
image.SetSource(stream);

image1.Source = image;

Although the first thing that comes to mind would be using a relative URI for the image source, it will not work on a Windows Phone 7 application because the user has no direct control over the storage unit.

Comments

Jon Nowick replied on Tue, 2011/01/18 - 6:56pm

I saw this article and the one you wrote for flicker and I am trying to do something similar. From what I am seen you are the best person to provide help. Basically I have a rest webservice that is self hosted on a pc and I want to uload an image from a windows 7 phone. A lot of this is new to me so I have been learning as I go. My problem is that I can not upload an image to the webservice. Below is the code that I am using. Can you please tell me what I am doing wrong? I am testing with the wifi connection and it is up and working. I am using Fiddler and I can see the requests going to and from the phone/pc When I try to post I get a 400 response code back.

[ServiceContract]

public interface ItestService

{

[OperationContract, WebInvoke(Method = "POST", UriTemplate = "PostTest/{targetID}")]

string PostTargetPill(string targetID, Stream image);

}

//from service def

public string PostTargetPill(string targetID, System.IO.Stream image)

{

string id = WriteImageToDisk(image, targetID);

return id;

}

//phone code

private void SendImage1()

{

string address = ServiceURI + "/PostTest";

Uri baseAddress = new Uri(address);

var req = HttpWebRequest.Create(baseAddress) as HttpWebRequest;

req.Method = "POST";

req.ContentType = "image/jpeg";

req.BeginGetRequestStream(SendImagePost_Callback, req);

}

private void SendImagePost_Callback(IAsyncResult result)

{

try

{

var req = result.AsyncState as HttpWebRequest;

using (var strm = req.EndGetRequestStream(result))

{

var bytesToWrite = RawContent();

strm.Write(bytesToWrite, 0, bytesToWrite.Length);

strm.Flush();

}

req.BeginGetResponse(SendImageResponce_Callback, req);

}

catch (Exception ex)

{

DisplayMessage(this.txtError, ex.Message);

}

}

private void SendImageResponce_Callback(IAsyncResult result)

{

try

{

DisplayMessage(this.txtAction, "bob3");

var req = result.AsyncState as HttpWebRequest;

var strm = resp.GetResponseStream();

var reader = new StreamReader(strm);

DataContractSerializer ser = new DataContractSerializer(typeof(string));

string id = ser.ReadObject(strm).ToString();

DisplayMessage(this.txtAction, id);

}

catch (Exception ex)

{

DisplayMessage(this.txtError, ex.Message);

}

}

Kookee Gacho replied on Sat, 2012/07/07 - 11:38pm

A minor update released in 2012 known as "Tango", along with other bugfixes, would also lower the hardware requirements to allow for devices with 800 MHz CPUs and 256 MB of RAM to run Windows Phone. -FXDD

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.