Skip to content

Commit

Permalink
Unmultiply colors before brightening
Browse files Browse the repository at this point in the history
  • Loading branch information
jtmcdole committed Dec 14, 2024
1 parent bb734f4 commit 560b0f0
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions packages/flame/lib/src/extensions/image.dart
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,37 @@ extension ImageExtension on Image {
final newPixelData = Uint8List(pixelData.length);

for (var i = 0; i < pixelData.length; i += 4) {
final color = Color.fromARGB(
pixelData[i + 3],
pixelData[i + 0],
pixelData[i + 1],
pixelData[i + 2],
).brighten(amount);

newPixelData[i] = (color.r * 255).round();
newPixelData[i + 1] = (color.g * 255).round();
newPixelData[i + 2] = (color.b * 255).round();
newPixelData[i + 3] = (color.a * 255).round();
final a = pixelData[i + 3] / 255;

// Lets avoid division by zero.
if (a == 0) {
newPixelData[i + 0] = pixelData[i + 0];
newPixelData[i + 1] = pixelData[i + 1];
newPixelData[i + 2] = pixelData[i + 2];
newPixelData[i + 3] = pixelData[i + 3];
continue;
}

// Unmultiply the color
var r = (pixelData[i + 0] / 255) / a;
var g = (pixelData[i + 1] / 255) / a;
var b = (pixelData[i + 2] / 255) / a;

// Brighten in a color accurate way
r = r + (1.0 - r) * amount;
g = g + (1.0 - g) * amount;
b = b + (1.0 - b) * amount;

// Clamp
r = r.clamp(0, 1.0);
g = g.clamp(0, 1.0);
b = b.clamp(0, 1.0);

// Pre-multiply the new color.
newPixelData[i + 0] = (r * a * 255).round();
newPixelData[i + 1] = (g * a * 255).round();
newPixelData[i + 2] = (b * a * 255).round();
newPixelData[i + 3] = pixelData[i + 3];
}
return fromPixels(newPixelData, width, height);
}
Expand Down

0 comments on commit 560b0f0

Please sign in to comment.