mirror of
https://github.com/inventree/inventree-app.git
synced 2026-07-21 03:33:23 +00:00
Img upload (#858)
* Refactor existing code for image upload * re-encode cropped image to jpg * Fix UX * prevent crop from blocking UI * change default action
This commit is contained in:
@@ -7,6 +7,7 @@ import "package:inventree/inventree/model.dart";
|
||||
import "package:inventree/inventree/sentry.dart";
|
||||
import "package:inventree/l10.dart";
|
||||
import "package:inventree/widget/fields.dart";
|
||||
import "package:inventree/widget/image_upload.dart";
|
||||
import "package:inventree/widget/snacks.dart";
|
||||
import "package:path/path.dart" as path;
|
||||
|
||||
@@ -136,7 +137,7 @@ class InvenTreeAttachment extends InvenTreeModel {
|
||||
}) async {
|
||||
bool result = false;
|
||||
|
||||
await FilePickerDialog.pickImageFromCamera().then((File? file) {
|
||||
await FilePickerDialog.pickImageFromCamera().then((File? file) async {
|
||||
if (file != null) {
|
||||
String dir = path.dirname(file.path);
|
||||
String ext = path.extension(file.path);
|
||||
@@ -146,17 +147,30 @@ class InvenTreeAttachment extends InvenTreeModel {
|
||||
String filename = "${dir}/${prefix}_image_${now}${ext}";
|
||||
|
||||
try {
|
||||
return file.rename(filename).then((File renamed) {
|
||||
return uploadAttachment(renamed, modelType, modelId).then((
|
||||
success,
|
||||
) {
|
||||
result = success;
|
||||
showSnackIcon(
|
||||
result ? L10().imageUploadSuccess : L10().imageUploadFailure,
|
||||
success: result,
|
||||
);
|
||||
});
|
||||
});
|
||||
final File renamed = await file.rename(filename);
|
||||
final File? processed = await preProcessImage(renamed);
|
||||
|
||||
if (processed == null) {
|
||||
// User cancelled the upload - clean up the renamed capture
|
||||
if (await renamed.exists()) {
|
||||
await renamed.delete().catchError((_) => renamed);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final bool success = await uploadAttachment(
|
||||
processed,
|
||||
modelType,
|
||||
modelId,
|
||||
);
|
||||
|
||||
await cleanupProcessedImage(renamed, processed);
|
||||
|
||||
result = success;
|
||||
showSnackIcon(
|
||||
result ? L10().imageUploadSuccess : L10().imageUploadFailure,
|
||||
success: result,
|
||||
);
|
||||
} catch (error, stackTrace) {
|
||||
sentryReportError("uploadImage", error, stackTrace);
|
||||
showSnackIcon(L10().imageUploadFailure, success: false);
|
||||
|
||||
@@ -388,6 +388,12 @@
|
||||
"cropImage": "Crop Image",
|
||||
"@cropImage": {},
|
||||
|
||||
"cropImagePrompt": "Do you want to crop this image before uploading?",
|
||||
"@cropImagePrompt": {},
|
||||
|
||||
"useOriginal": "Use Original",
|
||||
"@useOriginal": {},
|
||||
|
||||
"customer": "Customer",
|
||||
"@customer": {},
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import "package:one_context/one_context.dart";
|
||||
import "package:inventree/l10.dart";
|
||||
import "package:inventree/app_colors.dart";
|
||||
import "package:inventree/widget/fields.dart";
|
||||
import "package:inventree/widget/image_upload.dart";
|
||||
import "package:inventree/widget/progress.dart";
|
||||
import "package:inventree/widget/snacks.dart";
|
||||
import "package:inventree/widget/refreshable_state.dart";
|
||||
@@ -80,14 +81,23 @@ class _AttachmentWidgetState extends RefreshableState<AttachmentWidget> {
|
||||
Future<void> upload(BuildContext context, File? file) async {
|
||||
if (file == null) return;
|
||||
|
||||
final File? processed = await preProcessImage(file);
|
||||
|
||||
if (processed == null) {
|
||||
// User cancelled the upload
|
||||
return;
|
||||
}
|
||||
|
||||
showLoadingOverlay();
|
||||
|
||||
final bool result = await InvenTreeAttachment().uploadAttachment(
|
||||
file,
|
||||
processed,
|
||||
widget.modelType,
|
||||
widget.modelId,
|
||||
);
|
||||
|
||||
await cleanupProcessedImage(file, processed);
|
||||
|
||||
hideLoadingOverlay();
|
||||
|
||||
if (result) {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import "dart:io";
|
||||
import "dart:typed_data";
|
||||
|
||||
import "package:flutter/foundation.dart" show compute;
|
||||
import "package:flutter/material.dart";
|
||||
import "package:image/image.dart" as img;
|
||||
import "package:one_context/one_context.dart";
|
||||
import "package:path_provider/path_provider.dart" as path_provider;
|
||||
|
||||
import "package:inventree/l10.dart";
|
||||
import "package:inventree/widget/part/image_cropper.dart";
|
||||
|
||||
const List<String> _kImageExtensions = [
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".bmp",
|
||||
".gif",
|
||||
".webp",
|
||||
];
|
||||
|
||||
/// Return true if the provided file appears to be an image, based on its extension
|
||||
bool isImageFile(File file) {
|
||||
final String path = file.path.toLowerCase();
|
||||
return _kImageExtensions.any((ext) => path.endsWith(ext));
|
||||
}
|
||||
|
||||
enum _ImageProcessChoice { crop, useOriginal }
|
||||
|
||||
/*
|
||||
* Common "pre-processing" step for any image file, applied before upload
|
||||
* (regardless of whether the image is destined for a Part, an Attachment, or elsewhere).
|
||||
*
|
||||
* - Files which are not images are returned unchanged.
|
||||
* - Image files prompt the user to either crop the image, or upload it as-is.
|
||||
* - If the user cancels at any point (the initial prompt, or the crop screen itself),
|
||||
* this returns null, and the caller must abort the upload entirely.
|
||||
*/
|
||||
Future<File?> preProcessImage(File imageFile) async {
|
||||
if (!isImageFile(imageFile)) {
|
||||
return imageFile;
|
||||
}
|
||||
|
||||
final _ImageProcessChoice? choice = await OneContext()
|
||||
.showDialog<_ImageProcessChoice>(
|
||||
barrierDismissible: false,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(L10().cropImage),
|
||||
content: Text(L10().cropImagePrompt),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(L10().cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
Navigator.of(context).pop(_ImageProcessChoice.crop),
|
||||
child: Text(L10().crop),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () =>
|
||||
Navigator.of(context).pop(_ImageProcessChoice.useOriginal),
|
||||
child: Text(L10().useOriginal),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (choice == null) {
|
||||
// User cancelled - abort the upload entirely
|
||||
return null;
|
||||
}
|
||||
|
||||
if (choice == _ImageProcessChoice.useOriginal) {
|
||||
return imageFile;
|
||||
}
|
||||
|
||||
final Uint8List imageBytes = await imageFile.readAsBytes();
|
||||
|
||||
final Uint8List? croppedBytes = await OneContext().showDialog<Uint8List>(
|
||||
barrierDismissible: false,
|
||||
builder: (context) => Dialog(
|
||||
insetPadding: const EdgeInsets.all(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
L10().cropImage,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(child: ImageCropperWidget(imageBytes: imageBytes)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (croppedBytes == null) {
|
||||
// User cancelled the crop screen - abort the upload entirely
|
||||
return null;
|
||||
}
|
||||
|
||||
// The crop widget always hands back uncompressed PNG data,
|
||||
// regardless of the source format - re-encode as JPEG so we
|
||||
// don't upload a file many times larger than the original photo.
|
||||
// Run this on a background isolate: decode/encode are synchronous,
|
||||
// CPU-heavy calls that would otherwise freeze the UI thread.
|
||||
final List<int> jpegBytes = await compute(_encodeAsJpeg, croppedBytes);
|
||||
|
||||
final tempDir = await path_provider.getTemporaryDirectory();
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final File tempFile = File("${tempDir.path}/cropped_image_$timestamp.jpg");
|
||||
await tempFile.writeAsBytes(jpegBytes);
|
||||
|
||||
return tempFile;
|
||||
}
|
||||
|
||||
/// Decode [pngBytes] and re-encode as JPEG. Runs on a background isolate via [compute].
|
||||
List<int> _encodeAsJpeg(Uint8List pngBytes) {
|
||||
final img.Image? decoded = img.decodeImage(pngBytes);
|
||||
return decoded != null ? img.encodeJpg(decoded, quality: 90) : pngBytes;
|
||||
}
|
||||
|
||||
/// Delete [processed] if it is a distinct temporary file created by [preProcessImage]
|
||||
Future<void> cleanupProcessedImage(File original, File processed) async {
|
||||
if (processed.path == original.path) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (await processed.exists()) {
|
||||
await processed.delete().catchError((_) => processed);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
import "dart:io";
|
||||
import "dart:typed_data";
|
||||
|
||||
import "package:flutter/material.dart";
|
||||
import "package:path_provider/path_provider.dart" as path_provider;
|
||||
import "package:flutter_tabler_icons/flutter_tabler_icons.dart";
|
||||
import "package:inventree/api.dart";
|
||||
import "package:inventree/inventree/part.dart";
|
||||
import "package:inventree/l10.dart";
|
||||
import "package:inventree/widget/fields.dart";
|
||||
import "package:inventree/widget/part/image_cropper.dart";
|
||||
import "package:inventree/widget/image_upload.dart";
|
||||
import "package:inventree/widget/refreshable_state.dart";
|
||||
import "package:inventree/widget/snacks.dart";
|
||||
|
||||
@@ -34,50 +32,18 @@ class _PartImageState extends RefreshableState<PartImageWidget> {
|
||||
@override
|
||||
String getAppBarTitle() => part.fullname;
|
||||
|
||||
Future<void> _processImageWithCropping(File imageFile) async {
|
||||
Future<void> _uploadImage(File imageFile) async {
|
||||
try {
|
||||
Uint8List imageBytes = await imageFile.readAsBytes();
|
||||
final File? processed = await preProcessImage(imageFile);
|
||||
|
||||
// Show the cropping dialog
|
||||
final Uint8List? croppedBytes = await showDialog<Uint8List>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) => Dialog(
|
||||
insetPadding: const EdgeInsets.all(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
L10().cropImage,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Expanded(child: ImageCropperWidget(imageBytes: imageBytes)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (croppedBytes != null) {
|
||||
imageBytes = croppedBytes;
|
||||
if (processed == null) {
|
||||
// User cancelled the upload
|
||||
return;
|
||||
}
|
||||
|
||||
// Save cropped bytes to a proper temporary file for upload
|
||||
final tempDir = await path_provider.getTemporaryDirectory();
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final tempFile = File("${tempDir.path}/cropped_image_$timestamp.jpg");
|
||||
await tempFile.writeAsBytes(imageBytes);
|
||||
final bool result = await part.uploadImage(processed);
|
||||
|
||||
// Upload the cropped file
|
||||
final result = await part.uploadImage(tempFile);
|
||||
|
||||
// Delete temporary file
|
||||
if (await tempFile.exists()) {
|
||||
await tempFile.delete().catchError((_) => tempFile);
|
||||
}
|
||||
await cleanupProcessedImage(imageFile, processed);
|
||||
|
||||
if (!result) {
|
||||
showSnackIcon(L10().uploadFailed, success: false);
|
||||
@@ -152,7 +118,7 @@ class _PartImageState extends RefreshableState<PartImageWidget> {
|
||||
onPressed: () async {
|
||||
FilePickerDialog.pickFile(
|
||||
onPicked: (File file) async {
|
||||
await _processImageWithCropping(file);
|
||||
await _uploadImage(file);
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user