Yadda Ake Cika Hoto A Cikakke Flutter- Jagora Mai Sauƙi

Ƙara mahimman bayanan shigo da su don image kunshin:

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

Ƙirƙiri aiki don shuka da adana hoton tsakiya:

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

Kira aikin tare da hanyar fayil ɗin hoto, faɗin amfanin gona, tsayin amfanin gona, da sunan fayil ɗin da ake so:

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

Tabbatar maye gurbin 'image_path.png' tare da ainihin hanyar zuwa fayil ɗin hoton ku. Lambar za ta karanta hoton, ƙididdige matsayi na tsakiya, ƙirƙirar rectangular amfanin gona a kusa da shi, sa'an nan kuma yanke hoton ta amfani da image kunshin. Hoton da aka yanke za a adana shi azaman sabon fayil ɗin hoto na PNG tare da sunan fayil na al'ada a cikin kundin adireshin aikace-aikacen. Za a buga hanyar fayil ɗin a cikin na'ura wasan bidiyo don bayanin ku.

Bugu da ƙari, tuna yin amfani da daidaitaccen sarrafa kuskure kuma bincika ƙima mara kyau lokacin aiki tare da fayiloli da hotuna.