如何裁剪居中的图像 Flutter- 简单指南

为包添加必要的导入语句 image

import 'dart:io';  
import 'package:image/image.dart' as img;  
import 'package:path_provider/path_provider.dart';  

创建一个函数来裁剪并保存居中图像:

Future<void> cropAndSaveCenteredImage(String imagePath, double cropWidth, double cropHeight, String fileName) async {  
  // Read the image from the file path  
  File imageFile = File(imagePath);  
  List<int> imageBytes = await imageFile.readAsBytes();  
  img.Image image = img.decodeImage(imageBytes);  
  
  // Calculate the center position for cropping  
  int centerX = image.width ~/ 2;  
  int centerY = image.height ~/ 2;  
  
  // Calculate the crop rectangle based on the center position  
  int cropX =(centerX- cropWidth ~/ 2).clamp(0, image.width);  
  int cropY =(centerY- cropHeight ~/ 2).clamp(0, image.height);  
  
  // Crop the image  
  img.Image croppedImage = img.copyCrop(image, cropX, cropY, cropWidth.toInt(), cropHeight.toInt());  
  
  // Get the document directory to save the image  
  Directory directory = await getApplicationDocumentsDirectory();  
  String filePath = '${directory.path}/$fileName.png';  
  
  // Save the image to file  
  File file = File(filePath);  
  await file.writeAsBytes(img.encodePng(croppedImage));  
  
  // Display the file path  
  print('Image saved to: $filePath');  
}  

使用图像文件路径、裁剪宽度、裁剪高度和所需的文件名调用该函数:

void main() async {  
  // Replace 'image_path.png' with the actual path of your image file  
  String imagePath = 'image_path.png';  
  
  // Define the desired crop width and height  
  double cropWidth = 200.0;  
  double cropHeight = 200.0;  
  
  // Define the desired filename(without the extension)  
  String fileName = 'cropped_image';  
  
  // Crop and save the centered image with the specified filename  
  await cropAndSaveCenteredImage(imagePath, cropWidth, cropHeight, fileName);  
}  

确保替换 'image_path.png' 为图像文件的实际路径。 该代码将读取图像,计算中心位置,在其周围创建一个裁剪矩形,然后使用该 image 包裁剪图像。 裁剪后的图像将在应用程序的文档目录中保存为具有自定义文件名的新 PNG 图像文件。 文件路径将打印在控制台中供您参考。

同样,请记住在处理文件和图像时使用适当的错误处理并检查空值。