简体   繁体   English

将大画布的内容转换为JPEG

[英]Converting the contents of a large Canvas to JPEG

How to convert contents of a large Canvas to a JPEG format? 如何将大型Canvas的内容转换为JPEG格式? I have a large canvas (around 1000x1000 pixels or larger) that I'd like to convert to JPEG formatted data for uploading to a server. 我有一个大画布(大约1000x1000像素或更大),我想将其转换为JPEG格式的数据以上传到服务器。

If the image were smaller, I could use canvas.toDataURL('image/jpeg') , but data URLs have a max size, and my image doesn't fit under that limit. 如果图像较小,则可以使用canvas.toDataURL('image/jpeg') ,但是数据URL的大小上限,并且我的图像不符合该限制。

There is canvas.getImageData() which looks promising, but how to convert that to a JPEG? canvas.getImageData()看起来很有希望,但是如何将其转换为JPEG? Is that possible on the client side? 在客户端这可能吗?

I have tried using canvas.toDataURL(), and it doesn't work for large Canvases. 我尝试使用canvas.toDataURL(),但不适用于大型Canvas。 Browsers seem to have max size for dataUrl . 浏览器似乎具有dataUrl的最大大小 For example Chrome gives me data URL data:, when using a large canvas. 例如data:,当使用大画布时,Chrome为我提供了数据URL data:,

You can use toBlob to achieve this 您可以使用toBlob实现此目的

The HTMLCanvasElement.toBlob() method creates a Blob object representing the image contained in the canvas; HTMLCanvasElement.toBlob()方法创建一个Blob对象,该对象表示画布中包含的图像。 this file may be cached on the disk or stored in memory at the discretion of the user agent. 该文件可以由用户代理决定是否缓存在磁盘上或存储在内存中。

You'll notice the last two arguments I submitted were 'image/jpeg', 0.9 this is the type and quality you can leave these out if you ever want a PNG. 您会注意到我提交的最后两个参数是'image/jpeg', 0.9就是类型和质量,如果您想要PNG,可以将其省略。

If type is not specified, the image type is image/png. 如果未指定type,则图像类型为image / png。 The created image is in a resolution of 96dpi. 创建的图像的分辨率为96dpi。 The third argument is used with image/jpeg images to specify the quality of the output. 第三个参数与image / jpeg图像一起使用,以指定输出的质量。

 let canvas = document.querySelector('canvas'); ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(600, 0); ctx.lineTo(1200, 1200); ctx.lineTo(0, 1200); ctx.closePath(); ctx.fillStyle = 'yellow'; ctx.fill(); canvas.toBlob((blob) => { let img = document.createElement('img'); let url = URL.createObjectURL(blob); img.src = url; document.body.appendChild(img); }, 'image/jpeg', 0.9); 
 <canvas width="1200" height="1200"></canvas> 

I hope you find this helpful 🙂 希望对您有帮助

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

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