resize method

void resize({
  1. int? width,
  2. int? height,
})

Resizes this PImage to the given width and height.

The pixels in this PImage are scaled up or down in the x and y direction, to satisfy the given dimensions.

To scale proportionally, pass in just a width, or just a height. The dimension that you leave out will be scaled up/down to retain the original aspect ratio of this PImage.

Implementation

void resize({
  int? width,
  int? height,
}) {
  if (width == null && height == null) {
    // This indicates no change in size. Don't do anything.
    return;
  }

  final newWidth = (width ?? (height! / this.height) * this.width).toInt();
  final newHeight = (height ?? (width! / this.width) * this.height).toInt();

  final newPixelBuffer = ByteData(newWidth * newHeight * 4);

  for (int x = 0; x < newWidth; x += 1) {
    for (int y = 0; y < newHeight; y += 1) {
      final sampledX = ((x / newWidth) * this.width).round();
      final sampledY = ((y / newHeight) * this.height).round();

      // TODO: de-dup this color calculation with the set() method. Consider creating
      //       a PixelBuffer class
      final argbColorInt = get(sampledX, sampledY).value;
      final rgbaColorInt = ((argbColorInt & 0xFF000000) >> 24) | ((argbColorInt & 0x00FFFFFF) << 8);

      newPixelBuffer.setPixel(newWidth, x, y, Color(rgbaColorInt));
    }
  }

  // Switch the new pixel buffer for the standard pixel buffer in this PImage.
  _pixels = newPixelBuffer;
  _width = newWidth;
  _height = newHeight;

  _isFlutterImageDirty = true;
}