WPF System.Windows.Controls.Image保存进数据库

我有其中有一个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;
                }
            }
        }
经过这两个方法就可以啦!

记住:要将项目的属性改为允许不安全代码。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值