Canvas-todataurl () Convert picture to Dataurl (base64)

Source: Internet
Author: User
Tags base64
the benefits of converting pictures into base64


converting a picture to BASE64 encoding allows you to easily insert a picture into another Web page or editor without uploading a file. This is extremely handy for small pictures because you don't need to look for a place to save pictures.



convert the picture to Base64 encoded, on the web on the general use of small pictures, not only can reduce the number of requests for pictures (set to JS, CSS code), but also to prevent some relative paths and other problems caused by the picture 404 error.



An application scenario: For some special reasons from the server request to the picture path, require the path to obtain the corresponding picture base64 Dataurl. a complete Datauri should be like this:



Data:[<mediatype>][;base64],<data>


Where mediatype declares the file type, follows the MIME rules, such as "Image/png", "Text/plain", and then the encoding type, where we only involve Base64, followed by the file-encoded content. We often see in HTML the img tag src will write this:


Src= "data:image/gif;base64,r0lgoddhmaawapaaaaaaap/// ywaaaaamaawaaac8iypqcvt3wccdkilc7c0qwyghhswpjqu5yqmcysapyuvuulvonmoztfzgfzbytb10qgxor0tqbqejhrnzofkvj+ 5yiuqrxf5y5lkh/deuncp5ylwgsebtliospa/ Tpg7jpjhxyendzwtbfx0cxonkpjgbzi4diinwgdkf8kjdfnycqzxzeygejmjlzegl9i2icvqanvailt6f5ij90m6mvuts4ok05m0vdk0q4xutwvkozrcd3iq9 Uisf81m1oicr7leewwclp7tunnkm3unna3f2jqfo97vriy/xl4/f1cf5vwzxyym7phhhx4dbgykaaa7 "

 


This img refers to the Base64 encoded Dataurl, as long as the browser support, you can be decoded into GIF images and rendering. or use in CSS:
Background-image:url ("data:image/png;base64,ivborw0kggo= ..."); Solution:



FileReader objects also have a similar approach, such as. Readasdataurl (), however, it only accepts file or BLOB types, which are generally only available through the Files property of the <input[type=file]> element. Or create a new object manually with the Blob () constructor. The awkward thing is that we currently have only picture paths, which are subject to the browser's security policy,<input[type=file]> the Files property is read-only, and the Blob () constructor accepts only the contents of the file, neither of which can be directly obtained through the picture path. The scenario above assumes that we must first consider how to get the picture content through the path. is OK, and can be drawn to <canvas>, and <canvas> happens to have the. Todataurl () method.



Solution One: Canvas-todataurl ()



Put the captured picture inside and then through the Todataurl () method to get the Base64 encoded Dataurl.



Canvas.todataurl ([Type, encoderoptions]);


Canvas is a DOM element <canvas> object; parameter type specifies the type of picture and replaces the default value image/png if the specified type is not supported; Encoderoptions can be image/jpeg or image/ The WEBP type of picture sets the picture quality, takes a value of 0-1, and exceeds the default value of 0.92 instead.



Note that you must first ensure that the picture is loaded successfully before converting to Dataurl, so the. Todataurl () method should be written in the OnLoad asynchronous event for . Now implement a functional function:



function getBase64 (URL) {
        //an IMG instance created by the constructor, which downloads the picture immediately after giving the SRC value, avoids the createelement () creation  eliminates the append (). Document redundancy and pollution
        var Img = new Image (),
            dataurl = ';
        img.src = URL;
        Img.onload = function () {//to first ensure that the picture is fully fetched, this is an asynchronous event
            //Create canvas element
            var canvas = document.createelement ("Canvas"), 
            width = img.width,//ensure canvas size and picture as
            height = img.height;
            Canvas.width = width;
            canvas.height = height;
            Canvas.getcontext ("2d"). DrawImage (Img, 0, 0, width, height); Draw the picture into canvas
            Dataurl = Canvas.todataurl (' image/jpeg ');//Convert picture to Dataurl
        };
        return dataurl;
    }
problems accessing a picture across domains:


Error: uncaught securityerror:failed to execute ' todataurl ' in ' htmlcanvaselement ': Tainted canvases May is exported.



Canvas drawing pictures, because of the security of the browser, if you use the canvas drawing process, using the image resources in Outland, then the Todataurl () will throw a security exception :



solution 1.



If you want to use Todataurl () to generate a picture file, the picture used in the canvas drawing should be under the current field.



Solution 2.



① access servers allow resources to be used across domains, that is, set up cors cross-domain configuration , Access-control-allow-origin



② then when the client accesses the image resource



var img = new Image ();
Img.setattribute (' Crossorigin ', ' Anonymous ');
img.src = URL;








Reference Link: http://www.jianshu.com/p/17d7e5ddf10a
http://blog.csdn.net/jia20003/article/details/8948005
http://imgbase64.duoshitong.com/

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.