Home Web Front-end JS Tutorial JavaScript code to implement image compression

JavaScript code to implement image compression

Aug 22, 2018 am 11:27 AM
Image Compression

The content of this article is about the JavaScript code for image compression. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Without further ado, let’s go straight to the code. What is returned is a base64 string

/**
 * 图片压缩,默认同比例压缩
 * @param {Object} path 
 *   pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 *   obj 对象 有 width, height, quality(0-1)
 * @param {Object} callback
 *   回调函数有一个参数,base64的字符串数据
 */
function dealImage(path, obj, callback){
 var img = new Image();
 img.src = path;
 img.onload = function(){
  var that = this;
  // 默认按比例压缩
  var w = that.width,
   h = that.height,
   scale = w / h;
   w = obj.width || w;
   h = obj.height || (w / scale);
  var quality = 0.7;  // 默认图片质量为0.7
  //生成canvas
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  // 创建属性节点
  var anw = document.createAttribute("width");
  anw.nodeValue = w;
  var anh = document.createAttribute("height");
  anh.nodeValue = h;
  canvas.setAttributeNode(anw);
  canvas.setAttributeNode(anh); 
  ctx.drawImage(that, 0, 0, w, h);
  // 图像质量
  if(obj.quality && obj.quality <= 1 && obj.quality > 0){
   quality = obj.quality;
  }
  // quality值越小,所绘制出的图像越模糊
  var base64 = canvas.toDataURL(&#39;image/jpeg&#39;, quality );
  // 回调函数返回base64的值
  callback(base64);
 }
}
Copy after login

Calling method

// 调用函数处理图片                 
dealImage("路径", {
// 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径(因为用take photo后的图片路径,我没有试成功(如果有人试成功了可以分享一下经验))
 width : 200
}, function(base){
//直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了
 document.getElementById("transform").src = base;
 console.log("压缩后:" + base.length / 1024 + " " + base);    
})
Copy after login

PS: The main idea is After obtaining the image, use H5 canvas technology to convert the image data into a base64 string, and finally transmit it to the background. The background will store the base64 string data as an image.

Related recommendations:

Javascript code sharing to realize provincial and municipal linkage

Javascript code introduction to realize binary tree

The above is the detailed content of JavaScript code to implement image compression. 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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 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)

How to handle image compression when saving remote images using PHP? How to handle image compression when saving remote images using PHP? Jul 15, 2023 pm 03:57 PM

How to handle image compression when saving remote images using PHP? In actual development, we often need to obtain images from the network and save them to the local server. However, some remote images may be too large, which requires us to compress them to reduce storage space and increase loading speed. PHP provides some powerful extensions to handle image compression, the most commonly used of which are the GD library and the Imagick library. The GD library is a popular image processing library that provides many functions for creating, editing and saving images. Here is a use

How to handle image uploading and compression in Vue technology development How to handle image uploading and compression in Vue technology development Oct 08, 2023 am 10:58 AM

How to handle image uploading and compression in Vue technology development In modern web applications, image uploading is a very common requirement. However, due to network transmission and storage reasons, directly uploading original high-resolution images may result in slow upload speeds and a large waste of storage space. Therefore, uploading and compressing images is very important. In Vue technology development, we can use some ready-made solutions to handle image uploading and compression. The following will introduce how to use vue-upload-comone

How to implement image compression function in uniapp How to implement image compression function in uniapp Jul 06, 2023 pm 05:16 PM

How to implement image compression function in uniapp 1. Introduction In modern society, pictures have become an indispensable part of people's daily lives. However, with the popularization of mobile phone camera functions and the improvement of photo pixels, the file size of pictures is also growing. This will not only occupy the phone's memory, but also cause the image to take a long time to load during network transmission. Therefore, image compression has become one of the important tasks for developers. 2. Image compression in uniapp uniapp is a cross-platform development framework based on Vue.js

Use uniapp to implement image compression function Use uniapp to implement image compression function Nov 21, 2023 pm 06:36 PM

Using uniapp to realize image compression function With the improvement of mobile phone camera functions, we often take a large number of photos in our daily life. However, these high-resolution photos take up storage space on your phone, making it slow and easy to fill up. In order to solve this problem, we can use the relevant technology in uniapp to implement the image compression function, compress the image to a smaller file size, and retain appropriate pixels and image quality. Below we will introduce in detail how to implement the image compression function in uniapp. Step 1: Introduce relevant

Java development skills revealed: implementing image compression and cropping functions Java development skills revealed: implementing image compression and cropping functions Nov 20, 2023 pm 03:27 PM

Java is a programming language widely used in the field of software development. Its rich libraries and powerful functions can be used to develop various applications. Image compression and cropping are common requirements in web and mobile application development. In this article, we will reveal some Java development techniques to help developers implement image compression and cropping functions. First, let's discuss the implementation of image compression. In web applications, pictures often need to be transmitted over the network. If the image is too large, it will take longer to load and use more bandwidth. therefore, we

How to deal with the compression and optimization of image resources in Vue technology development How to deal with the compression and optimization of image resources in Vue technology development Oct 09, 2023 pm 08:27 PM

How to handle the compression and optimization of image resources in Vue technology development Summary: With the continuous development of front-end development, images in web pages occupy an increasingly important position. However, too many image resources will cause the page to load slowly and affect the user experience. In order to solve this problem, this article will introduce how to use the compression and optimization method of processing image resources in Vue development, and give specific code examples. 1. Image compression Manual compression Manual compression is the most common method. You can use various image processing software, such as Photoshop, S

How to use Node for image compression How to use Node for image compression Mar 20, 2023 pm 06:22 PM

How to use Node for image compression? The following article uses PNG images as an example to introduce how to compress images. I hope it will be helpful to you!

How to use image compression to reduce page loading time and improve the access speed of Java websites? How to use image compression to reduce page loading time and improve the access speed of Java websites? Aug 06, 2023 pm 06:58 PM

How to use image compression to reduce page loading time and improve the access speed of Java websites? In the modern Internet era, website loading speed is crucial to user experience and SEO rankings. In web content, images usually occupy a large part of the content. Therefore, image optimization and compression is an important means to improve website access speed. Java, as a programming language widely used in website development, has the ability to handle image compression. Below, we will introduce how to use Java to compress images and reduce page size.

See all articles