2011年7月7日 星期四

C# 將圖檔/Imaget轉換為byte array

以下是2種方式的測試結果,
一是使用FileStream讀入圖檔,
另一是使用System.Drawing.Image讀入圖檔。
           
        // 先將圖檔讀到FileStream, 再轉換為byte array。
        private static void ToBinaryByFileStream(string imageFile)
        {
            FileStream fs = new FileStream(imageFile, FileMode.Open);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();
        }

        // 先將圖檔讀到Image object, 再轉換為byte array。
        private static void ToBinaryByImageObj(string imageFile)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(imageFile);
            MemoryStream mr = new MemoryStream();
            image.Save(mr, System.Drawing.Imaging.ImageFormat.Png);
            byte[] binaryImage = mr.ToArray();
            mr.Dispose();
            image.Dispose();
        }

// 測試method。 
public static void ConvertImageToBinary()
        {
            Console.WriteLine("=== Convert the image file to the binary object. ===");

            string imageFolder = @"D:\Images";
            // 測試的image數量。
            int sampleCount = 100;

            string[] imagePaths = Directory.GetFiles(imageFolder, "*.png");
            if (0 == imagePaths.Length)
            {
                Console.WriteLine("No image found.");
                return;
            }

            Stopwatch sw = new Stopwatch();

            sw.Reset();
            sw.Start();
            for (int i = 0; i < sampleCount; i++)
            {
                ToBinaryByFileStream(imagePaths[i]);
            }
            sw.Stop();
            Console.WriteLine("By FileStream: {0} ms.",
                sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < sampleCount; i++)
            {
                ToBinaryByImageObj(imagePaths[i]);
            }
            sw.Stop();
            Console.WriteLine("By System.Drawing.Image: {0} ms.",
                sw.ElapsedMilliseconds);
        }


測試100張圖檔的結果

Unit: ms

By FileStream
152
By System.Drawing.Image
2692


Image object會讀取圖檔的相關資訊,
相對地,FileStream只作資料的搬移,所以效能上會快很多。

沒有留言:

張貼留言