How can I create a canvas imageData array from an arrayBuffer representation of a JPG

前端 未结 1 1276
余生分开走
余生分开走 2020-12-16 03:21

First of all I am aware there are standard methods of achieving this (readAsDataURL and drawImage), but unfortunately they are not usable for this specific use case.

相关标签:
1条回答
  • 2020-12-16 03:44

    Edit

    A JPEG file isn't a simple byte-array of colour data, and therefore you can't simply load it in like this. If you want to get around this without importing directly into a canvas you'll have to use a JPEG decoding library, such as this project by notmasteryet which I found via a quick google search.

    Original

    unfortunately they are not usable for this specific use case

    Why are they not usable?

    // example array
    u = new Uint8ClampedArray(4);
    u[0] = 255, u[1] = 56, u[2] = 201, u[3] = 8; // [255, 56, 201, 8]
    // to String
    str = String.fromCharCode.apply(null, u); // "ÿ8É"
    // to Base64
    b64 = btoa(str); // "/zjJCA=="
    // to DataURI
    uri = 'data:image/jpeg;base64,' + b64; // "data:image/jpeg;base64,/zjJCA=="
    

    And the reverse

    // uri to Base64
    b64 = uri.slice(uri.indexOf(',')+1);
    // to String
    str = atob(b64);
    // to Array
    arr = str.split('').map(function (e) {return e.charCodeAt(0);});
    // to Uint8ClampedArray
    u = new Uint8ClampedArray(arr); // [255, 56, 201, 8]
    
    0 讨论(0)
提交回复
热议问题