C# 载入从文件载入图片,并且解除占用

//方法一:
            Stream s = File.Open(fileName, FileMode.Open);
            Image img = Bitmap.FromStream(s);
            s.Close();
            s.Dispose();
//方法二,封装成函数:
        public static System.Drawing.Image LoadImage(string fileName)
        {
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            int byteLength = (int)fileStream.Length;
            byte[] fileBytes = new byte[byteLength];
            fileStream.Read(fileBytes, 0, byteLength);
            fileStream.Close();

            return System.Drawing.Image.FromStream(new MemoryStream(fileBytes));
        }

从文件取得byte数组,并且不占用

        byte[] GetBytesFromFile(string spath)
        {
            FileStream file = new FileStream(spath, FileMode.Open, FileAccess.Read);
            byte[] bb = new byte[file.Length];
            file.Read(bb, 0, (int)file.Length);

            file.Close();

            return bb;
        }
        /// 
        /// 读取byte[]并转化为图片
        /// 
        /// byte[]
        /// Image
        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;
        }

 

你可能感兴趣的:(C#基础)