Jinsi ya Kupunguza Picha Zilizowekwa katikati Flutter- Mwongozo Rahisi

Ongeza taarifa zinazohitajika za uingizaji wa image kifurushi:

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

Unda chaguo za kukokotoa ili kupunguza na kuhifadhi picha iliyowekwa katikati:

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');  
}  

Piga simu kitendakazi ukitumia njia ya faili ya picha, upana wa mazao, urefu wa mmea, na jina la faili unalotaka:

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);  
}  

Hakikisha kubadilisha 'image_path.png' na njia halisi ya faili yako ya picha. Msimbo utasoma picha, kuhesabu nafasi ya katikati, kuunda mstatili wa mazao kuzunguka, na kisha kupunguza picha kwa kutumia kifurushi image. Picha iliyopunguzwa itahifadhiwa kama faili mpya ya picha ya PNG na jina la faili maalum katika saraka ya hati ya programu. Njia ya faili itachapishwa kwenye koni kwa kumbukumbu yako.

Tena, kumbuka kutumia utunzaji sahihi wa makosa na uangalie maadili yasiyofaa wakati wa kufanya kazi na faili na picha.