一、图片转byte
public byte[] ImageToByte() { string imagefile = @"http://192.168.0.212/pass/T-1.jpg";//互联网图片地址 Image img = UrlToImage(imagefile); Bitmap bmp = new Bitmap(img); MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); var a = Convert.ToBase64String(arr); string strbaser64 = ""; WebClient mywebclient = new WebClient(); byte[] Bytes = mywebclient.DownloadData(imagefile); return Bytes } public Image UrlToImage(string url) { WebClient mywebclient = new WebClient(); byte[] Bytes = mywebclient.DownloadData(url); using (MemoryStream ms = new MemoryStream(Bytes)) { Image outputImg = Image.FromStream(ms); return outputImg; } }
二、byte转图片
将byte数组保存成图片: 方式一:System.IO.File.WriteAllBytes(@"c:\test.jpg", bytes); 方式二:MemoryStream ms=new MemoryStream(Byte[] b); 把那个byte[]数组传进去,然后 FileStream fs=new FileStream(路径 例如:"E:\image\1.jpg"); ms.writeto(fs); ms.close(); fs.close(); 方法三: //得到图片地址 var stringFilePath = context.Server.MapPath(string.Format("~/Image/{0}{1}.jpg", imageName, id)); //声明一个FileStream用来将图片暂时放入流中 FileStream stream = new FileStream(stringFilePath, FileMode.Open); using (stream) { //透过GetImageFromStream方法将图片放入byte数组中 byte[] imageBytes = this.GetImageFromStream(stream,context); //上下文确定写到客户短时的文件类型 context.Response.ContentType = "image/jpeg"; //上下文将imageBytes中的数据写到前段 context.Response.BinaryWrite(imageBytes); stream.Close(); }