Content feed Comments Feed

The Official ASATO Site

Hi, welcome to my blog. ASP,asp.net,Health,Javascript,JQUERY

in this article,wo will learn how to convert images to byte arrays, how to convert byte[] back into images:

first:
convert images to byte arrays

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        /// <summary>
        /// convert image to byte[]
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public byte[] PhotoToBytes(string filePath) {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            try {
                byte[] photo = br.ReadBytes((int)fs.Length);
                br.Close();
                fs.Close();
                return photo;
            }
            catch {
                return null;
            }
        }

next: convert byte[] back into images

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
        /// <summary>
        /// byte[] back into Image
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public Image BytesToPhoto(byte[] Bytes) {
 
            MemoryStream stream = null;
 
            Image img = null;
 
            try {
                stream = new MemoryStream(Bytes);
 
                img = Image.FromStream(stream, true);
 
                return img;
 
            }
            catch {
 
                return null;
 
            }
            finally {
                stream.Close();
 
                img.Dispose();
 
            }
        }

Leave a Reply