convertHeicToJpegBytes method

  1. @override
Future<Uint8List> convertHeicToJpegBytes(
  1. Uint8List bytes
)
override

Implementation

@override
Future<Uint8List> convertHeicToJpegBytes(Uint8List bytes) async {
  // Fast-path: if it doesn't look like HEIC/HEIF, don't touch it.
  if (!_looksLikeHeicOrHeif(bytes)) return bytes;

  try {
    // Providing a MIME type helps libraries that check blob.type.
    final blob = html.Blob(<Object>[bytes], 'image/heic');

    final convertedBlob = await _convertHeicBlob(blob);

    final reader = html.FileReader();
    reader.readAsArrayBuffer(convertedBlob);
    await reader.onLoadEnd.first;

    final error = reader.error;
    if (error != null) {
      throw StateError('FileReader failed: $error');
    }

    final result = reader.result;

    if (result is ByteBuffer) {
      // Most correct/efficient: zero-copy view onto the ArrayBuffer.
      return result.asUint8List();
    }

    // Some interop paths can produce Uint8List directly.
    if (result is Uint8List) {
      return result;
    }

    throw StateError(
      'Unexpected FileReader.result type: ${result.runtimeType}',
    );
  } catch (e) {
    // Best-effort fallback: leave bytes unchanged if conversion fails.
    // ignore: avoid_print
    print('[FlutterImageConversion] Web bytes conversion failed: $e');
    return bytes;
  }
}