简体   繁体   English

在javascript中将字节数组转换为jpeg图像

[英]Converting byte array to jpeg image in javascript

I have an asp.net page. 我有一个asp.net页面。

Inside this page I have an img control/element. 在此页面中,我有一个img控件/元素。

I am calling an ashx page on my server. 我正在服务器上调用ashx页面。

This ashx page accepts a timestamp from the client and compares it to a timestamp stored on the server. 该ashx页面接受来自客户端的时间戳,并将其与服务器上存储的时间戳进行比较。

If the timestamps do not match then I return an image which has been converted to a byte array (in C#). 如果时间戳不匹配,则返回已转换为字节数组(在C#中)的图像。

If the timestamps do not match then I return a string value of "-1". 如果时间戳不匹配,那么我将返回字符串值“ -1”。

So, this is a cut-down of my ashx page: 因此,这是我的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");
    }
}

And in my javascript code: 在我的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');
}

But I get an error returned: 但是我得到一个错误返回:

TypeError: Function.prototype.apply: Arguments list has wrong type TypeError:Function.prototype.apply:参数列表类型错误

If I just apply: 如果我只申请:

live1x4.src = 'data:image/bmp;base64,' + btoa(response);

instead of: 代替:

live1x4.src = 'data:image/bmp;base64,' + encode(response);

I get this error: 我收到此错误:

InvalidCharacterError: btoa failed. InvalidCharacterError:btoa失败。 the string to be encoded contains characters outside of the Latin1 range. 要编码的字符串包含Latin1范围之外的字符。

I have tried using a canvas control with example code i have found on this site. 我曾尝试使用画布控件和在此站点上找到的示例代码。 I do not get an error but I also do not get an image. 我没有收到错误,但也没有图像。

I know the image is valid because my old code was point the image.src directly to the ashx handler (and i was not comparing timestamps). 我知道图像是有效的,因为我的旧代码将image.src直接指向ashx处理程序(并且我没有比较时间戳)。

I do not want to encode the byte array to base64 string on the server because that would inflate the download data. 我不想在服务器上将字节数组编码为base64字符串,因为这会使下载数据膨胀。

I was wondering if I was using the wrong context.Response.ContentType but I could not see what else I could use. 我想知道我是否使用了错误的context.Response.ContentType,但是我看不到我还能使用什么。

What am i doing wrong? 我究竟做错了什么?

When looking at the documentation at MDN you should pass 1 or more parameters to fromCharCode . 查看MDN上的文档时 ,应将1个或多个参数传递给fromCharCode You pass none in this line: 您在此行均未通过:

var str = String. var str =字符串。 fromCharCode .apply(null, data); fromCharCode .apply(null,data);

The syntax is: 语法为:

String.fromCharCode(num1, ..., numN)

There is although the apply method as your said in comments, but you use it the wrong way. 尽管有您评论中所说的apply方法,但是使用错误的方式。 The first parameter shouldn't be null . 第一个参数不应为null

The syntax of that is (from Convert array of byte values to base64 encoded string and break long lines, Javascript (code golf) ): 的语法是(从将字节值数组转换为base64编码的字符串和长行,Javascript(代码高尔夫) ):

somefunction.apply(thisObj[, argsArray])

Just use 只需使用

var str = String.fromCharCode.apply(data);

So use the thisObj parameter to pass the data . 因此,请使用thisObj参数传递data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM