Get the App
SLTechnology News&Howtos  ›  Development  › 

How to upload canvas compressed pictures in front-end development

Shulou Source: shulou.com Published: 2022-06-01 11:35:25 09月27日 Update

This article introduces the relevant knowledge of "how to upload canvas compressed pictures in front-end development". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First of all, there must be an upload button.

Let's get to the point:

UploadFile:function (event) {let file = event.target.files [0]; / / get the image file value of input let param = new FormData () / / create form object if (param.getAll ('file') [0] = = "undefined") {return false / / determine whether it is empty} let reader = new FileReader () reader.readAsDataURL (file) / / read the file and save the file in base64 format in the resulr attribute in URL format, the online document seems to specify the format. I chose a base64 reader.onload = function (e) {/ / file read to trigger let result = e.target.result / / base64 format picture address var image = new Image () image.src = result / / set the address of image to base64 image.onload = function () {var canvas = document.getElementById ("canvas"); var context = canvas.getContext ("2d") Canvas.width = image.width; / / set the canvas width of canvas to picture width canvas.height = image.height Context.drawImage (image, 0,0, image.width, image.height) / / draw a picture on canvas let dataUrl = canvas.toDataURL ('image/jpeg', 0.001) / / set the compression ratio, which can be set as needed. Setting too small will affect the picture quality, and dataUrl is the compressed picture resource. You can upload it to the server let tupian = _ this.dataURLtoFile (dataUrl, file.name) param.append ('file', tupian) / / corresponding to the picture name received in the background / / then you can write the axios method here. To upload this param to the background} the content of "how to upload canvas compressed images in front-end development" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Picture address file format front end development content background width more knowledge practical successful learning next dilemma picture resources actual objects attributes form Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn MariaDB Shulou Information macOS