功能需求:
1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库读取的byte数组转换为Image对象,赋值给相应的控件显示。
3、从图片byte数组得到对应图片的格式,生成一张图片保存到磁盘上。
这里的Image是System.Drawing.Image。
以下三个函数分别实现了上述三个需求:
        // Convert Byte[] to Image
        private Image ByteToImage(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            Image image = System.Drawing.Image.FromStream(ms);
            return image;
        }
        // Convert Byte[] to a picture
        private string CreateImageFromByte(string fileName, byte[] buffer)
        {
            string file = fileName; //文件名(不包含扩展名)
            Image image = ByteToImage(buffer);
            ImageFormat format = image.RawFormat;
            if (format.Equals(ImageFormat.Jpeg))
            {
                file += ".jpeg";
            }
            else if (format.Equals(ImageFormat.Png))
            {
                file += ".png";
            }
            else if (format.Equals(ImageFormat.Bmp))
            {
                file += ".bmp";
            }
            else if (format.Equals(ImageFormat.Gif))
            {
                file += ".gif";
            }
            else if (format.Equals(ImageFormat.Icon))
            {
                file += ".icon";
            }
            //文件路径目录必须存在,否则先用Directory创建目录
            File.WriteAllBytes(file, buffer);
            return file;
        }