Web Upload Photos

Source: Internet
Author: User

. Todataurl ()

FileReaderObjects also have similar methods, such as .readAsDataURL() , however, they are only accepted file or blob typed, and these two types are generally only <input[type=file]> available through the attributes of the element files , or Blob() manually create a new object with the constructor. The awkward thing is that we currently only have the picture path, subject to the browser's security policy, <input[type=file]> the files property is read-only, and the Blob() constructor only accepts the file content, neither of the two methods can be directly obtained through the picture path . The scenario described above forces us to first consider how to get the picture content through the path. is possible and can be drawn into <canvas> , and happens to <canvas> have a .toDataURL() method.

Everything has, we just need to put the acquired image into the <canvas> .toDataURL() method of conversion, we can get Base64 encoded dataurl. Look at the syntax of this method:

canvas.toDataURL([type, encoderOptions]);

The canvas is a DOM element object, the <canvas> parameter type specifies the picture type, and the default value is substituted if the specified type is not supported image/png ; encoderOptions you can image/jpeg set the image/webp picture quality, value 0-1 , or default value 0.92 for a picture or type Alternative.

It is important to note that picture loading is asynchronous, and you must first ensure that the picture is loaded successfully before converting to dataurl, otherwise the canvas may fail to draw immediately, causing the conversion dataurl to fail. .toDataURL()the method should then be written in the onload event to ensure that the canvas's drawing work begins after the picture is downloaded. Fortunately .drawImage() , the method is synchronous, and only after the canvas has been drawn is done, for example .toDataURL() .




Web Upload Photos

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.