讓我們建立一個
項目概述:
建立一個 Web 應用程序,允許使用者上傳圖像、操作圖像的二進位數據,然後保存修改後的圖像。該應用程式將使用戶能夠透過直接修改圖像的二進位資料來應用灰度、反轉和亮度調整等各種效果。
主要特點:
我們將使用 HTML、CSS 和 JAVASCRIPT
``>
<input type="file" name="" id="fileinput" accept="image/*"> <br> <button id="grayscalebtn">Apply GrayScale</button> <button id="invertbtn">Apply Inversion</button> <button id="brightnessbtn">Apply Brightness</button> <input type="range" name="" id="brightnessrange" min="-100" max="100" value="0"> <br> <canvas id="canvas"></canvas> <br> <button id="downloadbtn">Download Image</button>`
## css:
*{
背景顏色: rgb(160, 226, 204);
}
身體{
字體系列:Arial、無襯線體;
文字對齊:居中;
內邊距:20px;
}
#畫布{
邊框:1px 實線 #000;
上邊距:20px;
}
**
**
`document.getElementById('grayscalebtn').addEventListener('click', applyGrayscale);
document.getElementById('invertbtn').addEventListener('click', applyInversion);
const BrightRange = document.getElementById('brightnessbtn');
BrightRange.addEventListener('輸入', () => {
ctx.putImageData(originalImageData, 0, 0); // 在套用亮度之前重設為原始值
調整亮度(Number(brightnessRange.value));
});
document.getElementById('downloadbtn').addEventListener('click', () => {
const link = document.createElement('a');
link.download = '修改後的圖片.png';
link.href = canvas.toDataURL();
link.click();
});
const fileinput = document.getElementById('fileinput'); const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let originalImageData; fileinput.addEventListener('change',(event)=>{ const file = event.target.files[0]; const reader = new FileReader(); reader.onload = function(e){ const img = new Image(); img.onload = function(){ canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img,0,0); originalImageData = ctx.getImageData(0,0,canvas.width,canvas.height); } img.src = e.target.result; } reader.readAsDataURL(file); }) function applyGrayscale() { let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); let data = imageData.data; for (let i = 0; i < data.length; i += 4) { const r = data[i]; const g = data[i + 1]; const b = data[i + 2]; const grayscale = r * 0.3 + g * 0.59 + b * 0.11; data[i] = data[i + 1] = data[i + 2] = grayscale; } ctx.putImageData(imageData, 0, 0);
}
函數 applyInversion() {
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
讓資料 = imageData.data;
for (let i = 0; i < data.length; i += 4) { data[i] = 255 - data[i]; // Red data[i + 1] = 255 - data[i + 1]; // Green data[i + 2] = 255 - data[i + 2]; // Blue } ctx.putImageData(imageData, 0, 0);
}
函數調整亮度(值){
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
讓資料 = imageData.data;
for (let i = 0; i < data.length; i += 4) { data[i] += value; // Red data[i + 1] += value; // Green data[i + 2] += value; // Blue } ctx.putImageData(imageData, 0, 0);
}
`
其輸出如下:
以上是二值影像處理器的詳細內容。更多資訊請關注PHP中文網其他相關文章!