Home > Web Front-end > JS Tutorial > The toDataURL() method in canvas converts images to dataURL (base64)

The toDataURL() method in canvas converts images to dataURL (base64)

小云云
Release: 2018-01-18 10:15:58
Original
4950 people have browsed it

This article mainly introduces to you the relevant information about using toDataURL() in canvas to convert images into dataURL(base64). The article introduces it in detail through sample code, which has certain reference learning value for everyone's study or work. Friends who need it, please follow the editor to learn together. I hope it can help everyone.

Benefits of converting images to base64

Converting images to Base64 encoding allows you to easily insert images into other web pages and editors without uploading files. This is extremely convenient for some small pictures, because you don't need to find a place to save the picture.

Convert the image to base64 encoding, which is generally used for small images on the web. It can not only reduce the number of image requests (collected into js and css codes), but also prevent problems such as relative paths. Resulting in a 404 error for the image.

Introduction

Assume an application scenario: Due to some special reasons, the image path is requested from the server, and the base64 dataURL of the corresponding image is required to be obtained through this path. In this scenario, we first infer that the image path is accessible, and we also need a way to convert the image to a dataURL.

How do we achieve it?

dataURL

Let’s briefly review the syntax of the orthodox dataURL, which will help us check whether the converted content is correct. A complete dataURI should look like this:

data:[<mediatype>][;base64],<data>
Copy after login

The mediatype declares the file type, following MIME rules, such as "image/png", "text/plain"; followed by the encoding type, here we only cover base64 ;The next step is the encoded content of the file. We often see the src of the img tag in HTML written like this:

src="data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7"
Copy after login

This img refers to the dataURL encoded in base64. As long as the browser supports it, it can be decoded into a gif image and rendered.

.toDataURL()

The FileReader object also has similar methods, such as .readAsDataURL(), but it only accepts file or blob types, and these two types can generally only be passed through Get the files attribute of the element, or use the Blob() constructor to manually create a new object. The embarrassing thing is that we currently only have the image path, which is subject to the browser's security policy. The files attribute of is read-only, and the Blob() constructor only accepts file content. Both methods are It cannot be obtained directly through the image path. The hypothetical application scenario above forces us to first consider how to obtain the image content through the path. is OK and can be drawn into , and happens to have the .toDataURL() method.

Everything is ready, we only need to put the image obtained by into and then convert it through the .toDataURL() method to get the base64-encoded dataURL. Let’s look at the syntax of this method:

canvas.toDataURL([type, encoderOptions]);
Copy after login

canvas is the DOM element object; the parameter type specifies the image type. If the specified type is not supported, it will be replaced by the default value image/png; encoderOptions can be image Set the image quality for /jpeg or image/webp type pictures, with a value of 0-1. If it exceeds the value, it will be replaced by the default value of 0.92.

It should be noted that before converting to dataURL, you must first ensure that the image is successfully loaded, so the .toDataURL() method should be written in the onload asynchronous event of . Now let’s implement a functional function:

 function getBase64(url){
  //通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 <img> 省去了 append(),也就避免了文档冗余和污染
  var Img = new Image(),
   dataURL='';
  Img.src=url;
  Img.onload=function(){ //要先确保图片完整获取到,这是个异步事件
   var canvas = document.createElement("canvas"), //创建canvas元素
    width=Img.width, //确保canvas的尺寸和图片一样
    height=Img.height;
   canvas.width=width;
   canvas.height=height;
   canvas.getContext("2d").drawImage(Img,0,0,width,height); //将图片绘制到canvas中
   dataURL=canvas.toDataURL('image/jpeg'); //转换图片为dataURL
  };
 }
Copy after login

A conversion function that can be called at any time is completed. It will return an entire dataURL string after the image is loaded.

Improvement

The onload event ensures that the conversion task is executed after loading, but it brings a new problem - the dataURL will only be returned after the image is loaded, and we cannot determine when the image is loaded. Complete loading. If the dataURL needs to be processed later (such as passing it to other servers), it is necessary to add a callback. This can ensure that the subsequent processing task is executed after the dataURL is successfully obtained. We need to modify getBase64():

 function getBase64(url,callback){ //添加一个回调参数
  ...
  Img.onload=function(){
   ...
   canvas.getContext("2d").drawImage(Img,0,0,width,height);
   dataURL=canvas.toDataURL('image/jpeg');
   callback?callback(dataURL):null; //调用回调函数
  };
 }
Copy after login

Add callback during execution:

 getBase64('//upload.jianshu.io/users/upload_avatars/555630/fdd1b798e6b0.jpg',(dataURL)=>{
  console.log(dataURL);
 });
Copy after login

That’s it. If compatibility is not considered, maybe we can use promises and generators to implement it, and it will be more perfect if we add some error handling.

Related recommendations:

html5 Canvas realizes image rotation

jquery plug-in canvaspercent.js realizes the percentage round cake effect example sharing

How Canvas handles images

The above is the detailed content of The toDataURL() method in canvas converts images to dataURL (base64). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template