今天要調整的影像色溫是指讓影像偏紅,讓人有溫暖的感覺, 或是讓影像偏藍, 讓人有偏冷的感覺. 偏藍和偏紅的效果是利用調整RGB的紅色R和藍色B元素來達成. 如果要偏紅就R加一點,B減一點. 如果要偏藍就R減一點,B加一點.
function applyTemperature(temperature) {
if (!image) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const red = data[i];
const green = data[i + 1];
const blue = data[i + 2];
let newRed, newGreen, newBlue;
if (temperature < 0) {
newRed = red * (1 + temperature / 100);
newGreen = green * (1 + temperature / 200);
newBlue = blue * (1 - temperature / 100);
} else {
newRed = red * (1 - temperature / 100) + 255 * temperature / 100;
newGreen = green * (1 - temperature / 200);
newBlue = blue * (1 + temperature / 100);
}
data[i] = Math.min(255, Math.max(0, newRed));
data[i + 1] = Math.min(255, Math.max(0, newGreen));
data[i + 2] = Math.min(255, Math.max(0, newBlue));
}
ctx.putImageData(imageData, 0, 0);
// Update temperature value display
temperatureValue.textContent = temperature;
}
JavaScript完整程式放在網頁 https://cardteck.com/wp/adjustTemperature.html.
原始圖像如下, 調整範圍為正負100.
調整增加100的效果.
調整減少100的效果.