C#图片与string相互转换

来源:互联网 发布:ubuntu vi 编辑命令 编辑:程序博客网 时间:2024/05/17 21:38

在C#中      

   图片到byte[]再到base64string的转换:

               Bitmap bmp = new Bitmap(filepath);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
            string     pic = Convert.ToBase64String(arr);

 

 base64string到byte[]再到图片的转换:

                      byte[] imageBytes = Convert.FromBase64String(pic);
                    //读入MemoryStream对象
                    MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
                    memoryStream.Write(imageBytes, 0, imageBytes.Length);
                    //转成图片
                    Image image = Image.FromStream(memoryStream);

 

现在的数据库开发中:图片的存放方式一般有CLOB:存放base64string

                                                                       BLOB:存放byte[]

 一般推荐使用byte[]。因为图片可以直接转换为byte[]存放到数据库中

若使用base64string 还需要从byte[]转换成base64string 。更浪费性能。


转自http://blog.csdn.net/thebesttome/article/details/6870155

0 0
原创粉丝点击