在 JavaScript 中操作图像

Muhammad Muzammil Hussain 2023年1月30日 2022年5月5日
  1. 在 JavaScript 中操作图像
  2. 在 Javascript 中调整图像大小
  3. 在 JavaScript 中裁剪图像
  4. 在 JavaScript 中反转图像
  5. 在 JavaScript 中对图像应用可调噪点
  6. 在 JavaScript 中调整图像的鲜艳度
在 JavaScript 中操作图像

本文将介绍 JavaScript 中的图像处理功能。我们将使用 JavaScript 库 CamanJS 来操作图像。

在 JavaScript 中操作图像

图像操作用于对图像执行各种操作功能。例如,我们可以增加图像的亮度、增加图像的饱和度、调整图像的大小等等。

要在你的项目中使用 CamanJs,请在 </body> 标签之后添加 script 标签。

<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js" integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

然后,我们使用下面的代码。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <!-- 	<link rel="stylesheet" href="css/style.css" /> -->
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter rmBrightness btn btn-info">-</button>
                            <button class="btn btn-secondary btn-disabled" disabled>Brightness</button>
                            <button class="filter addBrightness btn btn-info">+</button>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter rmContrast btn btn-info">-</button>
                            <button class="btn btn-secondary btn-disabled" disabled>Contrast</button>
                            <button class="filter addContrast btn btn-info">+</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("addBrightness")) {
                Caman("#canvas", img, function () {
                    this.brightness(5).render();
                });
            } else if (e.target.classList.contains("rmBrightness")) {
                Caman("#canvas", img, function () {
                    this.brightness(-5).render();
                });
            } else if (e.target.classList.contains("addContrast")) {
                Caman("#canvas", img, function () {
                    this.contrast(5).render();
                });
            } else if (e.target.classList.contains("rmContrast")) {
                Caman("#canvas", img, function () {
                    this.contrast(-5).render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

在 Javascript 中调整图像大小

要调整图像大小,请使用以下代码。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <!-- 	<link rel="stylesheet" href="css/style.css" /> -->
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter resize btn btn-info"> Resize </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("resize")) {
                Caman("#canvas", img, function () {
                    this.resize({
                        width: 1000,
                        height:200
                    }).render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

在 JavaScript 中裁剪图像

我们还可以使用 CamanJs 裁剪图像。我们必须指定裁剪开始的宽度、高度和可选的左上角坐标。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter crop btn btn-info"> Crop </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("crop")) {
                Caman("#canvas", img, function () {
                    this.crop(500, 300).render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

在 JavaScript 中反转图像

反转图像会从 255 中减去每个颜色通道值。它不需要任何参数。

请参阅下面的代码。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <!-- 	<link rel="stylesheet" href="css/style.css" /> -->
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter invert btn btn-info"> Invert </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("invert")) {
                Caman("#canvas", img, function () {
                    this.invert().render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

在 JavaScript 中对图像应用可调噪点

我们还可以对图像应用可调节的噪声,范围从 0 到无穷大。值越高,使用的噪声越多。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <!-- 	<link rel="stylesheet" href="css/style.css" /> -->
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter rmNoise btn btn-info">-</button>
                            <button class="btn btn-secondary btn-disabled" disabled>Noise</button>
                            <button class="filter addNoise btn btn-info">+</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("addNoise")) {
                Caman("#canvas", img, function () {
                    this.noise(5).render();
                });
            } else if (e.target.classList.contains("rmNoise")) {
                Caman("#canvas", img, function () {
                    this.noise(-5).render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

在 JavaScript 中调整图像的鲜艳度

鲜艳度会增加低饱和度图像上的颜色强度。

它的范围从 -100 到 100。值 < 0 将使图像去饱和,而值 > 0 将使图像饱和。

<html lang="en">

<head>
    <meta charset="utf-8" />

    <title>Image Manipulation</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
    <!-- 	<link rel="stylesheet" href="css/style.css" /> -->
    <style>
        #canvas {
            margin: auto;
            background-color: #ececec;
            width: 100%;
        }

        .btn-disable {
            color: #fff !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8 m-auto">
                <div class="custom-file mb-3">
                    <input type="file" class="custom-file-input" id="upload-file">
                    <label for="upload-file" class="custom-file-label">Choose Image</label>
                </div>
                <canvas id="canvas"></canvas>
                <h4 class="text-center my-3">Filters</h4>
                <div class="row my-4 text-center">
                    <div class="col-md-3">
                        <div class="btn-group btn-group-sm">
                            <button class="filter rmVibrance btn btn-info">-</button>
                            <button class="btn btn-secondary btn-disabled" disabled>Vibrance</button>
                            <button class="filter addVibrance btn btn-info">+</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"
    integrity="sha512-JjFeUD2H//RHt+DjVf1BTuy1X5ZPtMl0svQ3RopX641DWoSilJ89LsFGq4Sw/6BSBfULqUW/CfnVopV5CfvRXA=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    const uploadFile = document.getElementById("upload-file");
    // Filter & Effect Handlers
    document.addEventListener("click", e => {
        if (e.target.classList.contains("filter")) {
            if (e.target.classList.contains("addVibrance")) {
                Caman("#canvas", img, function () {
                    this.vibrance(5).render();
                });
            } else if (e.target.classList.contains("rmVibrance")) {
                Caman("#canvas", img, function () {
                    this.vibrance(-5).render();
                });
            }
        }
    });

    // Upload File
    uploadFile.addEventListener("change", () => {
        // Get File
        const file = document.getElementById("upload-file").files[0];
        // Init FileReader API
        const reader = new FileReader();

        // Check for file
        if (file) {
            // Read data as URL
            reader.readAsDataURL(file);
        }

        // Add image to canvas
        reader.addEventListener(
            "load",
            () => {
                // Create image
                img = new Image();
                // Set image src
                img.src = reader.result;
                // On image load add to canvas
                img.onload = function () {
                    canvas.width = img.width;
                    canvas.height = img.height;
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    canvas.removeAttribute("data-caman-id");
                };
            },
            false
        );
    });

</script>

</html>

相关文章 - JavaScript Image