js and canvas implement image preview compression upload
This article mainly shares the method of compressing and uploading image previews with js and canvas, combined with the example code and explanation, I hope it can help everyone.
Step 1: The user selects the image to be uploaded
<input type="file" accept="image/*" type="file"" name="imageFile" onchange="upload()">
After the image is selected, the upload function will be triggered. We need to obtain the resource of the image in this function and transfer it Compress and draw it using canvas. If you need to upload it to the server, you can also use ajax or other methods to upload it.
Second step: Get the compressed preview of the image resource and upload it
function upload() { let file = document.querySelector('input[type=file]').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('image/jpeg', 0.92) // 0.92为压缩比,可根据需要设置,设置过小会影响图片质量 // dataUrl 为压缩后的图片资源,可将其上传到服务器 } } }
Now let’s compare whether the image is successfully compressed:
Original image size:
Compression The 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 zoom ratio is set to 0.92, but the picture is actually smaller than The original picture is big? 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.
Related recommendations:
php uploads files to the server and implements image preview
The above is the detailed content of js and canvas implement image preview compression upload. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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 "Add to archive". Step 3: At this time, the software will automatically help us package our files. Select "Compress to XX.zip". This zip is the packaging format, and then click Compress Now.

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

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

1.Zip file compression syntax: zip plus the compressed file name plus the file name to be compressed. [root@localhost~]#ziptest.ziptest.txtadding:test.txt(deflated100%)[root@localhost~]#The percentage number of the progress bar appearing after it indicates that it has been compressed. Then you can verify it in ll to see if it has your name. file package. [root@localhost~]#llTotal usage 820004-rw-------.1rootroot1587 March 2216:58anaconda-ks.cfg-rw-r--r--.1ro

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
