Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to zoom and upload pictures through Canvas and File API

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to zoom and upload pictures through Canvas and File API", the content in the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "how to zoom and upload pictures through Canvas and File API"!

Introduction to Canvas

Canvas is a new DOM element in HTML5 that allows users to draw graphics directly on the page, usually using JavaScript. Different format standards are also different, for example, SVG is raster API (raster API) and VML is vector API (vector API). You can consider the difference between using Adobe Illustrator (vector graphics) and Adobe Photoshop (raster graphics).

All you can do on canvas (canvas) is to read and render images and allow you to manipulate image data through JavaScript. There are many existing articles to demonstrate basic image processing-- focusing on different image filtering techniques (image filtering techniques)-- but all we need is to zoom the image and convert it to a specific file format, and canvas can do that.

Our hypothetical requirements, such as an image height of no more than 100 pixels, no matter how high the original image is. The basic code is as follows:

The code is as follows:

/ / Parameter, maximum height

Var MAX_HEIGHT = 100

/ / render

Function render (src) {

/ / create an Image object

Var image = new Image ()

/ / bind the load event handler, and execute it after loading

Image.onload = function () {

/ / get the canvas DOM object

Var canvas = document.getElementById ("myCanvas")

/ / if the height exceeds the standard

If (image.height > MAX_HEIGHT) {

/ / proportional scale of width * =

Image.width * = MAX_HEIGHT / image.height

Image.height = MAX_HEIGHT

}

/ / get the 2d environment object of canvas

/ / it is understandable that Context is the administrator and canvas is the house

Var ctx = canvas.getContext ("2d")

/ / canvas clear the screen

Ctx.clearRect (0,0, canvas.width, canvas.height)

/ / reset canvas width and height

Canvas.width = image.width

Canvas.height = image.height

/ / draw the image to canvas

Ctx.drawImage (image, 0,0, image.width, image.height)

/ /! Note that image is not added to the dom

}

/ / set the src property, and the browser will load it automatically.

/ / remember that events must be bound before the src property can be set, otherwise synchronization problems will occur.

Image.src = src

}

In the above example, you can use canvas's toDataURL () method to get the Base64-encoded value of the image (similar to hexadecimal strings, or binary data streams).

Note: the URL obtained by toDataURL () of canvas begins with a string and has 22 pieces of useless data _ "data:image/png;base64," which need to be filtered on the client or server.

In principle, as long as the browser supports it, there is no limit to the length of URL addresses, and the 1024 length limit is unique to the older generation of IE.

Excuse me, how to get the image we need?

Good boy. I'm glad you asked. You can't handle this directly through the File input box, all you can get from this file input box element is the path path of the file selected by the user. According to the conventional imagination, you can load the image through this path path information, but this is not realistic in the browser. (translator's note: browser manufacturers must ensure the absolute security of their browsers in order to gain access to the market, at least to avoid media attacks, and if this is allowed, malicious URLs can try to obtain some sensitive information by piecing together file paths.

To achieve this requirement, we can use HTML5's File API to read files on the user's disk and use this file as the src,source of the image.

Introduction to File API

The new File API interface is a way to read and list user file directories without violating any safe sandboxie rules-- through the restriction of sandboxie (sandbox), malicious websites cannot write viruses to users' disks, let alone execute them.

The file read object we are going to use is called FileReader,FileReader, which allows developers to read the contents of the file (the implementation of specific browsers may be very different).

Assuming that we have obtained the path path of the image file, it is easy to load and render the image using FileReader, depending on the previous code:

The code is as follows:

/ / load image file (url path)

Function loadImage (src) {

/ / filter out files of non-image type

If (! src.type.match (/ image.*/)) {

If (window.console) {

Console.log ("the selected file type is not Picture:", src.type)

} else {

Window.confirm ("can only select picture files")

}

Return

}

/ / create a FileReader object and call the render function to complete the rendering.

Var reader = new FileReader ()

/ / bind load event automatic callback function

Reader.onload = function (e) {

/ / call the previous render function

Render (e.target.result)

}

/ / read the contents of the file

Reader.readAsDataURL (src)

}

Excuse me, how can I get the documents?

White rabbit, be patient! Our next step is to get the file, and of course there are many ways to do it. For example, you can use text boxes to ask users to enter file paths, but obviously most users are not developers and have no idea what values to enter.

For the convenience of users, we use Drag and Drop API interface.

Use Drag and Drop API

The drag-and-drop interface (Drag and Drop) is very simple-on most DOM elements, you can do this by binding event handlers. As long as the user drags a file from disk onto the dom object and releases the mouse, we can read the file. The code is as follows:

The code is as follows:

Function init () {

/ / get the DOM element object

Var target = document.getElementById ("drop-target")

/ / prevent the dragover (drag above the DOM element) event from passing

Target.addEventListener ("dragover", function (e) {e.preventDefault ();}, true)

/ / the event of dragging and releasing the mouse

Target.addEventListener ("drop", function (e) {

/ / prevent default events and event propagation

E.preventDefault ()

/ / call the previous load image function with the argument to the first file of the dataTransfer object

LoadImage (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.getElementById ("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's probably useless. We will use Ajax to upload image data through HTTP's post method. The following example uses the Dojo framework to complete the request, but you can also use other Ajax technologies to implement it.

The Dojo code is as follows:

The code is as follows:

/ / the translator does not understand Dojo, so the implementation of jQuery will be attached.

/ / Remember that DTK 1.7 + is AMD!

Require (["dojo/request"], function (request) {

/ / set request URL, parameters, and callback.

Request.post ("image-handler.php", {

Data: {

ImageName: "myImage.png"

ImageData: encodeURIComponent (document.getElementById ("canvas") .toDataURL ("image/png"))

}

}) .then (function (text) {

Console.log ("The server returned:", text)

});

});

The jQuery implementation is as follows:

The code is as follows:

/ / upload pictures, jQuery version

Function sendImage () {

/ / get the canvas DOM object

Var canvas = document.getElementById ("myCanvas")

/ / get the Base64-encoded image data in a string format

At the beginning of / / _ "data:image/png;base64,", you need to remove it on the client or server side, and the later part can be written directly to the file.

Var dataurl = canvas.toDataURL ("image/png")

/ / Encoding URI for security

/ / the beginning of data%3Aimage%2Fpng%3Bbase64%2C

Var imagedata = encodeURIComponent (dataurl)

/ / var url = $("# form") .attr ("action")

/ / 1. If the form form is not easy to handle, you can use a hidden hidden field to set the request address

/ /

Var url = $("input [name = 'action']") .val ()

/ / 2. You can also directly 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 files, and so on.

/ / personal convention. All http parameter names are 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.responseText)

Var $tip2 = $("# tip2")

If (! xhr) {

$tip2.text ('Network connection failed!')

Return false

}

Var text = xhr.responseText

If (! text) {

$tip2.text ('Network error!')

Return false

}

Var json = 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! All you need to do is create a user interface that allows you to control the size of the image. Data uploaded to the server does not need to deal with the case where enctype is multi-part/form-data, just a simple POST form processor.

All right, here's a complete code example:

The code is as follows:

Zoom and upload pictures through Canvas and File API

/ / Parameter, maximum height

Var MAX_HEIGHT = 100

/ / render

Function render (src) {

/ / create an Image object

Var image = new Image ()

/ / bind the load event handler, and execute it after loading

Image.onload = function () {

/ / get the canvas DOM object

Var canvas = document.getElementById ("myCanvas")

/ / if the height exceeds the standard

If (image.height > MAX_HEIGHT) {

/ / proportional scale of width * =

Image.width * = MAX_HEIGHT / image.height

Image.height = MAX_HEIGHT

}

/ / get the 2d environment object of canvas

/ / it is understandable that Context is the administrator and canvas is the house

Var ctx = canvas.getContext ("2d")

/ / canvas clear the screen

Ctx.clearRect (0,0, canvas.width, canvas.height)

/ / reset canvas width and height

Canvas.width = image.width

Canvas.height = image.height

/ / draw the image to canvas

Ctx.drawImage (image, 0,0, image.width, image.height)

/ /! Note that image is not added to the dom

}

/ / set the src property, and the browser will load it automatically.

/ / remember that events must be bound before the src property can be set, otherwise synchronization problems will occur.

Image.src = src

}

/ / load image file (url path)

Function loadImage (src) {

/ / filter out files of non-image type

If (! src.type.match (/ image.*/)) {

If (window.console) {

Console.log ("the selected file type is not Picture:", src.type)

} else {

Window.confirm ("can only select picture files")

}

Return

}

/ / create a FileReader object and call the render function to complete the rendering.

Var reader = new FileReader ()

/ / bind load event automatic callback function

Reader.onload = function (e) {

/ / call the previous render function

Render (e.target.result)

}

/ / read the contents of the file

Reader.readAsDataURL (src)

}

/ / upload pictures, jQuery version

Function sendImage () {

/ / get the canvas DOM object

Var canvas = document.getElementById ("myCanvas")

/ / get the Base64-encoded image data in a string format

At the beginning of / / _ "data:image/png;base64,", you need to remove it on the client or server side, and the later part can be written directly to the file.

Var dataurl = canvas.toDataURL ("image/png")

/ / Encoding URI for security

/ / the beginning of data%3Aimage%2Fpng%3Bbase64%2C

Var imagedata = encodeURIComponent (dataurl)

/ / var url = $("# form") .attr ("action")

/ / 1. If the form form is not easy to handle, you can use a hidden hidden field to set the request address

/ /

Var url = $("input [name = 'action']") .val ()

/ / 2. You can also directly 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 files, and so on.

/ / personal convention. All http parameter names are 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.responseText)

Var $tip2 = $("# tip2")

If (! xhr) {

$tip2.text ('Network connection failed!')

Return false

}

Var text = xhr.responseText

If (! text) {

$tip2.text ('Network error!')

Return false

}

Var json = eval ("(" + text+ ")")

If (! json) {

$tip2.text ('parsing 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.getElementById ("drop-target")

/ / prevent the dragover (drag above the DOM element) event from passing

Target.addEventListener ("dragover", function (e) {e.preventDefault ();}, true)

/ / the event of dragging and releasing the mouse

Target.addEventListener ("drop", function (e) {

/ / prevent default events and event propagation

E.preventDefault ()

/ / call the previous load image function with the argument to the first file of the dataTransfer object

LoadImage (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.getElementById ("btnsend")

Btnsend.addEventListener ("click", function (e) {

/ /

SendImage ()

}, true)

}

Window.addEventListener ("DOMContentLoaded", function () {

/ /

Init ()

}, false)

Zoom and upload pictures through Canvas and File API

Drag a photo from the folder to the box below and canvas and JavaScript will automatically zoom.

Set the maximum height of the picture

Drag the picture file here.

Upload

Thumbnail:

Server page, receive.jsp

The code is as follows:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report