resizePhotoUrl function

Uri resizePhotoUrl(
  1. Uri photoUrl,
  2. {int? quality,
  3. int? width,
  4. int? height,
  5. CropMode? crop,
  6. int? devicePixelRatio,
  7. ImageFormat? format,
  8. bool? autoFormat,
  9. ResizeFitMode? fit,
  10. Map<String, String>? imgixParams}
)

Returns a new Uri, Based on photoUrl, under which a dynamically resized version of the original photo can be accessed.

Unsplash supports dynamic resizing of photos. The transformations applied to the original photo can be configured through a set of query parameters in the requested url.

The officially supported parameters are:

  • width, height : for adjusting the width and height of a photo
  • crop : for applying cropping to the photo
  • format : for converting image format
  • autoFormat : for automatically choosing the optimal image format depending on user browser
  • quality : for changing the compression quality when using lossy file formats
  • fit : for changing the fit of the image within the specified dimensions
  • devicePixelRatio : for adjusting the device pixel ratio of the image

Under the hood unsplash uses imgix. The other parameters offered by Imgix can be used through imgixParams, but unsplash dose not officially support them and may remove support for them at any time in the future.

See: Unsplash docs

Implementation

Uri resizePhotoUrl(
  Uri photoUrl, {
  int? quality,
  int? width,
  int? height,
  CropMode? crop,
  int? devicePixelRatio,
  ImageFormat? format,
  bool? autoFormat,
  ResizeFitMode? fit,
  Map<String, String>? imgixParams,
}) {
  assert(quality.isNull || quality! >= 0 && quality <= 100);
  assert(width.isNull || width! >= 0);
  assert(height.isNull || height! >= 0);
  assert(devicePixelRatio.isNull ||
      devicePixelRatio! >= 0 && devicePixelRatio <= 8);

  // The officially supported params.
  final params = {
    'q': quality?.toString(),
    'w': width?.toString(),
    'h': height?.toString(),
    'crop': crop?.let(enumName),
    'dpi': devicePixelRatio?.toString(),
    'fm': format?.let(enumName),
    if (autoFormat == true) 'auto': 'format',
    'fit': fit?.let(enumName),
  };

  if (imgixParams != null) {
    params.addAll(imgixParams);
  }

  // Make sure the original query parameters are included for view tracking,
  // as required by unsplash.
  params.addAll(photoUrl.queryParameters);

  // Remove params whose value is null.
  params.removeWhereValue(isNull);

  return photoUrl.replace(queryParameters: params);
}