C# byte陣列與Image相互轉換的方法

世紀緣發表於2016-03-23

功能需求:

1、把一張圖片(png bmp jpeg bmp gif)轉換為byte陣列存放到資料庫。

2、把從資料庫讀取的byte陣列轉換為Image物件,賦值給相應的控制元件顯示。

3、從圖片byte陣列得到對應圖片的格式,生成一張圖片儲存到磁碟上。

這裡的Image是System.Drawing.Image。

以下三個函式分別實現了上述三個需求:

複製程式碼程式碼如下:

// Convert Image to Byte[]
        private byte[] ImageToByte(Image image)
        {
            ImageFormat format = image.RawFormat;
            using (MemoryStream ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }
                byte[] buffer = new byte[ms.Length];
                //Image.Save()會改變MemoryStream的Position,需要重新Seek到Begin
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }

        // 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;
        }


相關文章