fromImage static method

Future<Texture2D> fromImage(
  1. Image image, {
  2. TextureContent content = TextureContent.color,
  3. TextureSampling sampling = const TextureSampling(),
  4. bool opaque = false,
})

Builds a texture from a decoded image.

Set opaque when every pixel of image is fully opaque. A texture that then needs no mip chain wraps the image's own GPU texture instead of reading it back and uploading it again. The wrapper keeps the image's storage alive, so image may still be disposed. It is opt-in because the image's texture is premultiplied and the readback is straight alpha, which only agree where alpha is 1. Backends that cannot wrap the image (the web) read it back regardless.

Implementation

static Future<Texture2D> fromImage(
  ui.Image image, {
  TextureContent content = TextureContent.color,
  TextureSampling sampling = const TextureSampling(),
  bool opaque = false,
}) async {
  if (opaque && !(sampling.mipmaps && mipChainsAreSampled)) {
    gpu.Texture? wrapped;
    try {
      wrapped = gpu.Texture.fromImage(gpu.gpuContext, image);
    } on Object {
      wrapped = null;
    }
    if (wrapped != null) {
      return Texture2D._(wrapped, sampling.toSamplerOptions());
    }
  }
  final bytes = await image.toByteData(
    format: ui.ImageByteFormat.rawStraightRgba,
  );
  if (bytes == null) {
    throw Exception('Failed to read RGBA data from image.');
  }
  return fromPixels(
    bytes.buffer.asUint8List(),
    image.width,
    image.height,
    content: content,
    sampling: sampling,
  );
}