我有其中有一个Image控件一个WPF应用程序。我试图将图像保存在控制一个SQL数据库。
在我的实体模型,图片列在我的数据库中的数据类型是一个byte[]
。所以,我发现一个System.Drawing.Image对象转换为一种方法byte[]
和背部。但是,我还没有发现从System.Windows.Controls.Image转换为一个方法byte[]
。
经过两部转换:
/// <summary>
/// 将System.Windows.Controls.Image 转byte[]
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static byte[] GetByteImage(System.Windows.Controls.Image img)
{
byte[] bt = null;
if (!img.Equals(null))
{
using (MemoryStream mostream = new MemoryStream())
{
Bitmap bmp = new Bitmap(GetBitmap(img));
bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图像以指定的格式存入缓存内存流
bt = new byte[mostream.Length];
mostream.Position = 0;//设置留的初始位置
mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
}
}
return bt;
}
/// <summary>
/// 将System.Windows.Controls.Image的BitmapSource转换为System.Drawing.Bitmap
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static System.Drawing.Bitmap GetBitmap(System.Windows.Controls.Image image)
{
System.Windows.Media.Imaging.BitmapSource transformedBitmapSource = image.Source as BitmapSource;
int width = transformedBitmapSource.PixelWidth;
int height = transformedBitmapSource.PixelHeight;
int stride = width * ((transformedBitmapSource.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
transformedBitmapSource.CopyPixels(bits, stride, 0);
unsafe
{
fixed (byte* pBits = bits)
{
IntPtr ptr = new IntPtr(pBits);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
width,
height,
stride,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
ptr);
return bitmap;
}
}
}
经过这两个方法就可以啦!
记住:要将项目的属性改为允许不安全代码。