gpuTextureFromImage function Assets and loading

Future<Texture> gpuTextureFromImage(
  1. Image image
)

Uploads a decoded dart:ui ui.Image to a Flutter GPU texture.

The image is read as raw RGBA bytes and copied into a host-visible GPU texture matching the image's dimensions. No mip chain is built, so a minified texture shimmers; prefer Texture2D.fromImage for anything a material samples, and reach for this only when a raw gpu.Texture is what you need (building an EnvironmentMap, interop with a custom pipeline). A material texture slot takes a TextureSource, so wrap the result in GpuTextureSource to bind it.

Throws if the image can't be read as RGBA.

Implementation

Future<gpu.Texture> gpuTextureFromImage(ui.Image image) async {
  // Straight (non-premultiplied) alpha: the material shaders treat a sampled
  // texture as straight and premultiply on output, so a premultiplied source
  // (the rawRgba default) would be multiplied by alpha twice and darken every
  // partially transparent texel. Invisible for opaque images, but it crushes
  // soft-edged content (sprites, cutouts). Mirrors the widget-texture path.
  final byteData = await image.toByteData(
    format: ui.ImageByteFormat.rawStraightRgba,
  );
  if (byteData == null) {
    throw Exception('Failed to get RGBA data from image.');
  }

  // Upload the RGBA image to a Flutter GPU texture.
  final texture = gpu.gpuContext.createTexture(
    gpu.StorageMode.hostVisible,
    image.width,
    image.height,
  );
  texture.overwrite(byteData);

  return texture;
}