Skip to content

Instantly share code, notes, and snippets.

@wamphlett
Created June 12, 2019 00:09
Show Gist options
  • Save wamphlett/9af0af01c6fc7c9e5639d1ed3e185a9e to your computer and use it in GitHub Desktop.
Save wamphlett/9af0af01c6fc7c9e5639d1ed3e185a9e to your computer and use it in GitHub Desktop.
A way to crop an image from an image stream in flutter to always have a 4:3 aspect ratio
// For FlutterNativeImage, see: https://github.com/btastic/flutter_native_image
// Takes the absolute file path
Future<String> resizeImage(String filePath) async {
ImageProperties properties = await FlutterNativeImage.getImageProperties(filePath);
int imageWidth;
int imageHeight;
switch (properties.orientation) {
case ImageOrientation.rotate90:
case ImageOrientation.rotate270:
imageWidth = properties.height;
imageHeight = properties.width;
break;
default:
imageWidth = properties.width;
imageHeight = properties.height;
}
int aspectHeight = ((imageWidth / 3) * 4).round();
// Make sure cropping is required and possible
if (aspectHeight >= imageHeight) {
return filePath;
}
double offset = (imageHeight - aspectHeight) / 2;
File croppedFile;
switch (properties.orientation) {
case ImageOrientation.rotate90:
case ImageOrientation.rotate270:
croppedFile = await FlutterNativeImage.cropImage(
filePath, offset.round(), 0, aspectHeight, imageWidth);
break;
default:
croppedFile = await FlutterNativeImage.cropImage(
filePath, 0, offset.round(), imageWidth, aspectHeight);
}
return croppedFile.path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment