How to convert varBinary into image or video when retrieved from database in C#

前端 未结 4 1867
孤街浪徒
孤街浪徒 2021-01-16 06:31

I am using visual studio 2010, (desktop application) and using LINQ to SQL to save image/video or audio files to database in dataType VarBinary (MAX). This I ca

4条回答
  •  长发绾君心
    2021-01-16 07:31

    Dillie-O's code makes for a very nice extension method:

        // from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c:
        public static BitmapImage ToImage(this Binary b)
        {
            if (b == null)
                return null;
    
            var binary = b.ToArray();
            var image = new BitmapImage();
            var ms = new MemoryStream();
    
            ms.Write(binary, 0, binary.Length);
    
            image.BeginInit();
            image.StreamSource = new MemoryStream(ms.ToArray());
            image.EndInit();
    
            return image;
        }
    

提交回复
热议问题