Problems turning an image file within the solution into a MemoryStream


  • I have a solution that uses a shared class library project, and I want to be able to "push" an image from the solution into the class library in order that the shared class will have access to the image file.

    The image file is part of my solution, but I am having issues getting it to work.  When I debug the code, the pixel height and width of the image are always empty.  Therefore, if I try to convert to a byte array or memory stream, I get a nullreferenceexception

    I dropped the control from the shared library temporarily into the solution, and it will work fine if I just pass the path to the control then create the image there.  Like this:

    BitmapImage Picture = new BitmapImage(new Uri(ImagePath, UriKind.RelativeOrAbsolute));

    But if I try to create an image within the solution: as an Image, byte[], or MemoryStream, they are always empty.  I also tried this approach:

    var myfile = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(imgpath));

    but got an exception as follows:

    File operation not permitted. Access to path '../Assets/person_m.png' is denied.

    If I try using an absolute path rather than relative, nothing will work - not even passing an ImagePath.

    Can someone point me in the right direction?  I have had no luck googling or on other forums

    Wednesday, April 18, 2012 11:19 AM


  • I worked out a solution that works for me, as follows:

    var uri = new Uri(imgpath, UriKind.Relative);
                var streamInfo = System.Windows.Application.GetResourceStream(uri);
                var stream = streamInfo.Stream;
                byte[] bytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(bytes, 0, (int)stream.Length);
                return new MemoryStream(bytes);

    The imgpath variable is simply the path to the image that you are using; for this problem the image was already part of the Visual Studio solution, so the imgpath would look something like this:


    Hopefully this can be of use to someone else! Smile

    Monday, April 23, 2012 6:30 AM