简体   繁体   中英

Convert an ImageData object (not a canvas) to image dataURL

I would like to create a dataURL from an ImageData object (ie width, height, data). I realize canvas has this, but I want to avoid distortions canvas use has (alpha premultiply mainly) .. ie I want to avoid the obvious canvas.putImageData step.

From this post I can make any arraybuffer/typedarray/dataview into base64. What I dont know is how the canvas dataurl adds the width/height to the Uint8 data portion of the base64 string. Nor do I know how the png conversion is done. (I'd be OK with a raw data image type but I don't think there is one .. just png and jpg)

Possible approaches:

  • Load ImageData into Canvas with putImageData. Fails, distorts data.
  • Create an image with img.src = base64 data. Fails, has to be canvas dataurl.
  • Other?

Anyone know how to construct an image dataURL from the raw width, height, data Imagedata?

It is theoretically possible, but not practical, to convert an ImageData object to a data URL without using a Canvas .

An ImageData object has the raw RGBA representation of the image pixels. A data URL expects data to be in a recognized MIME format. According to MDN , the only widely supported pixel-based image types are GIF, JPEG, PNG, and ICO. GIF and JPEG are quite complex, all of these formats have header information, and PNG has a CRC, so it is non-trivial to convert the pixel data into the image format.

The recommended way to do the conversion is using the Canvas . You say your attempts "distorted" the data, but that suggests there was something wrong with how you did it, since that is really the best supported method as it builds on the internals browsers use to do all their image manipulation.

Did you check your context settings? You probably want ctx.globalCompositeOperation = "copy" instead of the default "source-over" if you are using alpha.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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