views:

22

answers:

2

The System.Drawing.Image has the easy to use methods for FromFile and ToFile. What is the equivalent for the Silverlight BitmapImage? I am trying to load and save a jpeg image as part of a unit test. The bytes must match exactly for it to pass. Here is my current guess:

    //I am not sure this is right
    private BitmapImage GetImage(string fileName)
    {
        BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
        using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = imageStreamSource;
            bitmapImage.EndInit();
        }

        return bitmapImage;
    }

    private void SaveImage(BitmapImage bitmapImage, string file)
    {
        //How to do this?
    }
A: 

From MSDN link, use the ctor overload which takes in a URI or

BitmapImage myBitmapImage = new BitmapImage();

// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg");
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();

//set image source
myImage.Source = myBitmapImage;

To save the image to disk, you'd need the specific encoder e.g. JpegBitmapEncoder

Gishu
What is the DecodePixelWidth?
Greg Finzer
from the comment in the msdn code snippet (first link) "To save significant application memory, set the DecodePixelWidth or DecodePixelHeight of the BitmapImage value of the image source to the desired height and width of the rendered image. If you don't do this, the application will cache the image as though it were rendered as its normal size rather then just the size that is displayed."
Gishu
A: 

An in-browser Silverlight application cannot open a file using a filename. You would need it run out-of-browser with elevated trust to do that.

Silverlight has no built-in image encoding so you can't take the contents of a bitmap (BTW you would need to be using WriteableBitmap to be able to access the raw image).

You find something you need in Image Tools.

AnthonyWJones