.net FileUpload上传图片 图片转换二进制,以及保存显示
1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 4 5 Stream stream = FileUpload1.PostedFile.InputStream; 6 byte[] photo = new byte[FileUpload1.PostedFile.ContentLength]; 7 stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength); 8 stream.Close(); 9 10 11 System.Drawing.Image a = ByteToImage(photo); 12 string imgname = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg"; 13 string path = "Scripts/" + imgname; 14 a.Save(Server.MapPath(path)); 15 this.Image1.ImageUrl = path; 16 17 }
--转换方法
1 //图片转成二进制 2 public byte[] ImageToBytes(System.Drawing.Image image) 3 { 4 ImageFormat format = image.RawFormat; 5 using (MemoryStream ms = new MemoryStream()) 6 { 7 if (format.Equals(ImageFormat.Jpeg)) 8 { 9 image.Save(ms, ImageFormat.Jpeg); 10 } 11 else if (format.Equals(ImageFormat.Png)) 12 { 13 image.Save(ms, ImageFormat.Png); 14 } 15 else if (format.Equals(ImageFormat.Bmp)) 16 { 17 image.Save(ms, ImageFormat.Bmp); 18 } 19 else if (format.Equals(ImageFormat.Gif)) 20 { 21 image.Save(ms, ImageFormat.Gif); 22 } 23 else if (format.Equals(ImageFormat.Icon)) 24 { 25 image.Save(ms, ImageFormat.Icon); 26 } 27 byte[] buffer = new byte[ms.Length]; 28 //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin 29 ms.Seek(0, SeekOrigin.Begin); 30 ms.Read(buffer, 0, buffer.Length); 31 return buffer; 32 } 33 } 34 35 36 //二进制转成图片 37 public System.Drawing.Image ByteToImage(byte[] imgData) 38 { 39 System.IO.MemoryStream ms = new System.IO.MemoryStream(imgData); 40 System.Drawing.Image img = System.Drawing.Image.FromStream(ms); 41 return img; 42 }
鹰击长空,鱼翔浅底