Home Web Front-end JS Tutorial JS and Canvas implement image preview, compression and upload functions

JS and Canvas implement image preview, compression and upload functions

May 28, 2018 am 10:30 AM
canvas javascript compression

This article mainly introduces JS and Canvas to implement the image preview, compression and upload function. There are roughly two steps to implement this function. The first step is for the user to select the image that needs to be uploaded. The second step is to obtain the image resource, compress the preview and upload it. Specifically Please refer to this article to implement the code.

Let’s take a look at the renderings first to calm down the shock.

The first step: the user selects the image to be uploaded

<input type="file" accept="image/*" type="file"" name="imageFile" onchange="upload()">
Copy after login

After the image is selected, the upload function will be triggered. In this function, we need to obtain the resource of the image, compress it and draw it using canvas. If we need to upload it to the server, we can also use ajax or other methods. Upload.

Second step: Get the compressed preview of the image resource and upload it

function upload() { 
  let file = document.querySelector(&#39;input[type=file]&#39;).files[0] // 获取选择的文件,这里是图片类型 
  let reader = new FileReader() 
    reader.readAsDataURL(file) //读取文件并将文件以URL的形式保存在resulr属性中 base64格式 
    reader.onload = function(e) { // 文件读取完成时触发  
      let result = e.target.result // base64格式图片地址  
      var image = new Image() image.src = result // 设置image的地址为base64的地址  
      image.onload = function(){  
        var canvas = document.querySelector("#canvas");  
        var context = canvas.getContext("2d");  
        canvas.width = image.width; // 设置canvas的画布宽度为图片宽度  
        canvas.height = image.height;  
        context.drawImage(image, 0, 0, image.width, image.height) // 在canvas上绘制图片  
        let dataUrl = canvas.toDataURL(&#39;image/jpeg&#39;, 0.92) // 0.92为压缩比,可根据需要设置,设置过小会影响图片质量  
                                  // dataUrl 为压缩后的图片资源,可将其上传到服务器  
      }  
    } 
 }
Copy after login

Now let’s compare whether the image is successfully compressed:

Original image size:

The compression ratio is set to 0.92:

The compression ratio is set to 0.52

At first glance, do you think it’s strange why the image is larger than the original image when the zoom ratio is set to 0.92? In fact, after the image is encoded by base64, it will become larger than the original image. For specific reasons, you can check the encoding principle of base64. It seems that we have successfully compressed the image!

Note: Canvas is not supported below IE9; try not to use base64 for large pictures, which will affect the response speed.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JavaScript step by step implementation of a regular expression of date of birth

Tutorial on using Vue to develop dynamic refresh Echarts components Detailed explanation

Example of how to use the selectpicker drop-down box in bootstrap

The above is the detailed content of JS and Canvas implement image preview, compression and upload functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

7-zip maximum compression rate setting, how to compress 7zip to the minimum 7-zip maximum compression rate setting, how to compress 7zip to the minimum Jun 18, 2024 pm 06:12 PM

I found that the compressed package downloaded from a download website will be larger than the original compressed package after decompression. The difference is tens of Kb for a small one and several dozen Mb for a large one. If it is uploaded to a cloud disk or paid space, it does not matter if the file is small. , if there are many files, the storage cost will be greatly increased. I studied it specifically and can learn from it if necessary. Compression level: 9-Extreme compression Dictionary size: 256 or 384, the more compressed the dictionary, the slower it is. The compression rate difference is larger before 256MB, and there is no difference in compression rate after 384MB. Word size: maximum 273 Parameters: f=BCJ2, test and add parameter compression rate will be higher

Tips to reduce win10 screen recording file size Tips to reduce win10 screen recording file size Jan 04, 2024 pm 12:05 PM

Many friends need to record screens for office work or transfer files, but sometimes the problem of files that are too large causes a lot of trouble. The following is a solution to the problem of files that are too large, let’s take a look. What to do if the win10 screen recording file is too large: 1. Download the software Format Factory to compress the file. Download address >> 2. Enter the main page and click the "Video-MP4" option. 3. Click "Add File" on the conversion format page and select the MP4 file to be compressed. 4. Click "Output Configuration" on the page to compress the file according to the output quality. 5. Select "Low Quality and Size" from the drop-down configuration list and click "OK". 6. Click "OK" to complete the import of video files. 7. Click "Start" to start the conversion. 8. After completion, you can

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to compress a folder and send it in wps How to compress a folder and send it in wps Mar 20, 2024 pm 12:58 PM

Office workers use wps software very frequently at work. Sometimes they input multiple files a day and then send them to the leader or to a designated location. So how does wps software compress a folder and package it for sending? The editor below will teach you. This operation step. First, organize the files and folders you want to send into the same folder. If you have a lot of files, it's a good idea to name each file so it's easier to identify when sending. Second step, this time click on this large folder and then right-click. Select &quot;Add to archive&quot;. Step 3: At this time, the software will automatically help us package our files. Select &quot;Compress to XX.zip&quot;. This zip is the packaging format, and then click Compress Now.​

winrar 64-bit-How to decompress winrar? winrar 64-bit-How to decompress winrar? Mar 18, 2024 pm 12:55 PM

WinRAR is a powerful compressed file management tool that provides rich features and an easy-to-use interface. WinRAR 64-bit version is specially optimized for 64-bit operating systems and can better utilize system resources and performance. Next, let the editor introduce you to winrar 64-bit and explain how to decompress winrar! 1. What is winrar 64-bit software? WinRAR is a powerful compressed package manager. This software can be used to back up your data, reduce the size of email attachments, decompress RAR, ZIP and other files downloaded from the Internet, and create new files in RAR and ZIP formats. The latest WINRAR version is Wi

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

See all articles