Search code examples
c#silverlightwindows-phone-7

Compiler can't find the class JpegBitmapEncoder in WP7


i'm losing it, what am i doing wrong ?

Error 3 The name 'BitmapFrame' does not exist in the current context

Error 2 The type or namespace name 'JpegBitmapEncoder' could not be found (are you missing a using directive or an assembly reference?)

Code:

namespace Microsoft.Samples.CRUDSqlAzure.Phone.Converters
{
using System;
using System.Windows.Data;
using System.IO;
using System.Windows.Media.Imaging;

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        byte[] rawImageBytes = (byte[])value;
        BitmapImage imageSource = null;

        try
        {
            using (MemoryStream stream = new MemoryStream(rawImageBytes))
            {
                stream.Seek(0, SeekOrigin.Begin);
                BitmapImage b = new BitmapImage();
                b.SetSource(stream);
                imageSource = b;
            }
            return imageSource;
        }
        catch 
        {
            return null;
        }


    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            BitmapImage bitmapImage = (BitmapImage)value;
            byte[] data;
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                data = ms.ToArray();
            }
            return data;

        }
        catch
        {
            return null;
        }
    }
}

}


Solution

  • Silverlight on wp7 doesn't have JpegBitmapEncoder. If you want to convert a BitmapSource to a byte array you can do that using the WriteableBitmap's SaveJpeg method:

    try
    {
        BitmapImage bitmapImage = (BitmapImage)value;
        byte[] data;
        WriteableBitmap wb = new WriteableBitmap(bitmapImage);
        using (MemoryStream ms = new MemoryStream())
        {
            wb.SaveJpeg(ms, bitmapImage.PixelHeight, bitmapImage.PixelWidth, 0, 100);
            data = ms.ToArray();
        }
        return data;
    }
    catch
    {
        return null;
    }
    

    If you want to convert the BitmapSource to other file format like png or gif you have to use third party libraries like .NET image tools.

    But it's not a good idea to convert images back and forth in a converter. I don't even think you really need to. What control do you use which modifies the BitmapSource? :\