ssk
ssk

Reputation: 9265

Windows Phone read image and pixel values

I am trying to read an image (.png/jpg) from the storage and get pixel values on my Windows Phone 8 app:

    private static BitmapImage LoadBitmap(string iFilename)
    {
        var imgUri = new Uri(iFilename, UriKind.Relative);
        var image = new BitmapImage { CreateOptions = BitmapCreateOptions.None, UriSource = imgUri };

        return image;
    }

    public static string GetColorAttribute(string iFilename)
    {
        // Get Bitmap Image
        var image = LoadBitmap(iFilename);
        var wbmp = new WriteableBitmap(image);
    }

I get an exception on executing:

var wbmp = new WriteableBitmap(image);

{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'MyProject' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.

Are there examples for working with images on Windows Phone 8?

Upvotes: 1

Views: 916

Answers (1)

Olivier Payen
Olivier Payen

Reputation: 15268

You should use the SetSource method of the BitmapImage class:

private static WriteableBitmap LoadBitmap(string iFilename)
{
    using (var stream = Application.GetResourceStream(new Uri(iFilename, UriKind.Relative)).Stream)
    {
        var bmpi = new BitmapImage();
        bmpi.SetSource(stream);
        bmpi.CreateOptions = BitmapCreateOptions.None;
        WriteableBitmap bmp = new WriteableBitmap(bmpi);
        bmpi.UriSource = null;
        return bmp;
    }
}

public static void GetColorAttribute(string iFilename)
{
    // Get Bitmap Image
    var wbmp = LoadBitmap(iFilename);
}

Here is an article that explains how to load images on Windows Phone (the article was written for Windows Phone 7 but it didn't change with WP8): Image Tips for Windows Phone

Upvotes: 2

Related Questions