在 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