C#将路径图片生成流数据供Background的URL调用

发布单位: 发布人:张鑫鑫 发布时间:2019/5/3 15:43:55 关注度:382

1、完美解决方案,支持PNG透明格式

using (FileStream fs = new FileStream(path, FileMode.Open))
{
byte[] byData = new byte[fs.Length];
fs.Read(byData, 0, byData.Length);
fs.Close();
context.Response.Write("data:image/jpeg;base64," Convert.ToBase64String(byData));
}

案例:cloud->ashx->base64

2、只能生成JPG格式,PNG背景为白色,不推荐使用,仅供学习System.Drawing.Bitmap用法

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(path);

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();
context.Response.Write("data:image/jpeg;base64," Convert.ToBase64String(arr));