经常遇到系统之间转换文件的时候。如果不用字节是base64位字符串
base64编码字符串转换图片
/// <summary> /// base64编码的文本转为图片 /// </summary> /// <param name="txtFilePath">文件相对路径(存到服务器上)</param> /// <param name="str">图片字符串</param> private void Base64StringToImage(string txtFilePath, string str) { try { String inputStr = str; byte[] arr = Convert.FromBase64String(inputStr); MemoryStream ms = new MemoryStream(arr); Bitmap bmp = new Bitmap(ms); bmp.Save(System.Web.HttpContext.Current.Server.MapPath(txtFilePath) + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); ms.Close(); } catch (Exception ex) { } }
图片转换成base64编码字符串
/// <summary> /// 图片转换成base64编码字符串 /// </summary> /// <param name="txtFilePath">文件相对路径(存到服务器上)</param>
private string ImgToBase64String(string ImagePath) { try { Bitmap bmp = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(ImagePath)); 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(); return Convert.ToBase64String(arr); } catch (Exception ex) { return null; } }