我有一个网络服务,它向客户端返回一个字节[],以显示图像。
此图像存储在 json 对象中,请参见 fiddle: http://jsfiddle.net/FuGN8/
在我做了一行简单的操作后,数字数组被分配给结果:
result = result["d"];
这是通过 AJAX 调用获取的,因此我想根据此数据渲染图像。
当然,做这样的事情:
$("img#mytag").attr("src", result);
不会做我想做的事。
是否有一个 javascript 命令可以实现我想要的功能?
我更改的服务器端代码:
WebClient wsb = new WebClient();
string url = "...";
byte[] resp = wsb.DownloadData(url);
UTF8Encoding enc = new UTF8Encoding();
return enc.GetString(resp);
但在客户端,由于我不知道图像类型是什么,我正在尝试:
src="data:image/*;base64,"+RET_VAL
它没有做任何事情。类似地,我也尝试过:
src="data:image;base64,"+RET_VAL
由于上面是进行UTF8编码,所以我还添加了以下内容:
src:"data:image;base64,"+window.btoa(unescape(encodeURIComponent( RET_VAL )))
最佳答案
您没有在图像中使用 Base64 编码。请改用 Convert.ToBase64String
方法。您还可以在 JSON 响应中发送图像类型,以便将其应用到 src
属性。我可以让它使用这段代码:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string SendImage()
{
var path = @"C:\teste.png";
byte[] bytes = File.ReadAllBytes(path);
Image image = null;
using (var stream = new MemoryStream(bytes))
image = Image.FromStream(stream);
var json = new Dictionary<string, object>();
json.Add("type", new ImageFormatConverter().ConvertToString(image.RawFormat).ToLower());
json.Add("contents", Convert.ToBase64String(bytes));
return new JavaScriptSerializer().Serialize(json);
}
这段 JavaScript 代码:
$.ajax({
type: 'GET',
url: 'WebService1.asmx/SendImage',
contentType: 'application/json; charset=utf-8',
success: function (response) {
var data = JSON.parse(response.d);
$('<img />').attr('src', 'data:image/' + data.type + ';base64,' + data.contents).appendTo('body');
}
})
当然,当您使用 WebClient
获取图像时,您必须对其进行调整。
关于javascript - 图像下载为 JSON 整数数组,但我想通过转换为 byte[] 来渲染此图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19690396/