C# 返回圖片的位元組流byte[]

衣舞晨風發表於2015-06-17
#region 返回圖片的位元組流byte[]
        /// <summary>
        /// 返回圖片的位元組流byte[]
        /// </summary>
        /// <param name="imagePath"></param>
        /// <param name="webClient"></param>
        /// <returns></returns>
        public static byte[] getImageByte(string imagePath, WebClient webClient)
        {
            byte[] imgByte = null;
            try
            {
                //MessageBox.Show("getImageByte");
                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start();
                //DateTime dateStart = DateTime.Now;

                if (PubFunc.UrlDiscern(imagePath))
                {
                    Bitmap bt = new Bitmap(webClient.OpenRead(imagePath));
                    imgByte = PubFunc.ImgToByte(bt);
                }
                else
                {
                    using (FileStream files = new FileStream(imagePath, FileMode.Open))
                    {
                        imgByte = new byte[files.Length];
                        files.Read(imgByte, 0, imgByte.Length);
                        files.Close();
                    }
                }
                //stopwatch.Stop();
                //MessageBox.Show((DateTime.Now - dateStart).TotalMilliseconds.ToString());

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString());
            }
            return imgByte;
        }
        #endregion
  #region 圖片轉換成位元組流
        /// <summary>
        /// 圖片轉換成位元組流
        /// </summary>
        /// <param name="img">要轉換的Image物件</param>
        /// <returns>轉換後返回的位元組流</returns>
        public static byte[] ImgToByte(Image img)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] imagedata = null;
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    imagedata = ms.GetBuffer();
                    return imagedata;
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.ToString());
                return null;
            }
        }
        #endregion


相關文章