From 2065af481a4dc8b9b3917f138aa7b621092c7d39 Mon Sep 17 00:00:00 2001 From: brendan-duncan Date: Mon, 13 Jan 2025 07:43:47 -0700 Subject: [PATCH] Fix alpha color handling for jpeg encoder --- lib/src/formats/jpeg_encoder.dart | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/src/formats/jpeg_encoder.dart b/lib/src/formats/jpeg_encoder.dart index e17ab447..502c7796 100644 --- a/lib/src/formats/jpeg_encoder.dart +++ b/lib/src/formats/jpeg_encoder.dart @@ -1,5 +1,6 @@ import 'dart:typed_data'; +import '../../image.dart'; import '../color/color.dart'; import '../color/format.dart'; import '../exif/exif_data.dart'; @@ -122,6 +123,8 @@ class JpegEncoder extends Encoder { return fp.getBytes(); } + static const _black = const ConstColorRgb8(0, 0, 0); + void _calculateYUV( Image image, int x, @@ -153,6 +156,14 @@ class JpegEncoder extends Encoder { if (p.format != Format.uint8) { p = p.convert(format: Format.uint8); } + if (p.length > 3) { + final backgroundColor = image.backgroundColor ?? _black; + final a = p.aNormalized; + final invA = 1.0 - a; + p..r = (p.r * a + backgroundColor.r * invA).round() + ..g = (p.g * a + backgroundColor.r * invA).round() + ..b = (p.b * a + backgroundColor.r * invA).round(); + } final r = p.r.toInt(); final g = p.g.toInt(); final b = p.b.toInt();