Imageとbyte[]間の変換

5237 ワード

  // image            

        public static byte[] GetByteImage(Image img)

        {

            byte[] bt = null;

            if (!img.Equals(null))

            {

                using (MemoryStream mostream = new MemoryStream())

                {

                    Bitmap bmp = new Bitmap(img);

                    bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);// 



                    bt = new byte[mostream.Length];

                    mostream.Position = 0;// 

                    mostream.Read(bt, 0, Convert.ToInt32(bt.Length));

                }

            }

            return bt;

        }



        /// <summary>

        ///  byte[] 

        /// </summary>

        /// <param name="strFile">string </param>

        /// <returns>byte[]</returns>

        public static byte[] GetBytesByImagePath(string strFile)

        {

            byte[] photo_byte = null;

            using (FileStream fs =

            new FileStream(strFile, FileMode.Open, FileAccess.Read))

            {

                using (BinaryReader br = new BinaryReader(fs))

                {

                    photo_byte = br.ReadBytes((int)fs.Length);

                }

            }

            return photo_byte;

        }



        /// <summary>

        ///  byte[] 

        /// </summary>

        /// <param name="bytes">byte[]</param>

        /// <returns>Image</returns>

        public static Image GetImageByBytes(byte[] bytes)

        {

            Image photo = null;

            using (MemoryStream ms = new MemoryStream(bytes))

            {

                ms.Write(bytes, 0, bytes.Length);

                photo = Image.FromStream(ms, true);

            } 

            return photo;

        }