Table of Contents
js implements image compression and uploading
Home Web Front-end JS Tutorial How to implement the method of uploading and compressing images in js

How to implement the method of uploading and compressing images in js

Jul 20, 2018 am 11:02 AM
html5 javascript

This article introduces you to the compression of js uploaded images. It has certain reference value. Friends in need can refer to it.

js implements image compression and uploading

Technology used:

  1. canvas related api

  2. Some APIs of html5

Compatibility:

1

h5没发现问题,pc低版本浏览器不支持

Copy after login

Implementation ideas:

  • Monitor the upload of the file field and obtain the original data of the image through the FileReader api

  • Calculate the compressed width and height, and then draw it on the canvas Intercept the compressed data

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

<!DOCTYPE html>

<html lang="en">

 

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

</head>

 

<body>

    <input type="file" id="file">

    <canvas id="canvas"></canvas>

</body>

 

</html>

<script>

    // 兼容性 h5上可以使用,pc低版本浏览器不支持

    // 准备要用到的img和canvas

    var img = new Image(),

        canvas;

    // 创建读取文件对象

    var render = new FileReader();

    // 如果不需要放在页面上,使用js创建该元素就可以了

    // canvas = document.createElement('canvas');

 

    // 找到canvas,准备画图

    var canvas = document.getElementById('canvas');

    var context = canvas.getContext('2d');

 

    var input = document.getElementById('file');

    input.addEventListener('change'function (e) {

        // 通过files获取到当前文件

        var file = e.target.files[0];

        // 如果选择的是图片

        if (file.type.indexOf('image') != -1) {

            // 读取file文件,得到的结果为base64位

            render.readAsDataURL(file);

        };

    });

    render.onload = function (result) {

        // 把读取到的base64图片设置给img的src属性

        var src = render.result;

        img.src = src;

    };

    img.onload = function () {

        // 加载完毕后获取图片的原始尺寸

        var origin_width = this.width;

        var origin_height = this.height;

        // 设置最大允许宽高,根据需求自己设置,值越大,图片大小越大

        var max_width = 400;

        var max_height = 400;

 

        // 最终宽高

        var target_width = origin_width;

        var target_height = origin_height;

        if (origin_width > max_width || origin_height > max_height) {

            if (origin_width / origin_height > max_width / max_height) {

                // 更宽,按照宽度限定尺寸

                target_width = max_width;

                target_height = Math.round(max_width * (origin_height / origin_width));

            else {

                target_height = max_height;

                target_width = Math.round(max_height * (origin_width / origin_height));

            }

        }

        canvas.width = target_width;

        canvas.height = target_height;

        // 绘画到画布上

        context.drawImage(img, 0, 0, target_width, target_height);

        /*

            此处得到的是blob对象,blob对象是在ie10及以上才兼容,在ios8_1_1上和iphoneSE上有兼容问题

            canvas.toBlob(function(result) {

                console.log(result);

            });

        */

        // 读取canvas的数据

        var result = canvas.toDataURL();

        // 得到的结果是base64位的字符串,拿到压缩后的值通过网络请求交给后台处理...

        // 如果是blob对象,需要通过FormData对象发送

        console.log(result);

    };

 

</script>

Copy after login

Related recommendations:

Algorithm analysis of the full arrangement of strings in js

Use of React: State management inside React components

The above is the detailed content of How to implement the method of uploading and compressing images in js. 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
1 months 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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

See all articles