Create HTML canvas from Ajax Arraybuffer response type

删除回忆录丶 提交于 2020-01-06 01:48:42

问题


I am doing a Ajax call to Server for a Jpeg file. I have the data returned as Array buffer. Now how can I render this Array buffer on the canvas. Now please dont suggest any answer like setting the source url to the image. I want to hold the image data on memory for some processing.


回答1:


If you don't want to use the buffer as an image source, the only option left is to parse the raw buffer yourself. Just have in mind that this buffer contains the unprocessed (raw) file, so by parsing it means low-level byte parsing (using a DataView).

It's doable but you need to handle all aspects of parsing JPEG files such as header, format areas, decompressing and decoding any kind of image buffers (RGB, CMYK, YUV etc.), validation and error handling.

However, this can be unpractical unless you intend to use special aspects of the JPEG file such as retrieving for example raw CMYK data.

So the only practical way, if you want to avoid using a JavaScript parser, is to convert your ArrayBuffer to Base-64 (going by a view such as Uint8Array), prepend it with a data-uri header, and then set it as src for an Image object. Better yet, just set the URL as image source directly and let the browser parse and decode the file.

There are essentially only two ways to get image data into canvas:

  1. using an image source which can be Image, Video, Canvas or a context.
  2. Writing raw pixel data using ImageData objects.

For the latter you need to get the bitmap from somewhere, usually another or the same canvas, or from an external source in form of raw uncompressed bitmap data, or a file you pass on to the browser to process, or you process using the low-level approach mentioned earlier (both cases require CORS requirements to be fulfilled).

Sorry, there are no other ways..

You can still draw the JPEG image to canvas and then extract the image data (pixels):

context.drawImage(image, x, y);                             // image to canvas
var imageData = context.getImageData(x, y, width, height);  // get ImageData object
var uint8clampedarray = imageData.data;                     // get the 8-bit view
var arraybuffer = uint8clampedarray.buffer;                 // the raw byte buffer


来源:https://stackoverflow.com/questions/28827670/create-html-canvas-from-ajax-arraybuffer-response-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!