让我们创建一个
项目概述:
创建一个 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中文网其他相关文章!