Scales and upload images by Canvas and File APIs

How to zoom and upload a picture through the Canvas and File API? This issue may be often seen in our daily study or work. I hope that you can give you a deep harvest through this issue. Below is the reference content brought by Xiaobian, let’s take a look!

Create a user interface and allow you to control the size of the picture. Uploaded to the server-side data, do not need to handle encType for multi-part / form-data, just a simple POST form handler. Ok, here is attached to the complete code example: Canvas Resize Demo
Original Date: August 6, 2013
Translation Date: August 8, 2013

Tom Trenka can write for “I” blog An article, is a huge honor for me. Tom is one of the initial contributors of the Dojo framework. It is also a good friend of Sitepen. I have witnessed his top genius capabilities, and he is always the first forward-looking solution to foresee a lot of tricky problems. He always thinks about the foreigners, breaking the routine but resolves the edge problem. This article is a perfect illustration.

Recently, I always asked to create a user interface API, allowing users to upload pictures to the server (with other things), and can be used on the client of our company with a large number of websites supported. Usually this is very easy – create an Form form, add a file type INPUT input box, let the user select the picture from the computer, and set the eNCTYPE = “Multipart / Form-Data” form on the Form tab Property, then uploading. Very simple, isn’t it? In fact, there is a sufficiently simple example; click to enter
, if you want to pre-process the picture in advance, what should I do? For example, you have to compress the picture size, or you need pictures that can only be some types of formats, such as PNG or JPG, what do you do?
Solved with Canvas!

Canvas Introduction canvas is a new HTML5 DOM elements, allowing the user to directly draw graphics on the page, typically use JavaScript. Differs format standards are different, such as SVG is a grating API (raster API) and VML is a vector API (vector API). consider using Adobe Illustrator (vector) mapping the difference between using Adobe Photoshop (raster) mapping.

On Canvas (canvas) can do is to read and render the image, and allows you to manipulate the image data using JavaScript. There are already many existing articles to demonstrate basic image processing for you – and focus on a variety of image filtering techniques (image filtering techniques) – but we just need to scale the image and convert it to a specific file format, canvas can do these things.

We assume that demand, such as the image height does not exceed 100 pixels, no matter how high the original image. The basic code as follows:

 // parameter, the maximum height var MAX_HEIGHT = 100; // Render function render (src) {// create a Image object var image = new Image (); // bind load event handler, loading image.onload = function performed after completion () {// get the canvas DOM objects var canvas = document.getElementById ( "myCanvas"); // if the height exceeded if (image .height> MAX_HEIGHT) {// width scaling * = image.width * = MAX_HEIGHT / image.height; image.height = max_height;} // Get the CANVAS 2D environment object, // can understand that CONTEXT is an administrator, canvas is a house var ctx = canvas.getContext ("2D"); // canvas clear screen CTX.CleArRect (0, 0, canvas.width, canvas.height); // Reset canvas wide high canvas.width = image.width; canvas.Height = image.Height; // Draw image to CTX.DrawImage on Canvas (Image, 0, 0, image.width, image.height; // !!! Note that image is not added to the DOM}; // Setting the src property, the browser will automatically load. / / Remember that the event must be bound before you can set the SRC property, otherwise you will be synchronized. Image.SRC = SRC;};  In the above example, you can use the canvas's TodataURL () method to get the base 64 encoded value of the image (can be similar to 16) String, or binary data stream).  Note: The URL of Canvas's TodataURL () is started with a string, with 22 useless data "data: image / png; base64,", need to serve or serve Filtering. 
In principle, as long as the browser supports, the length of the URL address is not limited, and the length of the 1024 is unique to the older generation IE.

How do I get the image we need?
Good boy, I am very happy that you can ask. You cannot directly process the File input box, and you can get the Path path of the user selected file from this file. According to routine imagination, you can pass this PThe ATH path information is loaded, but this is unrealistic in the browser. (Translator Note: Browser manufacturers must ensure that their browser is absolutely safe, in order to get the market, at least avoid media attacks, if this is allowed, the malicious URL can try to obtain some sensitive information by patching the file path).
In order to achieve this requirement, we can use the File API of HTML5 to read files on the user disk, and use this file as an image source (SRC, SOURCE).


File API Introduction

The new File API interface is a way to read and list the user file directory without violating any safety sandbox rules – the malicious website cannot write virus through the sandbox restriction. User disk, of course, can not be executed.

We want to use the file read object called FileReader, FileReader allows developers to read the contents of the file (the implementation of the specific browser may be large). Suppose we have obtained the path path of the image file, depending on the previous code, using FileReader to load and rendering the image is very easy:

/ / Load Image File (URL Path) Function LoadImage (src) {// Filter off the non-image type file if (! Src.type.match (/ image. * /)) {If (window.console) {Console.log (“The selected file type is not a picture:”, src.type);} else {window.confirm (“You can only select the image file”);} return;} // Create a FileReader object and call the render function to complete the rendering. Var Reader = new fileReader (); // Binding load event auto-callback function reader.onLoad = FunctioN (e) {// Call the front RENDER function render (e.target.result);}; // read file content reader.readAsDataURL (src);};

 Excuse me, how to get a file?  Little white rabbit, must be patient! Our next step is to get the file, of course, many ways can be realized. For example: You can use the text box to enable the user to enter the file path, but it is clear that most users are not developers, I don't know what to import.  For users easy to use, we use the Drag and Drop API interface. 

Drag and Drop API

Drag and DROP) is very simple – on most DOM elements, you can process the processor by binding event Implementation. As long as the user drags a file from the disk to the DOM object and release the mouse, then we can read this file. The code is as follows:

function init () {// Get the DOM element object var target = document.getlementByid (“Drop-Target”); // Block DragOver (drag to the DOM element ) Event transfer target.addeventListener (“Dragover”, Function (E) {E.PREVENTDEFAULT ();}, true); // Drag and release the mouse event targetListener (“DROP”, Function (E) { / / Block the default event, as well as the event propagation E.PREVENTDEFAULT (); // call the previous load image function, the parameter is the first file of the DataTransfer object (E.DataTransfer.Files [0]);}, True); var setheight = document.getElementById ( “setheight”); var maxheight = document.getElementById ( “maxheight”); setheight.addEventListener ( “click”, function (e) {// var value = maxheight.value ; if (/ ^ \ d + $ /. Test (value) {max_height = parseint (value);} E.PREVENTDEFAULT ();}, true); var btnsend = document.GtelementByid (“btnsend”); btnsend.addeventListener (“Click”, Function (E) {// sendimage ();}, true);}; We can also do some other processing, such as displaying a preview. But if you don’t want to compress the picture, it is likely to use it. We will use AJAX to upload image data through the POST of HTTP. The following example is to use the Dojo framework to complete the request, of course, you can also use other AJAX technology to implement .. Dojo code is as follows:

// The translator does not understand Dojo, so attach jQuery’s implementation // Remember That DTK 1.7+ IS AMD! Require ([“Dojo / Request”], Function (Request) {// Setup URL, parameter, and callback. Request.post (“Image-handler.php”, {data: {imagename: “MyimAge.png “, imagedata: encodeuricomponent (” canvas “). TodataURL (” Image / PNG “)}})})})}. Then (” The Server Returned: “, TEXT );});}); jQuery is achieved as follows:
   
// Upload pictures, jQuery version function sendimage () {// Get the Canvas DOM object var canvas = document.getlementByid (“mycanvas”); // Get base 64 encoded image data, format is string // “data: image / PNG; base64,” start, need to be on the client or server The end will be removed, the back portion can be written directly into the file. Var dataURL = canvas.todataURL (“image / png”); / / to secure the URI // DATA% 3AIMAGE% 2FPNG% 3BBase64% 2C started VAR imagedata = EncodeuriComponent (dataURL); // var URL = $ (“# form”). Attr (“action”); // 1. If the Form form is not good, you can use a Hidden hidden domain to set the request address //// VAR URL = $ (“INPUT [Name = ‘Action’). Val (); // 2. You can also get //

// var URL = directly with the properties of a DOM object. $ (“# ImageAction”). Attr (“ACTI”); // Because it is string, the server needs to transfer the data, write file operations, etc. // Personal agreement, all HTTP parameter names all lowercase console.log (dataurl); //console.log (ImageData) Var data = {imagename: “MyImage.png”, imagedata: imagedata}; jQuery.ajax ({URL: URL, DATA: DATA, TYPE: “post”, // expected return value type DataType: “json”, Complete: function (xhr, result) {//console.log (xhr.responsext); var $ tip2 = $ (“# tip2”); if (! xhr) {$ tip2.text (‘network connection failed!’) Return False;} var text = xhr.responsetext; if (! text) {$ TIP2.TEXT (‘network error!’); returnaf = Eval (“(” + text + “)”); if (! json) {$ tip2.text (‘parsing error!’); return false;} else {$ tip2.text (json.Message);} //console.dir(json); ///console.log(xhr .responsetext);}});};

OK, get it! You still need to do it, just create a user interface and allow you to control the size of the picture. Upload to The server-side data does not need to handle ENCTYPE for Multi-Part / Form-DataIn the case of just a simple POST form handler.

Ok, there is a complete code example:

   

     // parameter, maximum height Var max_height = 100; // Rendering Function Render (src) {// Create a image object var image = new image (); // Bind the load event processor, execute image.onload = function () after loading is complete () {/ / Get Canvas DOM object var canvas = document.getlementByid ("mycanvas"); // If the height exceeds the standard IF (Image.Height> max_height) {// width is equivalent to scale * = image.width * = max_height / image.height; Image.height = max_height;} // Get the CANVAS 2D environment object, // You can understand that CONTEXT is an administrator, canvas is a house var ctx = canvas.getContext ("2D"); // canvas clear screen CTX.CleArRect (0) , 0, canvas.width, canvas.height); // Reset canvas wide high canvas.Width = image.width; canvas.height = image.Height; // Draw images to CANCTX.drawImage (Image, 0, 0, Image.width, Image.height); // !!! Note that image is not added to the DOM}; // Setting SRC properties, the browser will load. / / Remember that the event must be bound before you can set the SRC property, otherwise you will be synchronized. Image.src = src;}; // Load Image File (URL Path) Function LoadImage (src) {// Filter Filter File IF (! src.type.match (/ image. * /)) {IF (Window.console) {Console.log ("Selected file type is not a picture:", src.type);} else {window.confirm ("You can only select image file");} return;} // Create a FileReader object And call the render function to complete the rendering. Var reader = new fileReader (); // Bind the load event auto callback function Reader.onLoad = function (e) {// Call the front RENDER function render (e.target.result); }; // Read file content reader.readAsDataURL (src);}; // upload picture, jQuery version function sendimage () {// Get Canvas Dom object var canvas = document.getlementByid ("mycanvas"); // Get The image data encoded after Base64, the format is the string // "data: image / png; base64," start, you need to remove it on the client or server, the back part can be directlyWrite files. Var dataURL = canvas.todataURL ("image / png"); // to encode // DATA% 3AIMAGE% 2FPNG% 3BBase64% 2C = Encodeuricomponent ("); // var URL = $ (" #form "). Attr (" action "); // 1. If the Form form is not good, you can use a Hidden hidden domain to set the request address // 
var URL = $ (” INPUT [NAME = ‘ Action ‘] “). VAL (); // 2. You can also use the properties of a DOM object to get // // var URL = $ (” # ImageAction “). Attr (” Action “) ; // Because it is string, the server needs to transcode the data, write file operations, and more. // Personal conventions, all HTTP parameter names are written on console.log (data); //console.log (Imagedata); var data = {imagename: “MyImage.png”, imagedata: imagedata}; jQuery.ajax ({URL : URL, DATA: DATA, TYPE: “post”, // expected return value type DATATYPE: “json”, completion: function (xhr, result) {//console.log (xhr.responsetext); var $ tip2 = $ (“# tip2”); if (! xhr) {$ TIP2.TEXT (‘network connection failed!’); returnaf;} var text= Xhr.ResponseText; if (! text) {$ TIP2.TEXT (‘network error!’); return false;} var json = evAl (“(+ text +”) “); if (! json) {$ TIP2 .text (‘parsing the error!’); return false;} else {$ tip2.text (json.Message);} //console.dir(json); //console.log (xhr.ResponseText);}}) }; function init () {// Get the DOM element object var target = document.getlementByid (“DROP-TARGET”); // Block Dragover from the top of the DOM element) Event Pass Target.adDeventListener (“Dragover”, Function (e) {E.PREVENTDEFAULT ();}, true); // Drag and release the mouse event targetListener (“DROP”, Function (e) {// block the default event, and event propagation E.PREVENTDEFAULT (); // Call the previous load image function, parameter is the first file of the DataTransfer object loadImage (E.DataTransfer.Files [0]);}, true); var setHeight = document.getlementByid (“setHeight”); Var maxheight = document.getlementByid (“maxHeight”); setHeight.AddeventListener (“Click”, Function (e) {// var value = maxheight.value; if (/ ^ \ d + $ /. test (value)) {max_height = parseint (value);} E.PREVENTDEFAULT ();}, true); var btnsend = Document.GtelementByid (“btnsend”); btnsend.addeventListener (“click”, Function (E) {// sendimage ();}, true);}; window.addeventListener (“DomconTentLoaded”, function () {//


  Zooms and uploaded by Canvas and File APIs   Drag a photo from the folder to below In the box, Canvas and JavaScript will automatically scales.   Set the maximum height of the picture      Drag the picture file here       Thumbnail:      

Service end page, Receive.jsp

{"Message": "

", "Success":

} Thank you for reading! After reading the above, do you know about the method of zooming and uploading a picture through the Canvas and File API? I hope that the content of the article will help everyone. If you want to know more about the content, please pay attention to Tumi Yun Industry Information Channel.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment