推荐文章

Winform 全屏显示

Winform 全屏显示

Winform程序无边框、置顶、全屏显示
WPF之Image控件

WPF之Image控件

Image控件加载图片包括加载动态图片,加载静态图片两种方式。加载动态图片通过生成一个BitmapImage,创建该对象后,赋给Image的Source即可。加载的形式:BitmapImage myBitmapImage =new BitmapImage();myBitmapImage.BeginInit();取得数据库存储的图片字段,MSSQL的Image类型Byte[] mybyte = Re
wpf list<T>与ObservableCollection<T>的区别

wpf list<T>与ObservableCollection<T>的区别

List《T》与ObservableCollection《T》的用法基本上是一样的。区别:list《T》:当T继承于INotifyPropertyChanged时,如果list《T》中的属性发生改变,则通知UI属性值已发生改变。但当list《T》添加一项时,list《T》就无法通知前端UI了(此时,ObservableCollection《T》闪亮登场)。ObservableCollection《
WPF调用线程复制文件并显示进度条

WPF调用线程复制文件并显示进度条

在WPF中复制文件时,如何调用线程,显示进度条。《Window x:Class="WpfThreadTest.MainWindow"xmlns="http:schemas.microsoft.comwinfx2006xamlpresentation"xmlns:x="http:schemas.microsoft.comwinfx2006xaml"Title="MainWindow" Closed=
WPF中对XML的读写

WPF中对XML的读写

已知有一个XML文件(bookste.xml)如下:《?xmlversion="1.0" encoding="gb2312"?》《bookste》《bookgenre="fantasy" ISBN="236314"》《title》OberonsLegacy《title》《auth》Cets,Eva《auth》《price》5.95《price》《book》《bookste》 1、往《bookste

WPF将图片保存到数据库中、从数据库中读取图片

日期:2018-08-14 点击:1395 来源:PB2.CN

WPF将图片保存到数据库中、从数据库中读取图片


存储步骤:
1、搜索到图片的路径
2、读取图片并将图片转换成Base64String格式
3、sql语句保存到数据库中。
读取步骤:
1、sql读取出图片Base64String文本
2、Base64String转为BitmapImage
3、绑定到Image控件


图片转换类

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Xml;
namespace ImagesApp
{
    class ImagesHelper
    {
        /// <summary>
        /// 将字节数组进行压缩后返回压缩的字节数组
        /// </summary>
        /// <param name="data">需要压缩的数组</param>
        /// <returns>压缩后的数组</returns>
        public static byte[] Compress(byte[] data)
        {
            MemoryStream stream = new MemoryStream();
            GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
            gZipStream.Write(data, 0, data.Length);
            gZipStream.Close();
            return stream.ToArray();
        }

        /// <summary>
        /// 解压字符数组
        /// </summary>
        /// <param name="data">压缩的数组</param>
        /// <returns>解压后的数组</returns>
        public static byte[] Decompress(byte[] bytes)
        {
            using (MemoryStream tempMs = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);
                    Decompress.CopyTo(tempMs);
                    Decompress.Close();
                    return tempMs.ToArray();
                }
            }
        }
        public static string Compress(string str)
        {
            //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误
            return Convert.ToBase64String(Compress(Convert.FromBase64String(Convert.ToBase64String(Encoding.Default.GetBytes(str)))));
        }
        public byte[] GetPictureData(string imagepath)
        {
            try
            {
                /**/
                ////根据图片文件的路径使用文件流打开,并保存为byte[]
                FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
                byte[] byData = new byte[fs.Length];
                fs.Read(byData, 0, byData.Length);
                fs.Close();
                return byData;
            }
            catch (System.Exception e)
            {
                return null;
            }
        }
        private static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }
            return bmp;
        }

        /// <summary>
        /// BitmapImage转ByteArray
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private static byte[] BitmapImageToByteArray(BitmapImage bmp)
        {
            byte[] byteArray = null;
            try
            {
                Stream sMarket = bmp.StreamSource;
                if (sMarket != null && sMarket.Length > 0)
                {
                    //很重要,因为Position经常位于Stream的末尾,导致下面读取到的长度为0。
                    sMarket.Position = 0;
                    using (BinaryReader br = new BinaryReader(sMarket))
                    {
                        byteArray = br.ReadBytes((int)sMarket.Length);
                    }
                }
                //Console.WriteLine(sMarket.Length.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return byteArray;
        }
        public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        //反过来,16进制格式的string 转成byte[],例如, "ae00cf"转换成0xae00cf,长度缩减一半;"3031" 转成new byte[]{ 0x30, 0x31}:
        public static byte[] GetBytes(string hexString, out int discarded)
        {
            discarded = 0;
            string newString = "";
            char c;
            // remove all none A-F, 0-9, characters
            for (int i = 0; i < hexString.Length; i++)
            {
                c = hexString[i];
                if (Uri.IsHexDigit(c))
                    newString += c;
                else
                    discarded++;
            }
            // if odd number of characters, discard last character
            if (newString.Length % 2 != 0)
            {
                discarded++;
                newString = newString.Substring(0, newString.Length - 1);
            }
            int byteLength = newString.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                hex = new String(new Char[] { newString[j], newString[j + 1] });
                bytes[i] = HexToByte(hex);
                j = j + 2;
            }
            return bytes;
        }
        private static byte HexToByte(string hex)
        {
            byte tt = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return tt;
        }
        /// <summary>
        /// 字符串转BitmapImage
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static BitmapImage ToBitmapImage(string Value)
        {
            string hexValue = Value;
            byte[] imageByte = Convert.FromBase64String(hexValue);
            imageByte = Decompress(imageByte);
            BitmapImage imgSource = ByteArrayToBitmapImage(imageByte);
            return imgSource;
        }

        /// <summary>
        /// BitmapImage转字符串
        /// </summary>
        /// <param name="bi"></param>
        /// <returns></returns>
        public static string toString(BitmapImage imgSource)
        {
            try
            {              
                byte[] imageByte = BitmapImageToByteArray(imgSource);
                byte[] sourceData2 = Compress(imageByte);
                string recString = Convert.ToBase64String(sourceData2);
                return recString;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return "";
        }
    }
}


//保存

标题

private void Button_Click_2(object sender, RoutedEventArgs e)
{
            //选择图片
            //最好使用WPF原生OpenFileDialog
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.Title = "选择文件";
            openFileDialog.Filter = "图片(*.bmp;*.gif;*.jpg;*.png)|*.bmp;*.gif;*.jpg;*.png";
            openFileDialog.FileName = string.Empty;
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            openFileDialog.DefaultExt = "jpg";
            bool? result = openFileDialog.ShowDialog();
            if (result != true)
            {
                return;
            }
            string fileName = openFileDialog.FileName;
 
            BitmapImage image = new BitmapImage();
            FileStream m_ImageStream = new FileStream(fileName, FileMode.Open);
            image.BeginInit();
            image.StreamSource = m_ImageStream;
            image.EndInit();
            // BitmapImage转字符串
            var _zp = ImagesHelper.toString(image);
            //保存进数据库
           ....
}


读取并显示图片


private void Window_Loaded(object sender, RoutedEventArgs e)
{
      //读取数据库
      ....
      var _zp="获得的图片字符串";
      if(!string.IsNullOrEmpty(_zp)){
         ZP.Source = ImagesHelper.ToBitmapImage(models.ZP); //图片加载,ZP为Image控件
       }
}


这篇文档对您是否有帮助?

Winform 全屏显示

Winform 全屏显示

Winform程序无边框、置顶、全屏显示
WPF之Image控件

WPF之Image控件

Image控件加载图片包括加载动态图片,加载静态图片两种方式。加载动态图片通过生成一个BitmapImage,创建该对象后,赋给Image的Source即可。加载的形式:BitmapImage myBitmapImage =new BitmapImage();myBitmapImage.BeginInit();取得数据库存储的图片字段,MSSQL的Image类型Byte[] mybyte = Re
wpf list<T>与ObservableCollection<T>的区别

wpf list<T>与ObservableCollection<T>的区别

List《T》与ObservableCollection《T》的用法基本上是一样的。区别:list《T》:当T继承于INotifyPropertyChanged时,如果list《T》中的属性发生改变,则通知UI属性值已发生改变。但当list《T》添加一项时,list《T》就无法通知前端UI了(此时,ObservableCollection《T》闪亮登场)。ObservableCollection《
WPF调用线程复制文件并显示进度条

WPF调用线程复制文件并显示进度条

在WPF中复制文件时,如何调用线程,显示进度条。《Window x:Class="WpfThreadTest.MainWindow"xmlns="http:schemas.microsoft.comwinfx2006xamlpresentation"xmlns:x="http:schemas.microsoft.comwinfx2006xaml"Title="MainWindow" Closed=
WPF中对XML的读写

WPF中对XML的读写

已知有一个XML文件(bookste.xml)如下:《?xmlversion="1.0" encoding="gb2312"?》《bookste》《bookgenre="fantasy" ISBN="236314"》《title》OberonsLegacy《title》《auth》Cets,Eva《auth》《price》5.95《price》《book》《bookste》 1、往《bookste