Home Web Front-end JS Tutorial Js uses Canvas to compress images to explain the method

Js uses Canvas to compress images to explain the method

Sep 15, 2017 am 09:24 AM
canvas javascript compression

The following editor will bring you an article using JS to implement image compression function using Canvas. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

The APP project I recently worked on involves taking photos and uploading pictures with mobile phones. Because the pictures taken by mobile phones are usually relatively large, uploading will be very slow. For this reason, images need to be compressed to optimize the upload function. The following is the specific implementation:


/* 
 * 图片压缩
 * img    原始图片
 * width   压缩后的宽度
 * height  压缩后的高度
 * ratio   压缩比率 
 */
 function compress(img, width, height, ratio) {        
   var canvas, ctx, img64;
        
   canvas = document.createElement('canvas');        
   canvas.width = width;
   canvas.height = height;
        
   ctx = canvas.getContext("2d");        
   ctx.drawImage(img, 0, 0, width, height);
        
   img64 = canvas.toDataURL("image/jpeg", ratio);
        
   return img64;
 }
Copy after login

The above is an image compression function that returns image data in base64 format. The larger the compression ratio value (between 0 and 1), the higher the picture quality. It is recommended not to convert the image to png format, because the base64 of the image is much longer than that of jpeg. The following is the actual call:


var image = new Image();
image.src = "/img/test.jpg";
      
image.onload = function(){
  var img64 = compress(image, 500, 400, 0.7);
  document.getElementById("test").src = img64;
}
Copy after login

Note: The call to the compression method and the image src assignment must be placed in the onload method of the image in. Because only after the image is loaded can it be compressed and converted to base64 for assignment. If placed outside the onload method, the compression code may be invalid, or a pure black image may be generated.

The above is the detailed content of Js uses Canvas to compress images to explain the method. 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 "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.​

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

Centos 7 compression and decompression command overview Centos 7 compression and decompression command overview Dec 31, 2023 pm 09:02 PM

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

See all articles