Image.fromBytes constructor

Image.fromBytes(
  1. Uint8List bytes, {
  2. StbiChannel desiredChannel = StbiChannel.default_,
  3. StbiDType dtype = StbiDType.u8,
})

Implementation

factory Image.fromBytes(
  Uint8List bytes, {
  StbiChannel desiredChannel = StbiChannel.default_,
  StbiDType dtype = StbiDType.u8,
}) {
  final pBytes = malloc<ffi.Uint8>(bytes.length);
  pBytes.asTypedList(bytes.length).setAll(0, bytes);
  final pW = calloc<ffi.Int>();
  final pH = calloc<ffi.Int>();
  final pChannels = calloc<ffi.Int>();
  final ptr = switch (dtype) {
    StbiDType.u8 => c.stbi_load_from_memory(
      pBytes.cast(),
      bytes.length,
      pW,
      pH,
      pChannels,
      desiredChannel.value,
    ),
    StbiDType.u16 => c.stbi_load_16_from_memory(
      pBytes.cast(),
      bytes.length,
      pW,
      pH,
      pChannels,
      desiredChannel.value,
    ),
    StbiDType.f32 => c.stbi_loadf_from_memory(
      pBytes.cast(),
      bytes.length,
      pW,
      pH,
      pChannels,
      desiredChannel.value,
    ),
  };
  if (ptr == ffi.nullptr) {
    final pMsg = c.stbi_failure_reason();
    throw MNNException("Failed to load image from memory: ${pMsg.cast<Utf8>().toDartString()}");
  }
  final width = pW.value;
  final height = pH.value;
  final channels = pChannels.value;
  calloc.free(pBytes);
  calloc.free(pW);
  calloc.free(pH);
  calloc.free(pChannels);
  return Image.fromPointer(
    ptr,
    width: width,
    height: height,
    channels: channels,
    desiredChannels: desiredChannel,
    dtype: dtype,
  );
}