|
| 1 | +import 'dart:io'; |
1 | 2 | import 'dart:typed_data'; |
2 | 3 |
|
3 | 4 | import 'package:flutter/material.dart'; |
4 | 5 | import 'package:image/image.dart' as img; |
5 | 6 | import 'package:image_cropper/image_cropper.dart'; |
6 | 7 | import 'package:image_picker/image_picker.dart'; |
| 8 | +import 'package:path_provider/path_provider.dart'; |
7 | 9 |
|
8 | 10 | class ImageLoader extends ChangeNotifier { |
9 | 11 | img.Image? image; |
10 | 12 | final List<img.Image> processedImgs = List.empty(growable: true); |
| 13 | + bool isLoading = false; |
11 | 14 |
|
12 | | - void pickImage({required int width, required int height}) async { |
| 15 | + Future<bool> pickImage({required int width, required int height}) async { |
13 | 16 | final ImagePicker picker = ImagePicker(); |
14 | 17 | final XFile? file = await picker.pickImage(source: ImageSource.gallery); |
15 | | - if (file == null) return; |
| 18 | + if (file == null) return false; |
16 | 19 |
|
17 | 20 | final croppedFile = await ImageCropper().cropImage( |
18 | 21 | sourcePath: file.path, |
19 | | - aspectRatio: |
20 | | - CropAspectRatio(ratioX: width.toDouble(), ratioY: height.toDouble()), |
| 22 | + aspectRatio: CropAspectRatio( |
| 23 | + ratioX: width.toDouble(), |
| 24 | + ratioY: height.toDouble(), |
| 25 | + ), |
21 | 26 | ); |
22 | | - if (croppedFile == null) return; |
| 27 | + if (croppedFile == null) return false; |
23 | 28 |
|
24 | 29 | processedImgs.clear(); |
25 | 30 | image = await img.decodeImageFile(croppedFile.path); |
26 | 31 |
|
27 | 32 | notifyListeners(); |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + Future<void> saveFinalizedImageBytes(Uint8List bytes) async { |
| 37 | + final dir = await getApplicationDocumentsDirectory(); |
| 38 | + final file = File('${dir.path}/last_finalized.png'); |
| 39 | + await file.writeAsBytes(bytes); |
| 40 | + } |
| 41 | + |
| 42 | + Future<void> loadFinalizedImage({ |
| 43 | + required int width, |
| 44 | + required int height, |
| 45 | + }) async { |
| 46 | + isLoading = true; |
| 47 | + notifyListeners(); |
| 48 | + |
| 49 | + try { |
| 50 | + final dir = await getApplicationDocumentsDirectory(); |
| 51 | + final file = File('${dir.path}/last_finalized.png'); |
| 52 | + |
| 53 | + if (await file.exists()) { |
| 54 | + final bytes = await file.readAsBytes(); |
| 55 | + final decoded = img.decodeImage(bytes); |
| 56 | + if (decoded != null) { |
| 57 | + final resized = img.copyResize(decoded, width: width, height: height); |
| 58 | + image = resized; |
| 59 | + } |
| 60 | + } |
| 61 | + } finally { |
| 62 | + isLoading = false; |
| 63 | + notifyListeners(); |
| 64 | + } |
28 | 65 | } |
29 | 66 |
|
30 | 67 | Future<void> updateImage({ |
|
0 commit comments