fixQRCodeBMPWithHiddenTransparency function

Image? fixQRCodeBMPWithHiddenTransparency(
  1. Uint8List bytes
)

Rewrites the BMP so that BmpDecoder does not ignore the alpha value

Implementation

Image? fixQRCodeBMPWithHiddenTransparency(Uint8List bytes) {
  // BmpDecoder treats the 4th byte of each pixel as alpha value
  // if the BMP header has more than 40 bytes (see BmpInfo::ignoreAlphaChannel).
  // Therefore we turn the 40 byte BITMAPINFOHEADER into a 52 byte BITMAPV2INFOHEADER.
  // See: https://en.wikipedia.org/wiki/BMP_file_format

  final buffer = InputBuffer(bytes);
  buffer.skip(0x0A);
  final oldDataOffset = buffer.readUint32();
  final oldHeaderSize = buffer.readUint32();
  if (oldHeaderSize != 40) {
    return null;
  }

  final growableBytes = bytes.toList();
  // Set header size to 54 bytes
  growableBytes[0x0E] = 54;
  // Insert 14 zero bytes before the BMP data starts
  growableBytes.insertAll(oldDataOffset, List.filled(14, 0));
  // Adjust the BMP data offset
  final newOffsetBytes = OutputBuffer(bigEndian: false, size: 4)..writeUint32(oldDataOffset + 14);
  growableBytes.replaceRange(0x0A, 0x0E, newOffsetBytes.getBytes().toList());
  return BmpDecoder().decode(Uint8List.fromList(growableBytes));
}