encodePngAsWebp function
Encodes PNG bytes as WebP using the platform encoder shipped by webp.
The temporary input/output files are owned by this call and are removed whether encoding succeeds, fails, or throws.
Implementation
Future<Uint8List?> encodePngAsWebp(
Uint8List pngBytes, {
required String benchmarkOperation,
int? resizeWidth,
String? blendAlpha,
}) {
return RunnerBenchmark.async('screenshot', benchmarkOperation, () async {
if (RunnerBenchmark.collector?.disabledExecutables.contains('cwebp') ==
true) {
RunnerBenchmark.dimension('codecFallback', 'controlled-unavailable-webp');
return null;
}
final encoder = await (_encoderPath ??= _resolveEncoderPath());
if (encoder == null) return null;
final temporaryDirectory =
Directory.systemTemp.createTempSync('ensemble_webp_');
try {
final input = File(p.join(temporaryDirectory.path, 'input.png'));
final output = File(p.join(temporaryDirectory.path, 'output.webp'));
input.writeAsBytesSync(pngBytes);
final result = await Process.run(encoder, [
'-quiet',
'-q',
'$_quality',
'-m',
'4',
'-metadata',
'none',
if (resizeWidth != null) ...['-resize', '$resizeWidth', '0'],
if (blendAlpha != null) ...['-blend_alpha', blendAlpha],
input.path,
'-o',
output.path,
]);
if (result.exitCode != 0 || !output.existsSync()) return null;
return output.readAsBytesSync();
} catch (_) {
return null;
} finally {
try {
temporaryDirectory.deleteSync(recursive: true);
} catch (_) {}
}
});
}