ProjetThe/ProjetTheAlone/Converter/BinaryImageConverter.cs

68 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;
//https://cromwellhaus.com/2007/07/binding-to-the-byte-of-an-image-in-wpf/
namespace ProjetTheAlone.Converter
{
public class BinaryImageConverter : IValueConverter
{
object IValueConverter.Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
if (value != null && value is byte?[])
{
byte?[] bytes = value as byte?[];
byte[] bb = Array.ConvertAll<byte?, byte>(bytes,
delegate (byte? b)
{
return b.Value;
});
MemoryStream stream = new MemoryStream(bb);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
return null;
}
object IValueConverter.ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
if (value != null)
{
byte?[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)value));
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
byte[] bb = ms.ToArray();
data = Array.ConvertAll<byte, byte?>(bb,
delegate (byte b)
{
return b;
});
return data;
}
}
return null;
}
}
}