OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat(image): add Phase 4 color adjustments and histogram utilities
Augustus Otu487a9f6ae518
diff --git a/apps/image/src/adjustments/black-white.ts b/apps/image/src/adjustments/black-white.tsnew file mode 100644index 00000000..d4338691--- /dev/null+++ b/apps/image/src/adjustments/black-white.ts@@ -0,0 +1,168 @@+export interface BlackWhiteSettings {+ reds: number;+ yellows: number;+ greens: number;+ cyans: number;+ blues: number;+ magentas: number;+ tint: {+ enabled: boolean;+ hue: number;+ saturation: number;+ };+}++export const DEFAULT_BLACK_WHITE: BlackWhiteSettings = {+ reds: 40,+ yellows: 60,+ greens: 40,+ cyans: 60,+ blues: 20,+ magentas: 80,+ tint: {+ enabled: false,+ hue: 30,+ saturation: 25,+ },+};++export const BLACK_WHITE_PRESETS = {+ default: { reds: 40, yellows: 60, greens: 40, cyans: 60, blues: 20, magentas: 80 },+ highContrast: { reds: 40, yellows: 60, greens: 40, cyans: 60, blues: 20, magentas: 80 },+ infrared: { reds: -70, yellows: 200, greens: -70, cyans: 200, blues: -20, magentas: -20 },+ maximumWhite: { reds: 100, yellows: 100, greens: 100, cyans: 100, blues: 100, magentas: 100 },+ maximumBlack: { reds: -200, yellows: -200, greens: -200, cyans: -200, blues: -200, magentas: -200 },+ neutral: { reds: 33, yellows: 33, greens: 33, cyans: 33, blues: 33, magentas: 33 },+ redFilter: { reds: 106, yellows: 52, greens: -10, cyans: -40, blues: -30, magentas: 94 },+ yellowFilter: { reds: 34, yellows: 106, greens: 54, cyans: -26, blues: -50, magentas: 14 },+ greenFilter: { reds: -44, yellows: 64, greens: 106, cyans: 60, blues: -30, magentas: -70 },+ blueFilter: { reds: -30, yellows: -46, greens: -16, cyans: 30, blues: 106, magentas: 30 },+};++function rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {+ r /= 255;+ g /= 255;+ b /= 255;++ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;++ if (max === min) {+ return { h: 0, s: 0, l };+ }++ const d = max - min;+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);++ let h: number;+ switch (max) {+ case r:+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;+ break;+ case g:+ h = ((b - r) / d + 2) / 6;+ break;+ default:+ h = ((r - g) / d + 4) / 6;+ break;+ }++ return { h, s, l };+}++function hslToRgb(h: number, s: number, l: number): { r: number; g: number; b: number } {+ if (s === 0) {+ const gray = Math.round(l * 255);+ return { r: gray, g: gray, b: gray };+ }++ const hue2rgb = (p: number, q: number, t: number): number => {+ if (t < 0) t += 1;+ if (t > 1) t -= 1;+ if (t < 1 / 6) return p + (q - p) * 6 * t;+ if (t < 1 / 2) return q;+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;+ return p;+ };++ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;+ const p = 2 * l - q;++ return {+ r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),+ g: Math.round(hue2rgb(p, q, h) * 255),+ b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),+ };+}++function getColorWeight(hue: number, targetHue: number, spread: number = 60): number {+ let diff = Math.abs(hue - targetHue);+ if (diff > 180) diff = 360 - diff;+ if (diff >= spread) return 0;+ return 1 - diff / spread;+}++export function applyBlackWhite(imageData: ImageData, settings: BlackWhiteSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ const { h, s } = rgbToHsl(r, g, b);+ const hue = h * 360;++ let gray = (r + g + b) / 3;++ if (s > 0.05) {+ const redWeight = getColorWeight(hue, 0) + getColorWeight(hue, 360);+ const yellowWeight = getColorWeight(hue, 60);+ const greenWeight = getColorWeight(hue, 120);+ const cyanWeight = getColorWeight(hue, 180);+ const blueWeight = getColorWeight(hue, 240);+ const magentaWeight = getColorWeight(hue, 300);++ const totalWeight = redWeight + yellowWeight + greenWeight + cyanWeight + blueWeight + magentaWeight;++ if (totalWeight > 0) {+ const adjustment =+ (redWeight * settings.reds ++ yellowWeight * settings.yellows ++ greenWeight * settings.greens ++ cyanWeight * settings.cyans ++ blueWeight * settings.blues ++ magentaWeight * settings.magentas) / totalWeight;++ gray = gray * (1 + (adjustment - 50) / 100 * s);+ }+ }++ gray = Math.max(0, Math.min(255, gray));++ let finalR = gray;+ let finalG = gray;+ let finalB = gray;++ if (settings.tint.enabled) {+ const tintH = settings.tint.hue / 360;+ const tintS = settings.tint.saturation / 100;+ const tintL = gray / 255;++ const tinted = hslToRgb(tintH, tintS, tintL);+ finalR = tinted.r;+ finalG = tinted.g;+ finalB = tinted.b;+ }++ resultData[i] = finalR;+ resultData[i + 1] = finalG;+ resultData[i + 2] = finalB;+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/channel-mixer.ts b/apps/image/src/adjustments/channel-mixer.tsnew file mode 100644index 00000000..6e53b1e7--- /dev/null+++ b/apps/image/src/adjustments/channel-mixer.ts@@ -0,0 +1,108 @@+export interface ChannelMixerSettings {+ red: {+ red: number;+ green: number;+ blue: number;+ constant: number;+ };+ green: {+ red: number;+ green: number;+ blue: number;+ constant: number;+ };+ blue: {+ red: number;+ green: number;+ blue: number;+ constant: number;+ };+ monochrome: boolean;+ monoRed: number;+ monoGreen: number;+ monoBlue: number;+ monoConstant: number;+}++export const DEFAULT_CHANNEL_MIXER: ChannelMixerSettings = {+ red: { red: 100, green: 0, blue: 0, constant: 0 },+ green: { red: 0, green: 100, blue: 0, constant: 0 },+ blue: { red: 0, green: 0, blue: 100, constant: 0 },+ monochrome: false,+ monoRed: 40,+ monoGreen: 40,+ monoBlue: 20,+ monoConstant: 0,+};++export const CHANNEL_MIXER_PRESETS = {+ default: {+ red: { red: 100, green: 0, blue: 0, constant: 0 },+ green: { red: 0, green: 100, blue: 0, constant: 0 },+ blue: { red: 0, green: 0, blue: 100, constant: 0 },+ },+ swapRedBlue: {+ red: { red: 0, green: 0, blue: 100, constant: 0 },+ green: { red: 0, green: 100, blue: 0, constant: 0 },+ blue: { red: 100, green: 0, blue: 0, constant: 0 },+ },+ sepia: {+ red: { red: 100, green: 50, blue: 0, constant: 0 },+ green: { red: 60, green: 60, blue: 0, constant: 0 },+ blue: { red: 30, green: 30, blue: 30, constant: 0 },+ },+ cyberPunk: {+ red: { red: 100, green: 0, blue: 50, constant: 0 },+ green: { red: 0, green: 100, blue: 50, constant: 0 },+ blue: { red: 50, green: 0, blue: 100, constant: 0 },+ },+};++export function applyChannelMixer(imageData: ImageData, settings: ChannelMixerSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ let newR: number, newG: number, newB: number;++ if (settings.monochrome) {+ const gray =+ r * (settings.monoRed / 100) ++ g * (settings.monoGreen / 100) ++ b * (settings.monoBlue / 100) ++ settings.monoConstant * 2.55;++ newR = newG = newB = Math.max(0, Math.min(255, gray));+ } else {+ newR =+ r * (settings.red.red / 100) ++ g * (settings.red.green / 100) ++ b * (settings.red.blue / 100) ++ settings.red.constant * 2.55;++ newG =+ r * (settings.green.red / 100) ++ g * (settings.green.green / 100) ++ b * (settings.green.blue / 100) ++ settings.green.constant * 2.55;++ newB =+ r * (settings.blue.red / 100) ++ g * (settings.blue.green / 100) ++ b * (settings.blue.blue / 100) ++ settings.blue.constant * 2.55;+ }++ resultData[i] = Math.max(0, Math.min(255, newR));+ resultData[i + 1] = Math.max(0, Math.min(255, newG));+ resultData[i + 2] = Math.max(0, Math.min(255, newB));+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/color-balance.ts b/apps/image/src/adjustments/color-balance.tsnew file mode 100644index 00000000..941e14ac--- /dev/null+++ b/apps/image/src/adjustments/color-balance.ts@@ -0,0 +1,111 @@+export interface ColorBalanceSettings {+ shadows: {+ cyanRed: number;+ magentaGreen: number;+ yellowBlue: number;+ };+ midtones: {+ cyanRed: number;+ magentaGreen: number;+ yellowBlue: number;+ };+ highlights: {+ cyanRed: number;+ magentaGreen: number;+ yellowBlue: number;+ };+ preserveLuminosity: boolean;+}++export const DEFAULT_COLOR_BALANCE: ColorBalanceSettings = {+ shadows: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },+ midtones: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },+ highlights: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },+ preserveLuminosity: true,+};++function getLuminance(r: number, g: number, b: number): number {+ return r * 0.299 + g * 0.587 + b * 0.114;+}++function getToneWeight(luminance: number, tone: 'shadows' | 'midtones' | 'highlights'): number {+ const normalized = luminance / 255;++ switch (tone) {+ case 'shadows':+ if (normalized <= 0.25) return 1;+ if (normalized <= 0.5) return 1 - (normalized - 0.25) / 0.25;+ return 0;++ case 'highlights':+ if (normalized >= 0.75) return 1;+ if (normalized >= 0.5) return (normalized - 0.5) / 0.25;+ return 0;++ case 'midtones':+ if (normalized >= 0.25 && normalized <= 0.75) {+ const distFromCenter = Math.abs(normalized - 0.5);+ return 1 - distFromCenter / 0.25;+ }+ return 0;+ }+}++export function applyColorBalance(imageData: ImageData, settings: ColorBalanceSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ for (let i = 0; i < data.length; i += 4) {+ let r = data[i];+ let g = data[i + 1];+ let b = data[i + 2];+ const a = data[i + 3];++ const luminance = getLuminance(r, g, b);++ const shadowWeight = getToneWeight(luminance, 'shadows');+ const midtoneWeight = getToneWeight(luminance, 'midtones');+ const highlightWeight = getToneWeight(luminance, 'highlights');++ let rShift = 0, gShift = 0, bShift = 0;++ if (shadowWeight > 0) {+ rShift += settings.shadows.cyanRed * shadowWeight;+ gShift += settings.shadows.magentaGreen * shadowWeight;+ bShift += settings.shadows.yellowBlue * shadowWeight;+ }++ if (midtoneWeight > 0) {+ rShift += settings.midtones.cyanRed * midtoneWeight;+ gShift += settings.midtones.magentaGreen * midtoneWeight;+ bShift += settings.midtones.yellowBlue * midtoneWeight;+ }++ if (highlightWeight > 0) {+ rShift += settings.highlights.cyanRed * highlightWeight;+ gShift += settings.highlights.magentaGreen * highlightWeight;+ bShift += settings.highlights.yellowBlue * highlightWeight;+ }++ r = Math.max(0, Math.min(255, r + rShift));+ g = Math.max(0, Math.min(255, g + gShift));+ b = Math.max(0, Math.min(255, b + bShift));++ if (settings.preserveLuminosity) {+ const newLuminance = getLuminance(r, g, b);+ if (newLuminance > 0) {+ const ratio = luminance / newLuminance;+ r = Math.max(0, Math.min(255, r * ratio));+ g = Math.max(0, Math.min(255, g * ratio));+ b = Math.max(0, Math.min(255, b * ratio));+ }+ }++ resultData[i] = r;+ resultData[i + 1] = g;+ resultData[i + 2] = b;+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/color-lookup.ts b/apps/image/src/adjustments/color-lookup.tsnew file mode 100644index 00000000..aab063b1--- /dev/null+++ b/apps/image/src/adjustments/color-lookup.ts@@ -0,0 +1,176 @@+export interface ColorLookupSettings {+ lutData: Float32Array | null;+ lutSize: number;+ strength: number;+}++export const DEFAULT_COLOR_LOOKUP: ColorLookupSettings = {+ lutData: null,+ lutSize: 0,+ strength: 100,+};++export function parseCubeLUT(content: string): { data: Float32Array; size: number } | null {+ const lines = content.split('\n');+ let size = 0;+ const data: number[] = [];++ for (const line of lines) {+ const trimmed = line.trim();++ if (trimmed.startsWith('#') || trimmed === '') continue;++ if (trimmed.startsWith('LUT_3D_SIZE')) {+ const match = trimmed.match(/LUT_3D_SIZE\s+(\d+)/);+ if (match) {+ size = parseInt(match[1], 10);+ }+ continue;+ }++ if (trimmed.startsWith('TITLE') || trimmed.startsWith('DOMAIN_')) continue;++ const values = trimmed.split(/\s+/).map(parseFloat);+ if (values.length === 3 && values.every((v) => !isNaN(v))) {+ data.push(...values);+ }+ }++ if (size === 0 || data.length !== size * size * size * 3) {+ return null;+ }++ return { data: new Float32Array(data), size };+}++export function parse3dlLUT(content: string): { data: Float32Array; size: number } | null {+ const lines = content.split('\n');+ const data: number[] = [];+ let size = 0;++ for (const line of lines) {+ const trimmed = line.trim();+ if (trimmed === '' || trimmed.startsWith('#')) continue;++ const values = trimmed.split(/\s+/).map(parseFloat);++ if (values.length === 1 && size === 0) {+ size = Math.round(Math.cbrt(values[0]));+ continue;+ }++ if (values.length === 3 && values.every((v) => !isNaN(v))) {+ data.push(values[0] / 4095, values[1] / 4095, values[2] / 4095);+ }+ }++ if (size === 0) {+ size = Math.round(Math.cbrt(data.length / 3));+ }++ if (size === 0 || data.length !== size * size * size * 3) {+ return null;+ }++ return { data: new Float32Array(data), size };+}++function trilinearInterpolate(+ lutData: Float32Array,+ size: number,+ r: number,+ g: number,+ b: number+): { r: number; g: number; b: number } {+ const rScaled = r * (size - 1);+ const gScaled = g * (size - 1);+ const bScaled = b * (size - 1);++ const r0 = Math.floor(rScaled);+ const g0 = Math.floor(gScaled);+ const b0 = Math.floor(bScaled);++ const r1 = Math.min(r0 + 1, size - 1);+ const g1 = Math.min(g0 + 1, size - 1);+ const b1 = Math.min(b0 + 1, size - 1);++ const rFrac = rScaled - r0;+ const gFrac = gScaled - g0;+ const bFrac = bScaled - b0;++ const getIndex = (ri: number, gi: number, bi: number) => (bi * size * size + gi * size + ri) * 3;++ const c000 = getIndex(r0, g0, b0);+ const c100 = getIndex(r1, g0, b0);+ const c010 = getIndex(r0, g1, b0);+ const c110 = getIndex(r1, g1, b0);+ const c001 = getIndex(r0, g0, b1);+ const c101 = getIndex(r1, g0, b1);+ const c011 = getIndex(r0, g1, b1);+ const c111 = getIndex(r1, g1, b1);++ const lerp = (a: number, b: number, t: number) => a + (b - a) * t;++ const interpolate = (channel: number) => {+ const c00 = lerp(lutData[c000 + channel], lutData[c100 + channel], rFrac);+ const c01 = lerp(lutData[c001 + channel], lutData[c101 + channel], rFrac);+ const c10 = lerp(lutData[c010 + channel], lutData[c110 + channel], rFrac);+ const c11 = lerp(lutData[c011 + channel], lutData[c111 + channel], rFrac);++ const c0 = lerp(c00, c10, gFrac);+ const c1 = lerp(c01, c11, gFrac);++ return lerp(c0, c1, bFrac);+ };++ return {+ r: interpolate(0),+ g: interpolate(1),+ b: interpolate(2),+ };+}++export function applyColorLookup(imageData: ImageData, settings: ColorLookupSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ if (!settings.lutData || settings.lutSize === 0) {+ resultData.set(data);+ return new ImageData(resultData, width, height);+ }++ const strength = settings.strength / 100;++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i] / 255;+ const g = data[i + 1] / 255;+ const b = data[i + 2] / 255;+ const a = data[i + 3];++ const lutColor = trilinearInterpolate(settings.lutData, settings.lutSize, r, g, b);++ resultData[i] = Math.max(0, Math.min(255, (r + (lutColor.r - r) * strength) * 255));+ resultData[i + 1] = Math.max(0, Math.min(255, (g + (lutColor.g - g) * strength) * 255));+ resultData[i + 2] = Math.max(0, Math.min(255, (b + (lutColor.b - b) * strength) * 255));+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}++export function createIdentityLUT(size: number): Float32Array {+ const data = new Float32Array(size * size * size * 3);++ for (let b = 0; b < size; b++) {+ for (let g = 0; g < size; g++) {+ for (let r = 0; r < size; r++) {+ const idx = (b * size * size + g * size + r) * 3;+ data[idx] = r / (size - 1);+ data[idx + 1] = g / (size - 1);+ data[idx + 2] = b / (size - 1);+ }+ }+ }++ return data;+}diff --git a/apps/image/src/adjustments/gradient-map.ts b/apps/image/src/adjustments/gradient-map.tsnew file mode 100644index 00000000..ba8fb886--- /dev/null+++ b/apps/image/src/adjustments/gradient-map.ts@@ -0,0 +1,164 @@+export interface GradientStop {+ position: number;+ color: string;+}++export interface GradientMapSettings {+ stops: GradientStop[];+ dither: boolean;+ reverse: boolean;+}++export const DEFAULT_GRADIENT_MAP: GradientMapSettings = {+ stops: [+ { position: 0, color: '#000000' },+ { position: 100, color: '#ffffff' },+ ],+ dither: false,+ reverse: false,+};++export const GRADIENT_MAP_PRESETS = {+ blackWhite: [+ { position: 0, color: '#000000' },+ { position: 100, color: '#ffffff' },+ ],+ sepiaTone: [+ { position: 0, color: '#1a0f00' },+ { position: 50, color: '#8b6914' },+ { position: 100, color: '#ffe7b3' },+ ],+ duotoneBlueOrange: [+ { position: 0, color: '#001f4d' },+ { position: 100, color: '#ff8c00' },+ ],+ duotonePurpleTeal: [+ { position: 0, color: '#2d1b4e' },+ { position: 100, color: '#00d4aa' },+ ],+ sunset: [+ { position: 0, color: '#1a0533' },+ { position: 33, color: '#6b1839' },+ { position: 66, color: '#d44d1b' },+ { position: 100, color: '#ffd700' },+ ],+ coolBlue: [+ { position: 0, color: '#000033' },+ { position: 50, color: '#0066cc' },+ { position: 100, color: '#99ccff' },+ ],+ warmRed: [+ { position: 0, color: '#1a0000' },+ { position: 50, color: '#cc3300' },+ { position: 100, color: '#ffcc99' },+ ],+ greenForest: [+ { position: 0, color: '#001a00' },+ { position: 50, color: '#336600' },+ { position: 100, color: '#99cc66' },+ ],+ infrared: [+ { position: 0, color: '#000000' },+ { position: 25, color: '#330066' },+ { position: 50, color: '#ff0066' },+ { position: 75, color: '#ffcc00' },+ { position: 100, color: '#ffffff' },+ ],+ thermal: [+ { position: 0, color: '#000033' },+ { position: 25, color: '#6600cc' },+ { position: 50, color: '#ff0000' },+ { position: 75, color: '#ffff00' },+ { position: 100, color: '#ffffff' },+ ],+};++function parseColor(color: string): { r: number; g: number; b: number } {+ const match = color.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);+ if (match) {+ return {+ r: parseInt(match[1], 16),+ g: parseInt(match[2], 16),+ b: parseInt(match[3], 16),+ };+ }+ return { r: 0, g: 0, b: 0 };+}++function interpolateGradient(+ stops: GradientStop[],+ position: number+): { r: number; g: number; b: number } {+ if (stops.length === 0) return { r: 0, g: 0, b: 0 };+ if (stops.length === 1) return parseColor(stops[0].color);++ const sortedStops = [...stops].sort((a, b) => a.position - b.position);++ if (position <= sortedStops[0].position) {+ return parseColor(sortedStops[0].color);+ }+ if (position >= sortedStops[sortedStops.length - 1].position) {+ return parseColor(sortedStops[sortedStops.length - 1].color);+ }++ for (let i = 0; i < sortedStops.length - 1; i++) {+ const stop1 = sortedStops[i];+ const stop2 = sortedStops[i + 1];++ if (position >= stop1.position && position <= stop2.position) {+ const t = (position - stop1.position) / (stop2.position - stop1.position);+ const c1 = parseColor(stop1.color);+ const c2 = parseColor(stop2.color);++ return {+ r: Math.round(c1.r + (c2.r - c1.r) * t),+ g: Math.round(c1.g + (c2.g - c1.g) * t),+ b: Math.round(c1.b + (c2.b - c1.b) * t),+ };+ }+ }++ return parseColor(sortedStops[sortedStops.length - 1].color);+}++function getLuminance(r: number, g: number, b: number): number {+ return (r * 0.299 + g * 0.587 + b * 0.114) / 255;+}++export function applyGradientMap(imageData: ImageData, settings: GradientMapSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const lookupTable: Array<{ r: number; g: number; b: number }> = [];+ for (let i = 0; i < 256; i++) {+ let position = (i / 255) * 100;+ if (settings.reverse) {+ position = 100 - position;+ }+ lookupTable[i] = interpolateGradient(settings.stops, position);+ }++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ let luminance = getLuminance(r, g, b);++ if (settings.dither) {+ const noise = (Math.random() - 0.5) * (1 / 255);+ luminance = Math.max(0, Math.min(1, luminance + noise));+ }++ const idx = Math.round(luminance * 255);+ const mappedColor = lookupTable[idx];++ resultData[i] = mappedColor.r;+ resultData[i + 1] = mappedColor.g;+ resultData[i + 2] = mappedColor.b;+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/histogram.ts b/apps/image/src/adjustments/histogram.tsnew file mode 100644index 00000000..cfc59d44--- /dev/null+++ b/apps/image/src/adjustments/histogram.ts@@ -0,0 +1,305 @@+export interface HistogramData {+ red: Uint32Array;+ green: Uint32Array;+ blue: Uint32Array;+ luminosity: Uint32Array;+}++export interface HistogramStatistics {+ mean: number;+ stdDev: number;+ median: number;+ min: number;+ max: number;+ pixelCount: number;+ shadowsClipped: number;+ highlightsClipped: number;+}++export interface HistogramResult {+ data: HistogramData;+ statistics: {+ red: HistogramStatistics;+ green: HistogramStatistics;+ blue: HistogramStatistics;+ luminosity: HistogramStatistics;+ };+}++export interface ColorInfo {+ rgb: { r: number; g: number; b: number };+ hsb: { h: number; s: number; b: number };+ hsl: { h: number; s: number; l: number };+ lab: { l: number; a: number; b: number };+ cmyk: { c: number; m: number; y: number; k: number };+ hex: string;+}++function calculateStatistics(histogram: Uint32Array, totalPixels: number): HistogramStatistics {+ let sum = 0;+ let min = 255;+ let max = 0;+ let pixelCount = 0;++ for (let i = 0; i < 256; i++) {+ const count = histogram[i];+ if (count > 0) {+ sum += i * count;+ pixelCount += count;+ if (i < min) min = i;+ if (i > max) max = i;+ }+ }++ const mean = pixelCount > 0 ? sum / pixelCount : 0;++ let varianceSum = 0;+ for (let i = 0; i < 256; i++) {+ const count = histogram[i];+ if (count > 0) {+ varianceSum += count * Math.pow(i - mean, 2);+ }+ }+ const stdDev = pixelCount > 0 ? Math.sqrt(varianceSum / pixelCount) : 0;++ let medianCount = 0;+ let median = 0;+ const halfCount = pixelCount / 2;+ for (let i = 0; i < 256; i++) {+ medianCount += histogram[i];+ if (medianCount >= halfCount) {+ median = i;+ break;+ }+ }++ const shadowsClipped = (histogram[0] / totalPixels) * 100;+ const highlightsClipped = (histogram[255] / totalPixels) * 100;++ return {+ mean,+ stdDev,+ median,+ min: pixelCount > 0 ? min : 0,+ max: pixelCount > 0 ? max : 0,+ pixelCount,+ shadowsClipped,+ highlightsClipped,+ };+}++export function calculateHistogram(imageData: ImageData): HistogramResult {+ const { data } = imageData;++ const histogramData: HistogramData = {+ red: new Uint32Array(256),+ green: new Uint32Array(256),+ blue: new Uint32Array(256),+ luminosity: new Uint32Array(256),+ };++ const totalPixels = data.length / 4;++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];++ histogramData.red[r]++;+ histogramData.green[g]++;+ histogramData.blue[b]++;++ const luminosity = Math.round(r * 0.299 + g * 0.587 + b * 0.114);+ histogramData.luminosity[luminosity]++;+ }++ return {+ data: histogramData,+ statistics: {+ red: calculateStatistics(histogramData.red, totalPixels),+ green: calculateStatistics(histogramData.green, totalPixels),+ blue: calculateStatistics(histogramData.blue, totalPixels),+ luminosity: calculateStatistics(histogramData.luminosity, totalPixels),+ },+ };+}++export function getColorInfo(r: number, g: number, b: number): ColorInfo {+ const rNorm = r / 255;+ const gNorm = g / 255;+ const bNorm = b / 255;++ const max = Math.max(rNorm, gNorm, bNorm);+ const min = Math.min(rNorm, gNorm, bNorm);+ const delta = max - min;++ let h = 0;+ if (delta !== 0) {+ if (max === rNorm) {+ h = ((gNorm - bNorm) / delta + (gNorm < bNorm ? 6 : 0)) / 6;+ } else if (max === gNorm) {+ h = ((bNorm - rNorm) / delta + 2) / 6;+ } else {+ h = ((rNorm - gNorm) / delta + 4) / 6;+ }+ }++ const l = (max + min) / 2;+ const sHsl = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));++ const sBrightness = max === 0 ? 0 : delta / max;++ const k = 1 - max;+ const c = max === 0 ? 0 : (1 - rNorm - k) / (1 - k);+ const m = max === 0 ? 0 : (1 - gNorm - k) / (1 - k);+ const y = max === 0 ? 0 : (1 - bNorm - k) / (1 - k);++ const xyzR = rNorm > 0.04045 ? Math.pow((rNorm + 0.055) / 1.055, 2.4) : rNorm / 12.92;+ const xyzG = gNorm > 0.04045 ? Math.pow((gNorm + 0.055) / 1.055, 2.4) : gNorm / 12.92;+ const xyzB = bNorm > 0.04045 ? Math.pow((bNorm + 0.055) / 1.055, 2.4) : bNorm / 12.92;++ const x = (xyzR * 0.4124564 + xyzG * 0.3575761 + xyzB * 0.1804375) / 0.95047;+ const yVal = xyzR * 0.2126729 + xyzG * 0.7151522 + xyzB * 0.0721750;+ const z = (xyzR * 0.0193339 + xyzG * 0.1191920 + xyzB * 0.9503041) / 1.08883;++ const f = (t: number) => t > 0.008856 ? Math.pow(t, 1 / 3) : 7.787 * t + 16 / 116;++ const labL = 116 * f(yVal) - 16;+ const labA = 500 * (f(x) - f(yVal));+ const labB = 200 * (f(yVal) - f(z));++ const hex = '#' ++ r.toString(16).padStart(2, '0') ++ g.toString(16).padStart(2, '0') ++ b.toString(16).padStart(2, '0');++ return {+ rgb: { r, g, b },+ hsb: {+ h: Math.round(h * 360),+ s: Math.round(sBrightness * 100),+ b: Math.round(max * 100),+ },+ hsl: {+ h: Math.round(h * 360),+ s: Math.round(sHsl * 100),+ l: Math.round(l * 100),+ },+ lab: {+ l: Math.round(labL),+ a: Math.round(labA),+ b: Math.round(labB),+ },+ cmyk: {+ c: Math.round(c * 100),+ m: Math.round(m * 100),+ y: Math.round(y * 100),+ k: Math.round(k * 100),+ },+ hex,+ };+}++export function renderHistogram(+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,+ histogram: Uint32Array,+ color: string,+ width: number,+ height: number,+ logarithmic: boolean = false+): void {+ const maxValue = Math.max(...histogram);+ if (maxValue === 0) return;++ ctx.fillStyle = color;+ ctx.globalAlpha = 0.7;++ const barWidth = width / 256;++ for (let i = 0; i < 256; i++) {+ let normalizedValue: number;+ if (logarithmic && histogram[i] > 0) {+ normalizedValue = Math.log10(histogram[i] + 1) / Math.log10(maxValue + 1);+ } else {+ normalizedValue = histogram[i] / maxValue;+ }++ const barHeight = normalizedValue * height;+ ctx.fillRect(i * barWidth, height - barHeight, barWidth, barHeight);+ }++ ctx.globalAlpha = 1;+}++export function autoLevels(imageData: ImageData, clipPercent: number = 0.1): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const histogram = calculateHistogram(imageData);+ const totalPixels = data.length / 4;+ const clipPixels = Math.round(totalPixels * (clipPercent / 100));++ const findClipPoint = (hist: Uint32Array, fromStart: boolean): number => {+ let count = 0;+ if (fromStart) {+ for (let i = 0; i < 256; i++) {+ count += hist[i];+ if (count > clipPixels) return i;+ }+ return 0;+ } else {+ for (let i = 255; i >= 0; i--) {+ count += hist[i];+ if (count > clipPixels) return i;+ }+ return 255;+ }+ };++ const channels = ['red', 'green', 'blue'] as const;+ const adjustments = channels.map((channel) => {+ const hist = histogram.data[channel];+ const inputBlack = findClipPoint(hist, true);+ const inputWhite = findClipPoint(hist, false);+ return { inputBlack, inputWhite };+ });++ for (let i = 0; i < data.length; i += 4) {+ for (let c = 0; c < 3; c++) {+ const { inputBlack, inputWhite } = adjustments[c];+ const range = inputWhite - inputBlack || 1;+ const value = data[i + c];+ const adjusted = ((value - inputBlack) / range) * 255;+ resultData[i + c] = Math.max(0, Math.min(255, Math.round(adjusted)));+ }+ resultData[i + 3] = data[i + 3];+ }++ return new ImageData(resultData, width, height);+}++export function autoContrast(imageData: ImageData): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ let minLum = 255;+ let maxLum = 0;++ for (let i = 0; i < data.length; i += 4) {+ const lum = Math.round(data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114);+ if (lum < minLum) minLum = lum;+ if (lum > maxLum) maxLum = lum;+ }++ const range = maxLum - minLum || 1;++ for (let i = 0; i < data.length; i += 4) {+ for (let c = 0; c < 3; c++) {+ const adjusted = ((data[i + c] - minLum) / range) * 255;+ resultData[i + c] = Math.max(0, Math.min(255, Math.round(adjusted)));+ }+ resultData[i + 3] = data[i + 3];+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/photo-filter.ts b/apps/image/src/adjustments/photo-filter.tsnew file mode 100644index 00000000..1a8ab36a--- /dev/null+++ b/apps/image/src/adjustments/photo-filter.ts@@ -0,0 +1,117 @@+export type PhotoFilterPreset =+ | 'warming-85'+ | 'warming-81'+ | 'warming-lba'+ | 'cooling-80'+ | 'cooling-82'+ | 'cooling-lbb'+ | 'red'+ | 'orange'+ | 'yellow'+ | 'green'+ | 'cyan'+ | 'blue'+ | 'violet'+ | 'magenta'+ | 'sepia'+ | 'deep-red'+ | 'deep-blue'+ | 'deep-emerald'+ | 'deep-yellow'+ | 'underwater'+ | 'custom';++export interface PhotoFilterSettings {+ filter: PhotoFilterPreset;+ color: string;+ density: number;+ preserveLuminosity: boolean;+}++export const DEFAULT_PHOTO_FILTER: PhotoFilterSettings = {+ filter: 'warming-85',+ color: '#ec8a00',+ density: 25,+ preserveLuminosity: true,+};++export const PHOTO_FILTER_COLORS: Record<PhotoFilterPreset, string> = {+ 'warming-85': '#ec8a00',+ 'warming-81': '#ebb113',+ 'warming-lba': '#fa9600',+ 'cooling-80': '#006dff',+ 'cooling-82': '#00b5ff',+ 'cooling-lbb': '#005fcc',+ red: '#ea1a1a',+ orange: '#f28e00',+ yellow: '#f9d71c',+ green: '#1ab800',+ cyan: '#00e5e5',+ blue: '#0000ff',+ violet: '#8000ff',+ magenta: '#ea00ea',+ sepia: '#ac7a33',+ 'deep-red': '#a10000',+ 'deep-blue': '#000066',+ 'deep-emerald': '#003d00',+ 'deep-yellow': '#998c00',+ underwater: '#00c2b0',+ custom: '#ffffff',+};++function parseColor(color: string): { r: number; g: number; b: number } {+ const match = color.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);+ if (match) {+ return {+ r: parseInt(match[1], 16),+ g: parseInt(match[2], 16),+ b: parseInt(match[3], 16),+ };+ }+ return { r: 255, g: 255, b: 255 };+}++function getLuminance(r: number, g: number, b: number): number {+ return r * 0.299 + g * 0.587 + b * 0.114;+}++export function applyPhotoFilter(imageData: ImageData, settings: PhotoFilterSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const filterColor = settings.filter === 'custom'+ ? parseColor(settings.color)+ : parseColor(PHOTO_FILTER_COLORS[settings.filter]);++ const density = settings.density / 100;++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ const originalLuminance = getLuminance(r, g, b);++ let newR = r + (filterColor.r - r) * density;+ let newG = g + (filterColor.g - g) * density;+ let newB = b + (filterColor.b - b) * density;++ if (settings.preserveLuminosity) {+ const newLuminance = getLuminance(newR, newG, newB);+ if (newLuminance > 0) {+ const ratio = originalLuminance / newLuminance;+ newR *= ratio;+ newG *= ratio;+ newB *= ratio;+ }+ }++ resultData[i] = Math.max(0, Math.min(255, newR));+ resultData[i + 1] = Math.max(0, Math.min(255, newG));+ resultData[i + 2] = Math.max(0, Math.min(255, newB));+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/posterize-threshold.ts b/apps/image/src/adjustments/posterize-threshold.tsnew file mode 100644index 00000000..46ad1f72--- /dev/null+++ b/apps/image/src/adjustments/posterize-threshold.ts@@ -0,0 +1,108 @@+export interface PosterizeSettings {+ levels: number;+}++export interface ThresholdSettings {+ level: number;+}++export const DEFAULT_POSTERIZE: PosterizeSettings = {+ levels: 4,+};++export const DEFAULT_THRESHOLD: ThresholdSettings = {+ level: 128,+};++export function applyPosterize(imageData: ImageData, settings: PosterizeSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const levels = Math.max(2, Math.min(255, Math.round(settings.levels)));+ const step = 255 / (levels - 1);+ const divisor = 256 / levels;++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ resultData[i] = Math.round(Math.floor(r / divisor) * step);+ resultData[i + 1] = Math.round(Math.floor(g / divisor) * step);+ resultData[i + 2] = Math.round(Math.floor(b / divisor) * step);+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}++export function applyThreshold(imageData: ImageData, settings: ThresholdSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const level = Math.max(0, Math.min(255, settings.level));++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ const luminance = r * 0.299 + g * 0.587 + b * 0.114;+ const value = luminance >= level ? 255 : 0;++ resultData[i] = value;+ resultData[i + 1] = value;+ resultData[i + 2] = value;+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}++export function applyAdaptiveThreshold(+ imageData: ImageData,+ blockSize: number = 11,+ constant: number = 2+): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const grayData = new Uint8Array(width * height);+ for (let i = 0; i < data.length; i += 4) {+ const idx = i / 4;+ grayData[idx] = Math.round(data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114);+ }++ const halfBlock = Math.floor(blockSize / 2);++ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ let sum = 0;+ let count = 0;++ for (let by = -halfBlock; by <= halfBlock; by++) {+ for (let bx = -halfBlock; bx <= halfBlock; bx++) {+ const nx = Math.min(Math.max(x + bx, 0), width - 1);+ const ny = Math.min(Math.max(y + by, 0), height - 1);+ sum += grayData[ny * width + nx];+ count++;+ }+ }++ const mean = sum / count;+ const threshold = mean - constant;+ const pixelIdx = y * width + x;+ const value = grayData[pixelIdx] > threshold ? 255 : 0;++ const i = pixelIdx * 4;+ resultData[i] = value;+ resultData[i + 1] = value;+ resultData[i + 2] = value;+ resultData[i + 3] = data[i + 3];+ }+ }++ return new ImageData(resultData, width, height);+}diff --git a/apps/image/src/adjustments/selective-color.ts b/apps/image/src/adjustments/selective-color.tsnew file mode 100644index 00000000..b32a6fdc--- /dev/null+++ b/apps/image/src/adjustments/selective-color.ts@@ -0,0 +1,225 @@+export type SelectiveColorRange =+ | 'reds'+ | 'yellows'+ | 'greens'+ | 'cyans'+ | 'blues'+ | 'magentas'+ | 'whites'+ | 'neutrals'+ | 'blacks';++export interface SelectiveColorAdjustment {+ cyan: number;+ magenta: number;+ yellow: number;+ black: number;+}++export interface SelectiveColorSettings {+ reds: SelectiveColorAdjustment;+ yellows: SelectiveColorAdjustment;+ greens: SelectiveColorAdjustment;+ cyans: SelectiveColorAdjustment;+ blues: SelectiveColorAdjustment;+ magentas: SelectiveColorAdjustment;+ whites: SelectiveColorAdjustment;+ neutrals: SelectiveColorAdjustment;+ blacks: SelectiveColorAdjustment;+ method: 'relative' | 'absolute';+}++const DEFAULT_ADJUSTMENT: SelectiveColorAdjustment = {+ cyan: 0,+ magenta: 0,+ yellow: 0,+ black: 0,+};++export const DEFAULT_SELECTIVE_COLOR: SelectiveColorSettings = {+ reds: { ...DEFAULT_ADJUSTMENT },+ yellows: { ...DEFAULT_ADJUSTMENT },+ greens: { ...DEFAULT_ADJUSTMENT },+ cyans: { ...DEFAULT_ADJUSTMENT },+ blues: { ...DEFAULT_ADJUSTMENT },+ magentas: { ...DEFAULT_ADJUSTMENT },+ whites: { ...DEFAULT_ADJUSTMENT },+ neutrals: { ...DEFAULT_ADJUSTMENT },+ blacks: { ...DEFAULT_ADJUSTMENT },+ method: 'relative',+};++function rgbToHsl(r: number, g: number, b: number): { h: number; s: number; l: number } {+ r /= 255;+ g /= 255;+ b /= 255;++ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;++ if (max === min) {+ return { h: 0, s: 0, l };+ }++ const d = max - min;+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);++ let h: number;+ switch (max) {+ case r:+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;+ break;+ case g:+ h = ((b - r) / d + 2) / 6;+ break;+ default:+ h = ((r - g) / d + 4) / 6;+ break;+ }++ return { h, s, l };+}++function getColorRangeWeight(r: number, g: number, b: number, range: SelectiveColorRange): number {+ const { h, s, l } = rgbToHsl(r, g, b);+ const hue = h * 360;++ switch (range) {+ case 'reds':+ if (s < 0.1) return 0;+ if ((hue >= 345 || hue <= 15)) return s;+ if (hue > 15 && hue <= 45) return s * (1 - (hue - 15) / 30);+ if (hue >= 315 && hue < 345) return s * ((hue - 315) / 30);+ return 0;++ case 'yellows':+ if (s < 0.1) return 0;+ if (hue >= 45 && hue <= 75) return s;+ if (hue > 15 && hue < 45) return s * ((hue - 15) / 30);+ if (hue > 75 && hue <= 105) return s * (1 - (hue - 75) / 30);+ return 0;++ case 'greens':+ if (s < 0.1) return 0;+ if (hue >= 105 && hue <= 135) return s;+ if (hue > 75 && hue < 105) return s * ((hue - 75) / 30);+ if (hue > 135 && hue <= 165) return s * (1 - (hue - 135) / 30);+ return 0;++ case 'cyans':+ if (s < 0.1) return 0;+ if (hue >= 165 && hue <= 195) return s;+ if (hue > 135 && hue < 165) return s * ((hue - 135) / 30);+ if (hue > 195 && hue <= 225) return s * (1 - (hue - 195) / 30);+ return 0;++ case 'blues':+ if (s < 0.1) return 0;+ if (hue >= 225 && hue <= 255) return s;+ if (hue > 195 && hue < 225) return s * ((hue - 195) / 30);+ if (hue > 255 && hue <= 285) return s * (1 - (hue - 255) / 30);+ return 0;++ case 'magentas':+ if (s < 0.1) return 0;+ if (hue >= 285 && hue <= 315) return s;+ if (hue > 255 && hue < 285) return s * ((hue - 255) / 30);+ if (hue > 315 && hue <= 345) return s * (1 - (hue - 315) / 30);+ return 0;++ case 'whites':+ if (l >= 0.8) return (l - 0.8) / 0.2;+ return 0;++ case 'blacks':+ if (l <= 0.2) return (0.2 - l) / 0.2;+ return 0;++ case 'neutrals':+ if (s < 0.2 && l > 0.2 && l < 0.8) {+ return (0.2 - s) / 0.2 * Math.min((l - 0.2) / 0.3, (0.8 - l) / 0.3, 1);+ }+ return 0;+ }+}++function rgbToCmyk(r: number, g: number, b: number): { c: number; m: number; y: number; k: number } {+ r /= 255;+ g /= 255;+ b /= 255;++ const k = 1 - Math.max(r, g, b);+ if (k === 1) {+ return { c: 0, m: 0, y: 0, k: 1 };+ }++ const c = (1 - r - k) / (1 - k);+ const m = (1 - g - k) / (1 - k);+ const y = (1 - b - k) / (1 - k);++ return { c, m, y, k };+}++function cmykToRgb(c: number, m: number, y: number, k: number): { r: number; g: number; b: number } {+ const r = 255 * (1 - c) * (1 - k);+ const g = 255 * (1 - m) * (1 - k);+ const b = 255 * (1 - y) * (1 - k);++ return {+ r: Math.max(0, Math.min(255, Math.round(r))),+ g: Math.max(0, Math.min(255, Math.round(g))),+ b: Math.max(0, Math.min(255, Math.round(b))),+ };+}++export function applySelectiveColor(imageData: ImageData, settings: SelectiveColorSettings): ImageData {+ const { width, height, data } = imageData;+ const resultData = new Uint8ClampedArray(data.length);++ const ranges: SelectiveColorRange[] = [+ 'reds', 'yellows', 'greens', 'cyans', 'blues', 'magentas', 'whites', 'neutrals', 'blacks'+ ];++ for (let i = 0; i < data.length; i += 4) {+ const r = data[i];+ const g = data[i + 1];+ const b = data[i + 2];+ const a = data[i + 3];++ let { c, m, y, k } = rgbToCmyk(r, g, b);++ for (const range of ranges) {+ const weight = getColorRangeWeight(r, g, b, range);+ if (weight <= 0) continue;++ const adj = settings[range];++ if (settings.method === 'relative') {+ c = c + (adj.cyan / 100) * c * weight;+ m = m + (adj.magenta / 100) * m * weight;+ y = y + (adj.yellow / 100) * y * weight;+ k = k + (adj.black / 100) * k * weight;+ } else {+ c = c + (adj.cyan / 100) * weight;+ m = m + (adj.magenta / 100) * weight;+ y = y + (adj.yellow / 100) * weight;+ k = k + (adj.black / 100) * weight;+ }+ }++ c = Math.max(0, Math.min(1, c));+ m = Math.max(0, Math.min(1, m));+ y = Math.max(0, Math.min(1, y));+ k = Math.max(0, Math.min(1, k));++ const rgb = cmykToRgb(c, m, y, k);++ resultData[i] = rgb.r;+ resultData[i + 1] = rgb.g;+ resultData[i + 2] = rgb.b;+ resultData[i + 3] = a;+ }++ return new ImageData(resultData, width, height);+}