Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mobile][photos] add lossless JPEG rotation to editor

Priyanshu Dangarec9c802d367b7
diff --git a/mobile/apps/photos/lib/ui/tools/editor/image_editor/image_editor_page.dart b/mobile/apps/photos/lib/ui/tools/editor/image_editor/image_editor_page.dart
index b774d12000..735dd3798f 100644
--- a/mobile/apps/photos/lib/ui/tools/editor/image_editor/image_editor_page.dart
+++ b/mobile/apps/photos/lib/ui/tools/editor/image_editor/image_editor_page.dart
@@ -36,6 +36,7 @@ import "package:photos/ui/tools/editor/image_editor/image_editor_tune_bar.dart";
import "package:photos/ui/viewer/file/detail_page.dart";
import "package:photos/utils/dialog_util.dart";
import "package:photos/utils/image_util.dart";
+import "package:photos/utils/lossless_edits.dart";
import 'package:pro_image_editor/pro_image_editor.dart';
class ImageEditorPage extends StatefulWidget {
@@ -59,47 +60,41 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
final editorKey = GlobalKey<ProImageEditorState>();
final _logger = Logger("ImageEditor");
- Future<void> saveImage(Uint8List? bytes) async {
- if (bytes == null) return;
-
- final dialog = createProgressDialog(
- context,
- AppLocalizations.of(context).saving,
+ Future<Uint8List> compressImage(Uint8List bytes) async {
+ final ui.Image decodedResult = await decodeImageFromList(bytes);
+ var result = await FlutterImageCompress.compressWithList(
+ bytes,
+ minWidth: decodedResult.width,
+ minHeight: decodedResult.height,
+ quality: 95,
+ format: CompressFormat.jpeg,
);
+ if (flagService.internalUser) {
+ try {
+ final image = img.decodePng(bytes);
+ if (image != null) {
+ await copyEXIF(
+ widget.originalFile,
+ image,
+ copyRenderingFields: false,
+ );
+ result = img.encodeJpg(image, quality: 95);
+ }
+ } catch (e, s) {
+ _logger.warning("Image Editor: copyEXIF failed", e, s);
+ }
+ }
+ return result;
+ }
+
+ Future<void> saveImage(Uint8List bytes) async {
+ final l10n = AppLocalizations.of(context);
+ final dialog = createProgressDialog(context, l10n.saving);
await dialog.show();
- debugPrint("Image saved with size: ${bytes.length} bytes");
- final DateTime start = DateTime.now();
bool hasStoppedChangeNotify = false;
try {
- final ui.Image decodedResult = await decodeImageFromList(bytes);
- var result = await FlutterImageCompress.compressWithList(
- bytes,
- minWidth: decodedResult.width,
- minHeight: decodedResult.height,
- quality: 95,
- format: CompressFormat.jpeg,
- );
- if (flagService.internalUser) {
- try {
- final image = img.decodePng(bytes);
- if (image != null) {
- await copyEXIF(
- widget.originalFile,
- image,
- copyRenderingFields: false,
- );
- result = img.encodeJpg(image, quality: 95);
- }
- } catch (e, s) {
- _logger.warning("Image Editor: copyEXIF failed", e, s);
- }
- }
- _logger.info('Size after compression = ${result.length}');
- final Duration diff = DateTime.now().difference(start);
- _logger.info('image_editor time : $diff');
-
final fileName =
path.basenameWithoutExtension(widget.originalFile.title!) +
"_edited_" +
@@ -110,7 +105,7 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
await PhotoManager.stopChangeNotify();
hasStoppedChangeNotify = true;
final AssetEntity newAsset = await (PhotoManager.editor.saveImage(
- result,
+ bytes,
filename: fileName,
));
final newFile = await ente.EnteFile.fromAsset(
@@ -166,7 +161,7 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
} catch (e, s) {
await dialog.hide();
if (mounted) {
- showToast(context, AppLocalizations.of(context).oopsCouldNotSaveEdits);
+ showToast(context, l10n.oopsCouldNotSaveEdits);
}
_logger.severe("Failed to save image edits", e, s);
} finally {
@@ -177,12 +172,13 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
}
Future<void> _showExitConfirmationDialog(BuildContext context) async {
+ final l10n = AppLocalizations.of(context);
final actionResult = await showActionSheet(
context: context,
- title: AppLocalizations.of(context).discardEditsQuestion,
+ title: l10n.discardEditsQuestion,
buttons: [
ButtonWidget(
- labelText: AppLocalizations.of(context).yesDiscardChanges,
+ labelText: l10n.yesDiscardChanges,
buttonType: ButtonType.critical,
buttonSize: ButtonSize.large,
shouldStickToDarkTheme: true,
@@ -190,7 +186,7 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
isInAlert: true,
),
ButtonWidget(
- labelText: AppLocalizations.of(context).no,
+ labelText: l10n.no,
buttonType: ButtonType.secondary,
buttonSize: ButtonSize.large,
buttonAction: ButtonAction.second,
@@ -198,7 +194,7 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
isInAlert: true,
),
],
- body: AppLocalizations.of(context).doYouWantToDiscardTheEditsYouHaveMade,
+ body: l10n.doYouWantToDiscardTheEditsYouHaveMade,
actionSheetType: ActionSheetType.defaultActionSheet,
);
if (!context.mounted) return;
@@ -349,9 +345,20 @@ class _ImageEditorPageState extends State<ImageEditorPage> {
undo: () => editor.undoAction(),
configs: editor.configs,
done: () async {
- final Uint8List bytes = await editorKey.currentState!
- .captureEditorImage();
- await saveImage(bytes);
+ final editor = editorKey.currentState!;
+ final turns = getTurnsIfOnlyRotated(editor);
+ final losslessBytes = turns == null
+ ? null
+ : await tryRotateFileLossless(
+ widget.originalFile,
+ turns,
+ );
+ await saveImage(
+ losslessBytes ??
+ await compressImage(
+ await editor.captureEditorImage(),
+ ),
+ );
},
close: () {
_showExitConfirmationDialog(context);
diff --git a/mobile/apps/photos/lib/utils/lossless_edits.dart b/mobile/apps/photos/lib/utils/lossless_edits.dart
new file mode 100644
index 0000000000..263bcc3d52
--- /dev/null
+++ b/mobile/apps/photos/lib/utils/lossless_edits.dart
@@ -0,0 +1,145 @@
+import "dart:io";
+import "dart:math";
+import "dart:typed_data";
+import "dart:ui";
+
+import "package:image/image.dart" as img;
+import "package:logging/logging.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/utils/file_util.dart";
+import "package:pro_image_editor/pro_image_editor.dart";
+
+final _logger = Logger("lossless_edits");
+
+Future<Uint8List?> tryRotateFileLossless(EnteFile src, int turns) async {
+ try {
+ return _rotateFileLossless(src, turns);
+ } catch (e, s) {
+ _logger.warning("Failed to rotate file losslessly", e, s);
+ return null;
+ }
+}
+
+Future<Uint8List> _rotateFileLossless(EnteFile src, int turns) async {
+ File? f;
+ try {
+ f = await getFile(src, isOrigin: true);
+ if (f == null) {
+ throw Exception("Failed to get file");
+ }
+ final bytes = await f.readAsBytes();
+ final exif = img.decodeJpgExif(bytes);
+ if (exif == null) {
+ throw Exception("Failed to decode JPEG EXIF");
+ }
+ _applyRotationToExif(exif, turns);
+ final out = img.injectJpgExif(bytes, exif);
+ if (out == null) {
+ throw Exception("Failed to inject JPEG EXIF");
+ }
+ return out;
+ } finally {
+ if (f != null && !src.isRemoteOnlyFile && Platform.isIOS) {
+ f.delete().ignore();
+ }
+ }
+}
+
+void _applyRotationToExif(img.ExifData exif, int turns) {
+ final originalTurns = _orientationToTurns(exif.imageIfd.orientation);
+ if (originalTurns == null) {
+ throw Exception("Unsupported EXIF orientation");
+ }
+ final updatedTurns = (originalTurns + turns) % 4;
+ final updatedOrientation = _turnsToOrientation(updatedTurns);
+ exif.imageIfd.orientation = updatedOrientation;
+}
+
+int? _orientationToTurns(int? orientation) {
+ return switch (orientation ?? 1) {
+ 1 => 0,
+ 6 => 1,
+ 3 => 2,
+ 8 => 3,
+ _ => null,
+ };
+}
+
+int _turnsToOrientation(int turns) {
+ return switch (turns % 4) {
+ 1 => 6,
+ 2 => 3,
+ 3 => 8,
+ _ => 1,
+ };
+}
+
+bool isTransformOnlyRotation(TransformConfigs t) {
+ final fullImageRect = Rect.fromLTWH(
+ 0,
+ 0,
+ t.originalSize.width,
+ t.originalSize.height,
+ );
+
+ final isRotationOnly =
+ t.originalSize.width.isFinite &&
+ t.originalSize.height.isFinite &&
+ t.cropRect.left.isFinite &&
+ t.cropRect.top.isFinite &&
+ t.cropRect.right.isFinite &&
+ t.cropRect.bottom.isFinite &&
+ t.angle != 0 &&
+ t.isRectangularCropper &&
+ _isSameRect(t.cropRect, fullImageRect) &&
+ _isSameDouble(t.scaleUser, 1) &&
+ t.aspectRatio == -1 &&
+ t.flipX == false &&
+ t.flipY == false &&
+ _isSameOffset(t.offset, Offset.zero);
+
+ return isRotationOnly;
+}
+
+int? getTurnsIfOnlyRotated(ProImageEditorState editorState) {
+ final stateManager = editorState.stateManager;
+
+ if (stateManager.activeLayers.isNotEmpty) {
+ return null;
+ }
+
+ final blur = stateManager.activeBlur;
+ final filters = stateManager.activeFilters;
+ final tuneAdjustments = stateManager.activeTuneAdjustments;
+ final transformConfigs = stateManager.transformConfigs;
+
+ if (blur != 0.0 || filters.isNotEmpty || tuneAdjustments.isNotEmpty) {
+ return null;
+ }
+
+ if (!isTransformOnlyRotation(transformConfigs)) return null;
+
+ const quarterTurn = pi / 2;
+ final rotations = transformConfigs.angle / quarterTurn;
+
+ if (rotations != rotations.roundToDouble()) {
+ return null;
+ }
+
+ return rotations.toInt();
+}
+
+bool _isSameDouble(double a, double b) {
+ return (a - b).abs() < 0.01;
+}
+
+bool _isSameOffset(Offset a, Offset b) {
+ return _isSameDouble(a.dx, b.dx) && _isSameDouble(a.dy, b.dy);
+}
+
+bool _isSameRect(Rect a, Rect b) {
+ return _isSameDouble(a.left, b.left) &&
+ _isSameDouble(a.top, b.top) &&
+ _isSameDouble(a.right, b.right) &&
+ _isSameDouble(a.bottom, b.bottom);
+}