|
|
|
|
|
|
|
|
|
|
|
|
|
const DEFAULT_FILTERS = { |
|
temperature: 0, |
|
brightness: 100, |
|
contrast: 100, |
|
saturation: 100 |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function applyFilters(imageData, filters) { |
|
const {temperature, brightness, contrast, saturation} = filters; |
|
|
|
const data = imageData.data; |
|
|
|
|
|
for (let i = 0; i < data.length; i += 4) { |
|
|
|
let r = data[i]; |
|
let g = data[i + 1]; |
|
let b = data[i + 2]; |
|
|
|
|
|
if (temperature !== 0) { |
|
const tempValue = temperature / 5; |
|
if (tempValue > 0) { |
|
|
|
r = Math.min(255, r + tempValue); |
|
b = Math.max(0, b - tempValue / 2); |
|
} else { |
|
|
|
r = Math.max(0, r + tempValue); |
|
b = Math.min(255, b - tempValue * 1.5); |
|
} |
|
} |
|
|
|
|
|
const brightnessMultiplier = brightness / 100; |
|
r = Math.min(255, r * brightnessMultiplier); |
|
g = Math.min(255, g * brightnessMultiplier); |
|
b = Math.min(255, b * brightnessMultiplier); |
|
|
|
|
|
const contrastFactor = (contrast / 100); |
|
r = Math.min(255, Math.max(0, (r - 128) * contrastFactor + 128)); |
|
g = Math.min(255, Math.max(0, (g - 128) * contrastFactor + 128)); |
|
b = Math.min(255, Math.max(0, (b - 128) * contrastFactor + 128)); |
|
|
|
|
|
const avg = (r + g + b) / 3; |
|
const saturationMultiplier = saturation / 100; |
|
r = Math.min(255, Math.max(0, avg + (r - avg) * saturationMultiplier)); |
|
g = Math.min(255, Math.max(0, avg + (g - avg) * saturationMultiplier)); |
|
b = Math.min(255, Math.max(0, avg + (b - avg) * saturationMultiplier)); |
|
|
|
|
|
data[i] = Math.round(r); |
|
data[i + 1] = Math.round(g); |
|
data[i + 2] = Math.round(b); |
|
} |
|
|
|
return imageData; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function createFilteredCanvas(image, filters) { |
|
if (!image) return null; |
|
|
|
const tempCanvas = document.createElement('canvas'); |
|
tempCanvas.width = image.width; |
|
tempCanvas.height = image.height; |
|
const tempCtx = tempCanvas.getContext('2d'); |
|
|
|
|
|
tempCtx.drawImage(image, 0, 0); |
|
|
|
|
|
const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height); |
|
const filteredData = applyFilters(imageData, filters); |
|
tempCtx.putImageData(filteredData, 0, 0); |
|
|
|
return tempCanvas; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function applyFilterToLayer(overlays, activeOverlayIndex, filterValues) { |
|
if (activeOverlayIndex >= 0 && activeOverlayIndex < overlays.length) { |
|
|
|
overlays[activeOverlayIndex].filters = { ...filterValues }; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function resetFilters(overlays, activeOverlayIndex) { |
|
|
|
if (activeOverlayIndex >= 0 && activeOverlayIndex < overlays.length) { |
|
overlays[activeOverlayIndex].filters = { ...DEFAULT_FILTERS }; |
|
} |
|
|
|
|
|
return { ...DEFAULT_FILTERS }; |
|
} |
|
|
|
|
|
window.ImageFilters = { |
|
applyFilters, |
|
createFilteredCanvas, |
|
applyFilterToLayer, |
|
resetFilters, |
|
DEFAULT_FILTERS |
|
}; |