public static string HttpRequestGetImageBase64(string Url, int TimeOut) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "Get"; request.Timeout = TimeOut; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); MemoryStream memoryStream = new MemoryStream(); responseStream.CopyTo(memoryStream); byte[] buff = new byte[memoryStream.Length]; memoryStream.Position = 0; memoryStream.Read(buff, 0, (int)memoryStream.Length); memoryStream.Close(); return Convert.ToBase64String(buff); } catch (Exception ex) { return ex.Message; } }; 调用 HttpRequestGetImageBase64(“http://www.qq.com/iamge/1.jpg”, 5000,); 然后 在返回头部加上 “data:image/jpeg;base64,”, 返回的就是完整的base64 格式体数据, 可以通过 jquery 设置 img src = "返回Base64数据"即可。 但是有时候有这样的需求,就是我们要下载远程图片,处理后再让前台显示,那么这里就需要把图 片的BASE64数据通过http 流的形式返回给前台,当然写入文件然后给前台地址可行,但是太麻烦。 这里就要注意了, 前台 action 就可以通过访问这个action获取到图片, byte[] bytes = Convert.FromBase64String(ImageBaseData); MemoryStream Ms = new MemoryStream(bytes); HttpContext.Response.ContentType = “image/jpeg”; HttpContext.Response.BinaryWrite(Ms.ToArray()); 当然如果不对图片数据处理,直接将 Stream responseStream = response.GetResponseStream(); 返回给http输出流就行了。 主要在中间对base64数据处理,所以做了两次转换。 |
|Archiver|手机版|小黑屋|软件开发编程门户 ( 陇ICP备2024013992号-1|甘公网安备62090002000130号 )
GMT+8, 2025-1-18 09:54 , Processed in 0.034641 second(s), 16 queries .
Powered by Discuz! X3.5
© 2001-2024 Discuz! Team.