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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

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 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

The development trend and future prospects of Canvas in China's education sector The development trend and future prospects of Canvas in China's education sector Jan 17, 2024 am 10:22 AM

With the rapid development of science and technology and the widespread application of information technology in the field of education, Canvas, as a world-leading online learning management system, is gradually emerging in the Chinese education industry. The emergence of Canvas provides new possibilities for the reform of education and teaching methods in China. This article will explore the development trends and prospects of Canvas in China’s education sector. First of all, one of the development trends of Canvas in China’s education sector is in-depth integration. With the rapid development of cloud computing, big data and artificial intelligence, Canvas will increasingly

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.​

How to correctly understand the differences between packaging and compression in Linux How to correctly understand the differences between packaging and compression in Linux Feb 20, 2024 pm 05:33 PM

Packaging and compression are commonly used operations in Linux, but many users tend to confuse the two concepts. This article will discuss the differences between packaging and compression in Linux systems in detail, and use specific code examples to help readers better understand. First, we need to clarify the difference between packaging and compression. Packaging is the combination of multiple files or directories into a single file, often used to organize, archive, or transfer files. Compression is to compress one or more files through an algorithm to reduce the size of the file, save storage space or speed up the transmission.

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

See all articles