image_helper.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'dart:typed_data';
  2. import 'dart:io';
  3. import 'package:image/image.dart' as img;
  4. import 'package:path_provider/path_provider.dart';
  5. import 'package:exif/exif.dart';
  6. import 'package:share_plus/share_plus.dart';
  7. import 'package:path/path.dart' as path;
  8. class ImageHelper {
  9. // Extract metadata from the selected image
  10. static Future<Map<String, IfdTag>?> extractMetadata(File image) async {
  11. List<int> bytes = await image.readAsBytes();
  12. return readExifFromBytes(bytes);
  13. }
  14. // Save file to a specified directory
  15. static Future<void> saveToDirectory(
  16. File file, String directoryPath, String fileName) async {
  17. final directory = Directory(directoryPath);
  18. if (!await directory.exists()) {
  19. await directory.create(recursive: true);
  20. }
  21. final newPath = path.join(directory.path, fileName);
  22. await file.copy(newPath);
  23. }
  24. // save the Image Without Metadata
  25. static Future<File> saveImageWithoutMetadata(File image) async {
  26. Uint8List bytes = await image.readAsBytes();
  27. img.Image? imgData = img.decodeImage(bytes);
  28. if (imgData != null) {
  29. imgData.exif.clear();
  30. final tempDir = await getTemporaryDirectory();
  31. final tempPath = tempDir.path;
  32. final originalFileName = path.basename(image.path);
  33. // Construct the temporary file path
  34. final tempFilePath = path.join(tempPath, originalFileName);
  35. // Create a File object
  36. final tempFile = File(tempFilePath);
  37. if (originalFileName.toLowerCase().endsWith('.png')) {
  38. await tempFile.writeAsBytes(img.encodePng(imgData));
  39. } else if (originalFileName.toLowerCase().endsWith('.bmp')) {
  40. await tempFile.writeAsBytes(img.encodeBmp(imgData));
  41. } else {
  42. await tempFile.writeAsBytes(img.encodeJpg(imgData));
  43. }
  44. return tempFile;
  45. } else {
  46. throw Exception('Error decoding image.');
  47. }
  48. }
  49. // Share the cleaned image
  50. static Future<void> shareImage(String imagePath) async {
  51. await Share.shareXFiles([XFile(imagePath)],
  52. text: 'Shared Image with Removed Metadata');
  53. }
  54. }