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?)
代码:
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;
}
}
}
}
答案 0 :(得分:3)
wp7上的Silverlight没有JpegBitmapEncoder。如果要将BitmapSource转换为字节数组,可以使用WriteableBitmap的SaveJpeg方法执行此操作:
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;
}
如果你想将BitmapSource转换为png或gif等其他文件格式,你必须使用第三方库,如.NET image tools。
但在转换器中来回转换图像并不是一个好主意。我甚至认为你真的不需要。您使用什么控件来修改BitmapSource? :\