DAY 8
2
Modern Web

## Day 8 圖片效果 - 對比度

### 算法

``````newRedColor = Factor * (oldRedColor -128) + 128
``````

``````Factor = 259( C + 255 ) / 255 ( 259 - C )
``````

### 實作

``````Factor = 259( C + 100 ) / 100 ( 259 - C )
``````

``````Factor = 350( C + 255 ) / 255 ( 350 - C )
``````

``````
export const contrast = (pixelData, amount) => {
// const factor = (259 * (amount + 255)) / (255 * (259 - amount))
const contrastThreshold = 128
const factor = (350 * (amount + 255)) / (255 * (350 - amount))
for (let i = 0; i < pixelData.length; i += 4) {
pixelData[i] =
factor * (pixelData[i] - contrastThreshold) + contrastThreshold
pixelData[i + 1] =
factor * (pixelData[i + 1] - contrastThreshold) + contrastThreshold
pixelData[i + 2] =
factor * (pixelData[i + 2] - contrastThreshold) + contrastThreshold
}
return pixelData
}

``````

### 外觀 & 資料流程

``````  <Slider
title="對比度"
:min="-100"
:max="100"
:value="contrast"
@sliderChange="val => sliderChange(val, 'contrast')"
></Slider>
``````

`Store` 裡面新增參數

``````state: {
sliderValue: {
brightness: 0,
contrast: 0
}
``````

``````editImageData({ sliderValue, originalEditData }) {
if (originalEditData.data) {
const imageDataCopy = new ImageData(
new Uint8ClampedArray(originalEditData.data),
originalEditData.width,
originalEditData.height
)
if (sliderValue.brightness !== 0) {
filters.brightness(imageDataCopy.data, sliderValue.brightness)
}
if (sliderValue.contrast !== 0) {
filters.contrast(imageDataCopy.data, sliderValue.contrast)
}
return imageDataCopy
}
}
``````