我有一个 asp.net 页面。
在此页面中,我有一个 img 控件/元素。
我在我的服务器上调用一个 ashx 页面。
这个 ashx 页面接受来自客户端的时间戳,并将它与存储在服务器上的时间戳进行比较。
如果时间戳不匹配,我将返回一张已转换为字节数组(在 C# 中)的图像。
如果时间戳不匹配,那么我返回一个字符串值“-1”。
所以,这是我的 ashx 页面的缩减版:
public void ProcessRequest (HttpContext context) {
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
try
{
string clientTS = context.Request.QueryString["clientTS"];
if (clientTS == serverTS)
{
//new version available. refresh browser
context.Response.ContentType = "text/json";
string value = "-1";
context.Response.Write(value);
}
else
{
context.Response.ContentType = "image/jpg";
byte[] data = Shared.GetMobileNextFrame("par1", 0);
context.Response.BinaryWrite(data);
}
}
catch (Exception ex)
{
context.Response.ContentType = "text/json";
context.Response.Write("ERR");
}
}
在我的 javascript 代码中:
function GetImageStatus() {
finished = false;
var val = url + '/Mobile/isNewFrame.ashx?Alias=' + Alias + '&CamIndex=' + camIndex + '&Version=' + version + '&GuidLogOn=' + guidLogOn;
$.ajax({
url: val,
type: 'GET',
timeout: refreshWaitlimit,
data: lastTS,
success: function (response, status, xhr) {
var ct = xhr.getResponseHeader("content-type");
if (ct.indexOf('json') > -1) {
//no update
}
else {
try {
live1x4.src = 'data:image/bmp;base64,' + encode(response);
}
catch (err) {
alert(err);
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
//handle error
}
});
}
function encode(data) {
var str = String.fromCharCode.apply(null, data);
return btoa(str).replace(/.{76}(?=.)/g, '$&\n');
}
但是我得到一个错误返回:
TypeError: Function.prototype.apply: Arguments list has wrong type
如果我只是申请:
live1x4.src = 'data:image/bmp;base64,' + btoa(response);
代替:
live1x4.src = 'data:image/bmp;base64,' + encode(response);
我收到这个错误:
InvalidCharacterError: btoa failed. the string to be encoded contains characters outside of the Latin1 range.
我已经尝试使用 Canvas 控件和我在这个网站上找到的示例代码。我没有收到错误消息,但也没有收到图片。
我知道图像是有效的,因为我的旧代码将 image.src 直接指向 ashx 处理程序(而且我没有比较时间戳)。
我不想在服务器上将字节数组编码为 base64 字符串,因为那样会使下载数据膨胀。
我想知道我是否使用了错误的 context.Response.ContentType 但我看不到我还能使用什么。
我做错了什么?
最佳答案
查看 documentation at MDN 时您应该将 1 个或多个参数传递给 fromCharCode
。你在这行没有传递:
var str = String.fromCharCode.apply(null, data);
语法是:
String.fromCharCode(num1, ..., numN)
虽然如您在评论中所说的那样有 apply
方法,但是您用错了方法。第一个参数不应为 null
。
它的语法是(来自 Convert array of byte values to base64 encoded string and break long lines, Javascript (code golf) ):
somefunction.apply(thisObj[, argsArray])
就用
var str = String.fromCharCode.apply(data);
所以使用thisObj
参数来传递data
。
关于javascript - 在javascript中将字节数组转换为jpeg图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21699882/