[英]Converting byte array to jpeg image in javascript
我有一個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:參數列表類型錯誤
如果我只申請:
live1x4.src = 'data:image/bmp;base64,' + btoa(response);
代替:
live1x4.src = 'data:image/bmp;base64,' + encode(response);
我收到此錯誤:
InvalidCharacterError:btoa失敗。 要編碼的字符串包含Latin1范圍之外的字符。
我曾嘗試使用畫布控件和在此站點上找到的示例代碼。 我沒有收到錯誤,但也沒有圖像。
我知道圖像是有效的,因為我的舊代碼將image.src直接指向ashx處理程序(並且我沒有比較時間戳)。
我不想在服務器上將字節數組編碼為base64字符串,因為這會使下載數據膨脹。
我想知道我是否使用了錯誤的context.Response.ContentType,但是我看不到我還能使用什么。
我究竟做錯了什么?
查看MDN上的文檔時 ,應將1個或多個參數傳遞給fromCharCode
。 您在此行均未通過:
var str =字符串。 fromCharCode .apply(null,data);
語法為:
String.fromCharCode(num1, ..., numN)
盡管有您評論中所說的apply
方法,但是使用錯誤的方式。 第一個參數不應為null
。
的語法是(從將字節值數組轉換為base64編碼的字符串和長行,Javascript(代碼高爾夫) ):
somefunction.apply(thisObj[, argsArray])
只需使用
var str = String.fromCharCode.apply(data);
因此,請使用thisObj
參數傳遞data
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.