Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

feat(images): Merge images, pictures one under another or side by side (#645)

KnifeLemond99bef2b9a64
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 736a8dfd..17464aea 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -65,6 +65,10 @@
window, into one file with FFmpeg (`IMediaJoiner`); pictures become PNG through the image engines first. Like the
other one-file jobs, the output follows "subfolder only for several files", and a join that fails or is cancelled
is undone by the job's allocator, which deletes only paths that were the job's own.
+ "Merge images" puts the pictures, in the order picked in the same window (with their layout: one under another or
+ side by side, the same width or their own sizes, a gap and a background), into one image with ImageMagick
+ (`IImageJoiner`), in the first picture's format. Pictures ImageMagick doesn't read become PNG first; a merged image
+ over 200 megapixels is refused with its size.
6. **Report** – progress and results appear in the toast window and in Home → Recent conversions.
Renderers check only the original source for referenced fonts. `ConversionStep.MissingFonts` reports any missing
families to `FileResult.MissingFonts`; the toast card can offer one trusted source, while the CLI and watch jobs
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 8738fcda..adb3cb29 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "لا يستطيع Apple Vision قراءة هذه اللغة. ثبّت Tesseract من الإعدادات ← المحركات",
"error.too_many_frames": "عدد الإطارات كبير جدًا لحفظها كصور. زِد قيمة «كل إطار رقم N»",
"error.too_many_pictures": "عدد الصور كبير جدًا لفيديو واحد، قسّمها على عدة فيديوهات",
+ "error.merged_image_too_large": "ستكون الصورة المدمجة كبيرة جدًا، ادمج صورًا أقل أو أصغر",
"error.over_size_limit": "لا يمكن تصغيره بما يكفي ليناسب حد الحجم",
"error.not_enough_space": "لا توجد مساحة كافية على القرص لحفظ الصور",
"error.no_motion_photo": "لا تحتوي هذه الصورة على فيديو يستطيع Filee قراءته (صورة Motion Photo من Android، أو Live Photo من iPhone مع ملف MOV بجانبها)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "دمج PDF",
"merge.order_title": "اختيار ترتيب الدمج",
"merge.order_hint": "حدّد ملفًا وانقله إلى أعلى أو أسفل. تُدمج الملفات بالترتيب من الأعلى إلى الأسفل. (‎Alt+↑ / Alt+↓‎)",
+ "merge.images_hint": "حدّد صورة وانقلها إلى أعلى أو أسفل. تأتي الأولى في الأعلى، أو على اليسار عند وضع الصور جنبًا إلى جنب. (‎Alt+↑ / Alt+↓‎)",
+ "merge.vertical": "من الأعلى إلى الأسفل",
+ "merge.horizontal": "جنبًا إلى جنب",
+ "merge.same_width": "العرض نفسه",
+ "merge.same_height": "الارتفاع نفسه",
+ "merge.same_size_tip": "يغيّر حجم الصور لتتطابق حوافها. عند الإيقاف تحتفظ كل صورة بحجمها في المنتصف.",
+ "merge.gap": "المسافة (بكسل)",
+ "merge.background": "الخلفية",
+ "merge.transparent": "شفافة",
+ "merge.transparent_tip": "لصيغ PNG وWEBP وغيرها مما يحفظ الشفافية. تصبح هذه المساحة بيضاء في JPG.",
"preset.group_pdf_edit": "تحرير",
"preset.pdf_crop": "اقتصاص PDF",
"preset.pdf_crop.short": "اقتصاص",
@@ -378,6 +389,7 @@
"preset.merge_videos": "دمج الفيديوهات",
"preset.compress_audio": "ضغط الصوت",
"preset.merge_audio": "دمج الصوت",
+ "preset.merge_images": "دمج الصور",
"preset.remove_metadata": "إزالة البيانات الوصفية",
"format.folder": "مجلد",
"format.category.Image": "صورة",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index 154a2512..32a9a3f2 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "Apple Vision kann diese Sprache nicht lesen. Installiere Tesseract unter Einstellungen → Module",
"error.too_many_frames": "Zu viele Einzelbilder zum Speichern. Erhöhe den Wert für „Jedes n-te Einzelbild“",
"error.too_many_pictures": "Zu viele Bilder für ein Video. Teile sie auf mehrere Videos auf",
+ "error.merged_image_too_large": "Das zusammengeführte Bild wäre zu groß. Führe weniger oder kleinere Bilder zusammen",
"error.over_size_limit": "Es lässt sich nicht klein genug für das Größenlimit machen",
"error.not_enough_space": "Nicht genügend freier Speicherplatz für die Bilder",
"error.no_motion_photo": "Dieses Foto enthält kein für Filee lesbares Video (Android Motion Photo oder iPhone Live Photo mit zugehöriger MOV-Datei im selben Ordner)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "PDF zusammenführen",
"merge.order_title": "Reihenfolge festlegen",
"merge.order_hint": "Wähle eine Datei und verschiebe sie nach oben oder unten. Dateien werden von oben nach unten zusammengeführt. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Wähle ein Bild und verschiebe es nach oben oder unten. Das erste kommt nach oben, nebeneinander nach links. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "Untereinander",
+ "merge.horizontal": "Nebeneinander",
+ "merge.same_width": "Gleiche Breite",
+ "merge.same_height": "Gleiche Höhe",
+ "merge.same_size_tip": "Skaliert die Bilder, sodass ihre Kanten bündig sind. Aus: Jedes behält seine Größe und wird zentriert.",
+ "merge.gap": "Abstand (px)",
+ "merge.background": "Hintergrund",
+ "merge.transparent": "Transparent",
+ "merge.transparent_tip": "Für PNG, WEBP und andere Formate mit Transparenz. Ein JPG wird dort weiß.",
"preset.group_pdf_edit": "Bearbeiten",
"preset.pdf_crop": "PDF zuschneiden",
"preset.pdf_crop.short": "Zuschneiden",
@@ -378,6 +389,7 @@
"preset.merge_videos": "Videos zusammenführen",
"preset.compress_audio": "Audio komprimieren",
"preset.merge_audio": "Audio zusammenführen",
+ "preset.merge_images": "Bilder zusammenführen",
"preset.remove_metadata": "Metadaten entfernen",
"format.folder": "Ordner",
"format.category.Image": "Bild",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 4cd5e0eb..534050b1 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision can't read this language. Install Tesseract in Settings → Engines",
"error.too_many_frames": "Too many frames to save as pictures, raise \"Every Nth frame\"",
"error.too_many_pictures": "Too many pictures for one video, split them into several",
+ "error.merged_image_too_large": "The merged picture would be too large, merge fewer or smaller pictures",
"error.over_size_limit": "It can't be made small enough for the size limit",
"error.not_enough_space": "Not enough free disk space for the pictures",
"error.no_motion_photo": "This photo has no video Filee can read (an Android Motion Photo, or an iPhone Live Photo with its MOV next to it)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Merge PDF",
"merge.order_title": "Choose merge order",
"merge.order_hint": "Select a file and move it up or down. Files are merged from top to bottom. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Select a picture and move it up or down. The first one goes at the top, or on the left side by side. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "Top to bottom",
+ "merge.horizontal": "Side by side",
+ "merge.same_width": "Same width",
+ "merge.same_height": "Same height",
+ "merge.same_size_tip": "Scales the pictures so their edges line up. Off: each keeps its own size, centred.",
+ "merge.gap": "Gap (px)",
+ "merge.background": "Background",
+ "merge.transparent": "Transparent",
+ "merge.transparent_tip": "For PNG, WEBP and other formats that keep transparency. A JPG gets white there.",
"preset.group_pdf_edit": "Edit",
"preset.pdf_crop": "Crop PDF",
"preset.pdf_crop.short": "Crop",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Merge videos",
"preset.compress_audio": "Compress audio",
"preset.merge_audio": "Merge audio",
+ "preset.merge_images": "Merge images",
"preset.remove_metadata": "Remove metadata",
"format.folder": "Folder",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 02dab483..ab4adb92 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "Apple Vision no puede leer este idioma. Instala Tesseract en Ajustes → Motores",
"error.too_many_frames": "Demasiados fotogramas para guardar como imágenes; aumenta «Cada N fotogramas»",
"error.too_many_pictures": "Demasiadas imágenes para un vídeo; divídelas en varios",
+ "error.merged_image_too_large": "La imagen unida sería demasiado grande; une menos imágenes o imágenes más pequeñas",
"error.over_size_limit": "No se puede reducir lo suficiente para el límite de tamaño",
"error.not_enough_space": "Espacio libre en disco insuficiente para las imágenes",
"error.no_motion_photo": "Esta foto no tiene un vídeo que Filee pueda leer (una Motion Photo de Android o una Live Photo de iPhone con su MOV al lado)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "Combinar PDF",
"merge.order_title": "Elegir el orden de combinación",
"merge.order_hint": "Selecciona un archivo y muévelo arriba o abajo. Los archivos se combinan de arriba abajo. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Selecciona una imagen y muévela arriba o abajo. La primera va arriba, o a la izquierda si van lado a lado. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "De arriba abajo",
+ "merge.horizontal": "Lado a lado",
+ "merge.same_width": "Mismo ancho",
+ "merge.same_height": "Misma altura",
+ "merge.same_size_tip": "Escala las imágenes para que sus bordes coincidan. Desactivado: cada una conserva su tamaño, centrada.",
+ "merge.gap": "Separación (px)",
+ "merge.background": "Fondo",
+ "merge.transparent": "Transparente",
+ "merge.transparent_tip": "Para PNG, WEBP y otros formatos con transparencia. Un JPG queda en blanco ahí.",
"preset.group_pdf_edit": "Editar",
"preset.pdf_crop": "Recortar PDF",
"preset.pdf_crop.short": "Recortar",
@@ -378,6 +389,7 @@
"preset.merge_videos": "Unir vídeos",
"preset.compress_audio": "Comprimir audio",
"preset.merge_audio": "Unir audio",
+ "preset.merge_images": "Unir imágenes",
"preset.remove_metadata": "Quitar metadatos",
"format.folder": "Carpeta",
"format.category.Image": "Imagen",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 36e31d0f..c9c23977 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision ne lit pas cette langue. Installez Tesseract dans Paramètres → Moteurs",
"error.too_many_frames": "Trop d'images à enregistrer, augmentez « Une image sur N »",
"error.too_many_pictures": "Trop d'images pour une seule vidéo, répartissez-les en plusieurs",
+ "error.merged_image_too_large": "L'image fusionnée serait trop grande, fusionnez moins d'images ou des images plus petites",
"error.over_size_limit": "Impossible de le rendre assez léger pour la taille maximale",
"error.not_enough_space": "Pas assez d'espace disque libre pour les images",
"error.no_motion_photo": "Cette photo ne contient aucune vidéo lisible par Filee (une Motion Photo Android, ou une Live Photo d'iPhone avec son MOV à côté)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Fusionner les PDF",
"merge.order_title": "Choisir l'ordre de fusion",
"merge.order_hint": "Sélectionnez un fichier et déplacez-le vers le haut ou le bas. Les fichiers sont fusionnés de haut en bas. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Sélectionnez une image et déplacez-la vers le haut ou le bas. La première va en haut, ou à gauche côte à côte. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "De haut en bas",
+ "merge.horizontal": "Côte à côte",
+ "merge.same_width": "Même largeur",
+ "merge.same_height": "Même hauteur",
+ "merge.same_size_tip": "Met les images à l'échelle pour aligner leurs bords. Désactivé : chacune garde sa taille, centrée.",
+ "merge.gap": "Espacement (px)",
+ "merge.background": "Arrière-plan",
+ "merge.transparent": "Transparent",
+ "merge.transparent_tip": "Pour PNG, WEBP et les autres formats qui gardent la transparence. Un JPG y devient blanc.",
"preset.group_pdf_edit": "Modifier",
"preset.pdf_crop": "Rogner le PDF",
"preset.pdf_crop.short": "Rogner",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Fusionner les vidéos",
"preset.compress_audio": "Compresser l'audio",
"preset.merge_audio": "Fusionner l'audio",
+ "preset.merge_images": "Fusionner les images",
"preset.remove_metadata": "Supprimer les métadonnées",
"format.folder": "Dossier",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 11dad241..250f366f 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "Apple Vision यह भाषा नहीं पढ़ सकता। सेटिंग्स → इंजन में Tesseract इंस्टॉल करें",
"error.too_many_frames": "तस्वीरों के रूप में सहेजने के लिए बहुत ज़्यादा फ़्रेम हैं, \"हर Nवाँ फ़्रेम\" बढ़ाएँ",
"error.too_many_pictures": "एक वीडियो के लिए तस्वीरें बहुत ज़्यादा हैं, इन्हें कई हिस्सों में बाँटें",
+ "error.merged_image_too_large": "जुड़ी हुई तस्वीर बहुत बड़ी होगी, कम या छोटी तस्वीरें जोड़ें",
"error.over_size_limit": "इसे आकार सीमा जितना छोटा नहीं किया जा सकता",
"error.not_enough_space": "तस्वीरों के लिए डिस्क पर पर्याप्त खाली जगह नहीं है",
"error.no_motion_photo": "इस फ़ोटो में ऐसा कोई वीडियो नहीं है जिसे Filee पढ़ सके (Android मोशन फ़ोटो, या पास में अपनी MOV फ़ाइल वाली iPhone लाइव फ़ोटो)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "PDF मर्ज करें",
"merge.order_title": "मर्ज करने का क्रम चुनें",
"merge.order_hint": "फ़ाइल चुनकर उसे ऊपर या नीचे ले जाएँ। फ़ाइलें ऊपर से नीचे के क्रम में मर्ज होंगी। (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "तस्वीर चुनकर उसे ऊपर या नीचे ले जाएँ। पहली तस्वीर सबसे ऊपर आएगी, या साथ-साथ जोड़ने पर सबसे बाईं ओर। (Alt+↑ / Alt+↓)",
+ "merge.vertical": "ऊपर से नीचे",
+ "merge.horizontal": "साथ-साथ",
+ "merge.same_width": "एक जैसी चौड़ाई",
+ "merge.same_height": "एक जैसी ऊँचाई",
+ "merge.same_size_tip": "तस्वीरों का आकार बदलता है ताकि उनके किनारे मिल जाएँ। बंद होने पर हर तस्वीर अपने आकार में बीच में रहती है।",
+ "merge.gap": "अंतर (px)",
+ "merge.background": "बैकग्राउंड",
+ "merge.transparent": "पारदर्शी",
+ "merge.transparent_tip": "PNG, WEBP और पारदर्शिता रखने वाले दूसरे फ़ॉर्मैट के लिए। JPG में वह जगह सफ़ेद हो जाती है।",
"preset.group_pdf_edit": "संपादित करें",
"preset.pdf_crop": "PDF क्रॉप करें",
"preset.pdf_crop.short": "क्रॉप",
@@ -378,6 +389,7 @@
"preset.merge_videos": "वीडियो जोड़ें",
"preset.compress_audio": "ऑडियो कंप्रेस करें",
"preset.merge_audio": "ऑडियो जोड़ें",
+ "preset.merge_images": "तस्वीरें जोड़ें",
"preset.remove_metadata": "मेटाडेटा हटाएँ",
"format.folder": "फ़ोल्डर",
"format.category.Image": "इमेज",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 5298e5df..9c7ecd6c 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "Apple Vision はこの言語を読めません。「設定」→「変換エンジン」で Tesseract をインストールしてください",
"error.too_many_frames": "画像として保存するフレーム数が多すぎます。「Nフレームごと」の値を大きくしてください",
"error.too_many_pictures": "1本の動画にするには画像が多すぎます。いくつかに分けてください",
+ "error.merged_image_too_large": "結合した画像が大きすぎます。枚数を減らすか、小さい画像で結合してください",
"error.over_size_limit": "サイズ上限に収まるまで小さくできません",
"error.not_enough_space": "画像を保存するための空き容量が不足しています",
"error.no_motion_photo": "この写真には、Fileeが読み取れる動画がありません(Androidのモーションフォト、または隣にMOVがあるiPhoneのLive Photo)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "結合",
"merge.order_title": "結合順序を選択",
"merge.order_hint": "ファイルを選択して上下に移動します。上から順に結合されます。(Alt+↑ / Alt+↓)",
+ "merge.images_hint": "画像を選択して上下に移動します。最初の画像が一番上(横に並べるときは一番左)になります。(Alt+↑ / Alt+↓)",
+ "merge.vertical": "縦に並べる",
+ "merge.horizontal": "横に並べる",
+ "merge.same_width": "幅をそろえる",
+ "merge.same_height": "高さをそろえる",
+ "merge.same_size_tip": "端がそろうように画像を拡大・縮小します。オフにすると元のサイズのまま中央に配置します。",
+ "merge.gap": "間隔 (px)",
+ "merge.background": "背景",
+ "merge.transparent": "透明",
+ "merge.transparent_tip": "PNG、WEBP など透明を保てる形式向けです。JPG ではその部分が白になります。",
"preset.group_pdf_edit": "編集",
"preset.pdf_crop": "PDF をトリミング",
"preset.pdf_crop.short": "トリミング",
@@ -378,6 +389,7 @@
"preset.merge_videos": "動画を結合",
"preset.compress_audio": "音声を圧縮",
"preset.merge_audio": "音声を結合",
+ "preset.merge_images": "画像を結合",
"preset.remove_metadata": "メタデータを削除",
"format.folder": "フォルダー",
"format.category.Image": "画像",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index bb6eb21d..54a32dba 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision은 이 언어를 읽지 못해요. 설정 → 변환 엔진에서 Tesseract를 설치해 주세요",
"error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요",
"error.too_many_pictures": "한 동영상에 넣기엔 사진이 너무 많아요. 여러 번에 나눠 주세요",
+ "error.merged_image_too_large": "합친 이미지가 너무 커요. 사진 수를 줄이거나 더 작은 사진으로 합쳐 주세요",
"error.over_size_limit": "크기 제한에 맞을 만큼 줄일 수 없어요",
"error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
"error.no_motion_photo": "이 사진에서 읽을 수 있는 동영상을 찾지 못했어요 (안드로이드 모션 포토, 또는 옆에 MOV가 있는 아이폰 라이브 포토)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "PDF 병합",
"merge.order_title": "병합 순서 선택",
"merge.order_hint": "파일을 골라 위아래로 옮기세요. 위에서부터 순서대로 병합돼요. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "사진을 골라 위아래로 옮기세요. 첫 번째 사진이 맨 위에, 나란히 붙일 때는 맨 왼쪽에 와요. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "위아래로",
+ "merge.horizontal": "나란히",
+ "merge.same_width": "너비 맞추기",
+ "merge.same_height": "높이 맞추기",
+ "merge.same_size_tip": "가장자리가 맞도록 사진 크기를 맞춰요. 끄면 사진마다 원래 크기로 가운데에 놓여요.",
+ "merge.gap": "간격(px)",
+ "merge.background": "배경",
+ "merge.transparent": "투명",
+ "merge.transparent_tip": "PNG, WEBP처럼 투명을 담는 형식에 쓰여요. JPG는 그 자리가 흰색이 돼요.",
"preset.group_pdf_edit": "편집",
"preset.pdf_crop": "PDF 자르기",
"preset.pdf_crop.short": "자르기",
@@ -388,6 +399,7 @@
"preset.merge_videos": "동영상 합치기",
"preset.compress_audio": "오디오 압축",
"preset.merge_audio": "오디오 합치기",
+ "preset.merge_images": "이미지 합치기",
"preset.remove_metadata": "메타데이터 제거",
"format.folder": "폴더",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 0716ee27..2a7d7753 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -91,6 +91,7 @@
"error.no_transparency": "यो ढाँचामा पारदर्शिता हुँदैन, त्यसैले काट्नुपर्ने केही छैन",
"error.too_many_frames": "छविका रूपमा सुरक्षित गर्न धेरै फ्रेमहरू छन्, \"प्रत्येक N-औं फ्रेम\" बढाउनुहोस्",
"error.too_many_pictures": "एउटा भिडियोका लागि धेरै तस्बिरहरू छन्, तिनलाई केही भागमा बाँड्नुहोस्",
+ "error.merged_image_too_large": "मर्ज गरिएको तस्बिर धेरै ठूलो हुनेछ, कम वा साना तस्बिरहरू मर्ज गर्नुहोस्",
"error.over_size_limit": "यसलाई आकार सीमाभित्र आउने गरी सानो बनाउन सकिएन",
"error.not_enough_space": "छविहरूका लागि डिस्कमा पर्याप्त खाली ठाउँ छैन",
"error.no_motion_photo": "यस तस्बिरमा Filee ले पढ्न सक्ने कुनै भिडियो छैन (Android मोशन फोटो, वा छेउमा MOV भएको iPhone लाइभ फोटो)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "PDF मर्ज गर्नुहोस्",
"merge.order_title": "मर्ज क्रम मिलाउनुहोस्",
"merge.order_hint": "फाइलहरूलाई इच्छित क्रममा मिलाउन तान्नुहोस् र छाड्नुहोस्",
+ "merge.images_hint": "तस्बिर छानेर माथि वा तल सार्नुहोस्। पहिलो तस्बिर सबैभन्दा माथि, वा छेउछेउमा राख्दा सबैभन्दा बायाँ आउँछ। (Alt+↑ / Alt+↓)",
+ "merge.vertical": "माथिदेखि तल",
+ "merge.horizontal": "छेउछेउमा",
+ "merge.same_width": "उही चौडाइ",
+ "merge.same_height": "उही उचाइ",
+ "merge.same_size_tip": "किनारा मिल्ने गरी तस्बिरहरूको आकार मिलाउँछ। बन्द गर्दा हरेक तस्बिर आफ्नै आकारमा बीचमा रहन्छ।",
+ "merge.gap": "बीचको दूरी (px)",
+ "merge.background": "पृष्ठभूमि",
+ "merge.transparent": "पारदर्शी",
+ "merge.transparent_tip": "PNG, WEBP र पारदर्शिता राख्ने अन्य ढाँचाका लागि। JPG मा त्यो ठाउँ सेतो हुन्छ।",
"preset.group_pdf_edit": "सम्पादन",
"preset.pdf_crop": "PDF क्रप गर्नुहोस्",
"preset.pdf_crop.short": "क्रप",
@@ -378,6 +389,7 @@
"preset.merge_videos": "भिडियोहरू मर्ज गर्नुहोस्",
"preset.compress_audio": "अडियो कम्प्रेस गर्नुहोस्",
"preset.merge_audio": "अडियो मर्ज गर्नुहोस्",
+ "preset.merge_images": "तस्बिरहरू मर्ज गर्नुहोस्",
"preset.remove_metadata": "मेटाडाटा हटाउनुहोस्",
"format.folder": "फोल्डर",
"format.category.Image": "छवि",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 7ea3d913..77981400 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision nie czyta tego języka. Zainstaluj Tesseract w Ustawienia → Silniki",
"error.too_many_frames": "Za dużo klatek do zapisania jako obrazy, zwiększ „Co N-ta klatka”",
"error.too_many_pictures": "Za dużo zdjęć na jedno wideo, podziel je na kilka",
+ "error.merged_image_too_large": "Połączony obraz byłby za duży, połącz mniej obrazów lub mniejsze",
"error.over_size_limit": "Nie da się go zmniejszyć do limitu rozmiaru",
"error.not_enough_space": "Za mało wolnego miejsca na dysku na obrazy",
"error.no_motion_photo": "To zdjęcie nie ma wideo, które Filee może odczytać (Motion Photo z Androida lub Live Photo z iPhone'a z plikiem MOV obok)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Połącz PDF",
"merge.order_title": "Wybierz kolejność scalania",
"merge.order_hint": "Wybierz plik i przesuń go w górę lub w dół. Pliki są scalane od góry do dołu. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Wybierz obraz i przesuń go w górę lub w dół. Pierwszy trafia na górę, a przy układzie obok siebie na lewo. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "Jeden pod drugim",
+ "merge.horizontal": "Obok siebie",
+ "merge.same_width": "Ta sama szerokość",
+ "merge.same_height": "Ta sama wysokość",
+ "merge.same_size_tip": "Skaluje obrazy tak, by ich krawędzie się zrównały. Wyłączone: każdy zachowuje swój rozmiar, wyśrodkowany.",
+ "merge.gap": "Odstęp (px)",
+ "merge.background": "Tło",
+ "merge.transparent": "Przezroczyste",
+ "merge.transparent_tip": "Dla PNG, WEBP i innych formatów z przezroczystością. W JPG to miejsce będzie białe.",
"preset.group_pdf_edit": "Edytuj",
"preset.pdf_crop": "Przytnij PDF",
"preset.pdf_crop.short": "Przytnij",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Połącz wideo",
"preset.compress_audio": "Kompresuj dźwięk",
"preset.merge_audio": "Połącz dźwięk",
+ "preset.merge_images": "Połącz obrazy",
"preset.remove_metadata": "Usuń metadane",
"format.folder": "Folder",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 140aa954..ab33d83d 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "O Apple Vision não lê este idioma. Instale o Tesseract em Configurações → Motores",
"error.too_many_frames": "Quadros demais para salvar como imagens. Aumente “A cada N quadros”",
"error.too_many_pictures": "Imagens demais para um vídeo; divida-as em vários",
+ "error.merged_image_too_large": "A imagem final ficaria grande demais; junte menos imagens ou imagens menores",
"error.over_size_limit": "Não foi possível deixá-lo pequeno o suficiente para o limite de tamanho",
"error.not_enough_space": "Não há espaço livre suficiente em disco para as imagens",
"error.no_motion_photo": "Esta foto não tem um vídeo que o Filee consiga ler (uma Motion Photo do Android, ou uma Live Photo do iPhone com o MOV ao lado)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Mesclar PDF",
"merge.order_title": "Escolha a ordem da mesclagem",
"merge.order_hint": "Selecione um arquivo e mova para cima ou para baixo. Os arquivos são mesclados de cima para baixo. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Selecione uma imagem e mova para cima ou para baixo. A primeira fica no topo, ou à esquerda lado a lado. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "De cima para baixo",
+ "merge.horizontal": "Lado a lado",
+ "merge.same_width": "Mesma largura",
+ "merge.same_height": "Mesma altura",
+ "merge.same_size_tip": "Redimensiona as imagens para alinhar as bordas. Desligado: cada uma mantém o tamanho, centralizada.",
+ "merge.gap": "Espaço (px)",
+ "merge.background": "Fundo",
+ "merge.transparent": "Transparente",
+ "merge.transparent_tip": "Para PNG, WEBP e outros formatos com transparência. Em JPG esse espaço fica branco.",
"preset.group_pdf_edit": "Editar",
"preset.pdf_crop": "Recortar PDF",
"preset.pdf_crop.short": "Recortar",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Juntar vídeos",
"preset.compress_audio": "Comprimir áudio",
"preset.merge_audio": "Juntar áudio",
+ "preset.merge_images": "Juntar imagens",
"preset.remove_metadata": "Remover metadados",
"format.folder": "Pasta",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index 05327916..5c1a8d15 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "O Apple Vision não consegue ler este idioma. Instala o Tesseract em Definições → Motores",
"error.too_many_frames": "Há demasiados fotogramas para guardar como imagens. Aumenta o valor de «A cada N fotogramas»",
"error.too_many_pictures": "Há demasiadas imagens para um só vídeo. Divide-as em vários vídeos",
+ "error.merged_image_too_large": "A imagem final seria demasiado grande. Junta menos imagens ou imagens mais pequenas",
"error.over_size_limit": "Não foi possível torná-lo suficientemente pequeno para o limite de tamanho",
"error.not_enough_space": "Não há espaço livre suficiente no disco para as imagens",
"error.no_motion_photo": "Esta fotografia não tem um vídeo que o Filee consiga ler (no interior de uma Motion Photo de Android ou num MOV junto a uma Live Photo de iPhone)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Juntar PDF",
"merge.order_title": "Escolher a ordem dos ficheiros",
"merge.order_hint": "Seleciona um ficheiro e move-o para cima ou para baixo. Os ficheiros são combinados pela ordem da lista, de cima para baixo. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Seleciona uma imagem e move-a para cima ou para baixo. A primeira fica no topo ou, lado a lado, à esquerda. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "De cima para baixo",
+ "merge.horizontal": "Lado a lado",
+ "merge.same_width": "Mesma largura",
+ "merge.same_height": "Mesma altura",
+ "merge.same_size_tip": "Redimensiona as imagens para alinhar os contornos. Desligado: cada uma mantém o seu tamanho, centrada.",
+ "merge.gap": "Espaçamento (px)",
+ "merge.background": "Fundo",
+ "merge.transparent": "Transparente",
+ "merge.transparent_tip": "Para PNG, WEBP e outros formatos com transparência. Num JPG esse espaço fica branco.",
"preset.group_pdf_edit": "Editar",
"preset.pdf_crop": "Recortar PDF",
"preset.pdf_crop.short": "Recortar",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Juntar vídeos",
"preset.compress_audio": "Comprimir áudio",
"preset.merge_audio": "Juntar áudio",
+ "preset.merge_images": "Juntar imagens",
"preset.remove_metadata": "Remover metadados",
"format.folder": "Pasta",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index c6b23149..648c1d4c 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision не читает этот язык. Установите Tesseract в разделе «Настройки → Движки»",
"error.too_many_frames": "Слишком много кадров для сохранения картинками — увеличьте «Каждый N-й кадр»",
"error.too_many_pictures": "Слишком много картинок для одного видео — разделите их на несколько",
+ "error.merged_image_too_large": "Объединённое изображение получится слишком большим — объедините меньше изображений или изображения поменьше",
"error.over_size_limit": "Не удалось уменьшить его до предела размера",
"error.not_enough_space": "Не хватает места на диске для картинок",
"error.no_motion_photo": "В этом фото нет видео, которое Filee может прочитать (Motion Photo с Android или Live Photo с iPhone с файлом MOV рядом)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "Объединить PDF",
"merge.order_title": "Выберите порядок объединения",
"merge.order_hint": "Выберите файл и переместите его вверх или вниз. Файлы объединяются сверху вниз. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Выберите изображение и переместите его вверх или вниз. Первое окажется сверху, а при размещении рядом — слева. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "Сверху вниз",
+ "merge.horizontal": "Рядом",
+ "merge.same_width": "Одинаковая ширина",
+ "merge.same_height": "Одинаковая высота",
+ "merge.same_size_tip": "Масштабирует изображения, чтобы края совпадали. Если выключено, каждое сохраняет свой размер и стоит по центру.",
+ "merge.gap": "Отступ (px)",
+ "merge.background": "Фон",
+ "merge.transparent": "Прозрачный",
+ "merge.transparent_tip": "Для PNG, WEBP и других форматов с прозрачностью. В JPG это место будет белым.",
"preset.group_pdf_edit": "Изменить",
"preset.pdf_crop": "Обрезать PDF",
"preset.pdf_crop.short": "Обрезать",
@@ -388,6 +399,7 @@
"preset.merge_videos": "Объединить видео",
"preset.compress_audio": "Сжать аудио",
"preset.merge_audio": "Объединить аудио",
+ "preset.merge_images": "Объединить изображения",
"preset.remove_metadata": "Удалить метаданные",
"format.folder": "Папка",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index bd33fbba..7be0d125 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -91,6 +91,7 @@
"error.no_transparency": "ฟอร์แมตนี้ไม่มีความโปร่งใส จึงไม่มีขอบให้ตัดออก",
"error.too_many_frames": "มีจำนวนเฟรมมากเกินกว่าจะบันทึกเป็นรูปภาพได้ ลองเพิ่มค่า \"บันทึกทุกๆ N เฟรม\"",
"error.too_many_pictures": "รูปภาพมากเกินไปสำหรับวิดีโอเดียว ลองแบ่งเป็นหลายวิดีโอ",
+ "error.merged_image_too_large": "รูปที่รวมแล้วจะใหญ่เกินไป ลองรวมรูปให้น้อยลงหรือใช้รูปที่เล็กลง",
"error.over_size_limit": "ทำให้เล็กพอสำหรับขนาดสูงสุดไม่ได้",
"error.not_enough_space": "พื้นที่ว่างบนดิสก์ไม่เพียงพอสำหรับการบันทึกรูปภาพ",
"error.no_motion_photo": "รูปภาพนี้ไม่มีวิดีโอที่ Filee สามารถอ่านได้ (เช่น ภาพเคลื่อนไหวของ Android หรือ Live Photo ของ iPhone ที่มีไฟล์ MOV อยู่คู่กัน)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "รวมไฟล์ PDF",
"merge.order_title": "เลือกลำดับการรวมไฟล์",
"merge.order_hint": "เลือกไฟล์แล้วเลื่อนขึ้นหรือลง ไฟล์จะรวมจากบนลงล่าง (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "เลือกรูปแล้วเลื่อนขึ้นหรือลง รูปแรกจะอยู่บนสุด หรืออยู่ซ้ายสุดเมื่อวางเรียงข้างกัน (Alt+↑ / Alt+↓)",
+ "merge.vertical": "บนลงล่าง",
+ "merge.horizontal": "เรียงข้างกัน",
+ "merge.same_width": "ความกว้างเท่ากัน",
+ "merge.same_height": "ความสูงเท่ากัน",
+ "merge.same_size_tip": "ปรับขนาดรูปให้ขอบตรงกัน ถ้าปิด แต่ละรูปจะคงขนาดเดิมและอยู่ตรงกลาง",
+ "merge.gap": "ระยะห่าง (px)",
+ "merge.background": "พื้นหลัง",
+ "merge.transparent": "โปร่งใส",
+ "merge.transparent_tip": "สำหรับ PNG, WEBP และรูปแบบอื่นที่เก็บความโปร่งใสได้ ใน JPG ส่วนนั้นจะเป็นสีขาว",
"preset.group_pdf_edit": "แก้ไข",
"preset.pdf_crop": "ครอบตัด PDF",
"preset.pdf_crop.short": "ครอบตัด",
@@ -378,6 +389,7 @@
"preset.merge_videos": "รวมวิดีโอ",
"preset.compress_audio": "บีบอัดเสียง",
"preset.merge_audio": "รวมไฟล์เสียง",
+ "preset.merge_images": "รวมรูปภาพ",
"preset.remove_metadata": "ลบเมทาดาตา",
"format.folder": "โฟลเดอร์",
"format.category.Image": "รูปภาพ",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 0a0ddf6c..13899f7d 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -91,6 +91,7 @@
"error.ocr_needs_tesseract": "Apple Vision bu dili okuyamıyor. Ayarlar → Dönüştürme motorları bölümünden Tesseract kurun",
"error.too_many_frames": "Görsel olarak kaydedilecek çok fazla kare var; “Her N'inci kare” değerini artırın",
"error.too_many_pictures": "Tek video için çok fazla görsel var; birkaç gruba bölün",
+ "error.merged_image_too_large": "Birleştirilen görsel çok büyük olur; daha az veya daha küçük görsel birleştirin",
"error.over_size_limit": "Boyut sınırına sığacak kadar küçültülemiyor",
"error.not_enough_space": "Görseller için yeterli boş disk alanı yok",
"error.no_motion_photo": "Bu fotoğrafta Filee'nin okuyabileceği video yok (Android Motion Photo veya yanında MOV dosyası bulunan iPhone Live Photo)",
@@ -331,6 +332,16 @@
"preset.merge_pdf": "PDF birleştir",
"merge.order_title": "Birleştirme sırasını seçin",
"merge.order_hint": "Bir dosya seçip yukarı veya aşağı taşıyın. Dosyalar yukarıdan aşağıya birleştirilir. (Alt+↑ / Alt+↓)",
+ "merge.images_hint": "Bir görsel seçip yukarı veya aşağı taşıyın. İlk görsel en üste, yan yana dizilince en sola gelir. (Alt+↑ / Alt+↓)",
+ "merge.vertical": "Alt alta",
+ "merge.horizontal": "Yan yana",
+ "merge.same_width": "Aynı genişlik",
+ "merge.same_height": "Aynı yükseklik",
+ "merge.same_size_tip": "Görselleri kenarları hizalanacak şekilde ölçekler. Kapalıyken her görsel kendi boyutunda ortalanır.",
+ "merge.gap": "Boşluk (px)",
+ "merge.background": "Arka plan",
+ "merge.transparent": "Saydam",
+ "merge.transparent_tip": "PNG, WEBP ve saydamlığı koruyan diğer biçimler için. JPG'de bu alan beyaz olur.",
"preset.group_pdf_edit": "Düzenle",
"preset.pdf_crop": "PDF kırp",
"preset.pdf_crop.short": "Kırp",
@@ -378,6 +389,7 @@
"preset.merge_videos": "Videoları birleştir",
"preset.compress_audio": "Sesi sıkıştır",
"preset.merge_audio": "Sesleri birleştir",
+ "preset.merge_images": "Görselleri birleştir",
"preset.remove_metadata": "Üst veriyi kaldır",
"format.folder": "Klasör",
"format.category.Image": "Görsel",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 7f250fbd..5d5e2034 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision 无法识别此语言。请在“设置 → 转换引擎”中安装 Tesseract",
"error.too_many_frames": "帧数太多,请调大“每 N 帧”",
"error.too_many_pictures": "图片太多,无法放进一个视频,请分成几次",
+ "error.merged_image_too_large": "合并后的图片太大,请减少图片数量或使用更小的图片",
"error.over_size_limit": "无法缩小到大小上限以内",
"error.not_enough_space": "磁盘空间不足,无法保存这些图片",
"error.no_motion_photo": "这张照片中没有可读取的视频(安卓动态照片,或旁边有 MOV 的 iPhone 实况照片)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "合并 PDF",
"merge.order_title": "选择合并顺序",
"merge.order_hint": "选择文件并上下移动。文件将按从上到下的顺序合并。(Alt+↑ / Alt+↓)",
+ "merge.images_hint": "选择图片并上下移动。第一张放在最上面(左右排列时放在最左边)。(Alt+↑ / Alt+↓)",
+ "merge.vertical": "上下排列",
+ "merge.horizontal": "左右排列",
+ "merge.same_width": "统一宽度",
+ "merge.same_height": "统一高度",
+ "merge.same_size_tip": "缩放图片使边缘对齐。关闭时每张图片保持原尺寸并居中。",
+ "merge.gap": "间距 (px)",
+ "merge.background": "背景",
+ "merge.transparent": "透明",
+ "merge.transparent_tip": "适用于 PNG、WEBP 等支持透明的格式。JPG 中该区域会变成白色。",
"preset.group_pdf_edit": "编辑",
"preset.pdf_crop": "裁剪 PDF",
"preset.pdf_crop.short": "裁剪",
@@ -388,6 +399,7 @@
"preset.merge_videos": "合并视频",
"preset.compress_audio": "压缩音频",
"preset.merge_audio": "合并音频",
+ "preset.merge_images": "合并图片",
"preset.remove_metadata": "移除元数据",
"format.folder": "文件夹",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 2d8f1978..49e1f21f 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -97,6 +97,7 @@
"error.ocr_needs_tesseract": "Apple Vision 無法辨識此語言。請在「設定 → 轉換引擎」中安裝 Tesseract",
"error.too_many_frames": "影格數太多,請調大「每 N 個影格」",
"error.too_many_pictures": "圖片太多,無法放進同一部影片,請分成幾次",
+ "error.merged_image_too_large": "合併後的圖片太大,請減少圖片數量或使用較小的圖片",
"error.over_size_limit": "無法縮小到大小上限以內",
"error.not_enough_space": "磁碟空間不足,無法儲存這些圖片",
"error.no_motion_photo": "這張照片中沒有可讀取的影片(Android 動態相片,或旁邊有 MOV 的 iPhone 原況照片)",
@@ -341,6 +342,16 @@
"preset.merge_pdf": "合併 PDF",
"merge.order_title": "選擇合併順序",
"merge.order_hint": "選擇檔案並上下移動。檔案將按從上到下的順序合併。(Alt+↑ / Alt+↓)",
+ "merge.images_hint": "選擇圖片並上下移動。第一張放在最上面(左右排列時放在最左邊)。(Alt+↑ / Alt+↓)",
+ "merge.vertical": "上下排列",
+ "merge.horizontal": "左右排列",
+ "merge.same_width": "統一寬度",
+ "merge.same_height": "統一高度",
+ "merge.same_size_tip": "縮放圖片讓邊緣對齊。關閉時每張圖片保持原尺寸並置中。",
+ "merge.gap": "間距 (px)",
+ "merge.background": "背景",
+ "merge.transparent": "透明",
+ "merge.transparent_tip": "適用於 PNG、WEBP 等支援透明的格式。JPG 中該區域會變成白色。",
"preset.group_pdf_edit": "編輯",
"preset.pdf_crop": "裁剪 PDF",
"preset.pdf_crop.short": "裁剪",
@@ -388,6 +399,7 @@
"preset.merge_videos": "合併影片",
"preset.compress_audio": "壓縮音訊",
"preset.merge_audio": "合併音訊",
+ "preset.merge_images": "合併圖片",
"preset.remove_metadata": "移除中繼資料",
"format.folder": "資料夾",
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
index b4ee3947..377248fe 100644
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -168,6 +168,23 @@ public sealed class PresetAvailability
if (preset.Image.TrimTransparent
&& formats.All(f => !Filee.Engines.Magick.ImageEncoder.HoldsAlpha(preset.TargetFormat == BuiltInData.SameAsSource ? f.Id : preset.TargetFormat)))
return new(PresetUse.Unusable, _loc["error.no_transparency"]);
+ // "Merge images": ImageMagick reads most pictures as they are; others need a route into PNG first.
+ if (preset.JoinsImages)
+ {
+ if (_catalog.All.OfType<IImageJoiner>().FirstOrDefault() is not { } joiner
+ || preset.TargetFormat != BuiltInData.SameAsSource && !joiner.CanWrite(preset.TargetFormat))
+ return new(PresetUse.Unusable, _loc["error.no_route"]);
+ var pictures = formats.Where(f => f.Category is FormatCategory.Image or FormatCategory.Vector).ToList();
+ if (pictures.Count == 0)
+ return new(PresetUse.Unusable, _loc["error.images_only"]);
+ bool Readable(RoutePlanner planner) => pictures.Any(f => joiner.CanRead(f.Id) || planner.CanConvert(f.Id, "png"));
+ if (Readable(installedPlanner()))
+ return new(PresetUse.Usable, null);
+ return packageEnabling(Readable) is { } reader
+ ? new(PresetUse.NeedsPackage, _loc.Format("engine.reason.needs_package", reader.Name))
+ : new(PresetUse.Unusable, _loc["error.no_route"]);
+ }
+
// "Merge videos" / "Merge audio" / "Video from images": FFmpeg joins the files, so a route into the target (or,
// for pictures, into PNG and from PNG into a video) says whether it is installed.
if (preset.JoinsIntoOneMedia)
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index d689f25d..943831e6 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -338,8 +338,8 @@ public sealed class RadialController(
return;
}
- // Merged PDFs, joined clips and slideshows follow the order the user picks.
- if ((preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle || preset.JoinsIntoOneMedia) && sources.Count > 1)
+ // Merged PDFs, joined clips, slideshows and merged pictures follow the order the user picks.
+ if ((preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle || preset.JoinsIntoOneMedia || preset.JoinsImages) && sources.Count > 1)
{
Close(animate: false);
_ = MergeInOrderAsync(sources, preset.Clone(), web);
@@ -371,7 +371,9 @@ public sealed class RadialController(
{
try
{
- var ordered = await windows.ChooseMergeOrderAsync(files);
+ var ordered = await windows.ChooseMergeOrderAsync(files, preset);
+ if (ordered is not null && preset.JoinsImages)
+ RememberMergeLayout(preset);
if (ordered is not null && preset.Output.AskEveryTime && web is null)
await AskThenConvertAsync(ordered, preset);
else if (ordered is not null)
@@ -382,7 +384,7 @@ public sealed class RadialController(
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
- log.LogError(ex, "Could not start the ordered PDF merge");
+ log.LogError(ex, "Could not start the ordered merge");
}
finally
{
@@ -390,6 +392,32 @@ public sealed class RadialController(
}
}
+ /// <summary>
+ /// "Merge images": the layout chosen in the merge order window (<paramref name="chosen"/>, a copy of the preset)
+ /// goes into the preset as saved, so the window opens with it next time.
+ /// </summary>
+ private void RememberMergeLayout(Preset chosen)
+ {
+ if (store.FindPreset(chosen.Id) is not { JoinsImages: true } saved)
+ return;
+ var image = saved.Image;
+ if (image.JoinDirection == chosen.Image.JoinDirection && image.JoinFit == chosen.Image.JoinFit
+ && image.JoinGap == chosen.Image.JoinGap && image.JoinBackground == chosen.Image.JoinBackground)
+ return;
+ image.JoinDirection = chosen.Image.JoinDirection;
+ image.JoinFit = chosen.Image.JoinFit;
+ image.JoinGap = chosen.Image.JoinGap;
+ image.JoinBackground = chosen.Image.JoinBackground;
+ try
+ {
+ store.SaveLibrary();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ log.LogWarning(ex, "Could not remember the layout of merged pictures");
+ }
+ }
+
private async Task AskThenConvertAsync(IReadOnlyList<string> sources, Preset preset)
{
try
diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs
index c6c23879..1c16baa6 100644
--- a/src/Filee.App/Services/WindowService.cs
+++ b/src/Filee.App/Services/WindowService.cs
@@ -49,11 +49,24 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
private void PrepareWindow(Window window) => services.GetService<ThemeService>()?.ApplyWindowClass(window);
- /// <summary>Reviews the order of a PDF merge. Closing or cancelling starts no conversion.</summary>
- public async Task<IReadOnlyList<string>?> ChooseMergeOrderAsync(IReadOnlyList<string> files)
+ /// <summary>
+ /// Reviews the order of a merge (<paramref name="preset"/>, when given, names the button). For "Merge images" the
+ /// layout is chosen too and written into <paramref name="preset"/>. Closing or cancelling starts no conversion.
+ /// </summary>
+ public async Task<IReadOnlyList<string>?> ChooseMergeOrderAsync(IReadOnlyList<string> files, Preset? preset = null)
{
_mergeOrder?.Close();
- var dialog = new MergeOrderWindow { DataContext = new MergeOrderViewModel(files) };
+ var images = preset is { JoinsImages: true };
+ var vm = new MergeOrderViewModel(files, images ? preset!.Image : null);
+ var dialog = new MergeOrderWindow { DataContext = vm };
+ if (preset is not null)
+ dialog.StartMerge.Content = loc.DisplayName(preset);
+ if (images)
+ {
+ // Room for the layout below the list.
+ dialog.Height = 640;
+ dialog.MinHeight = 540;
+ }
PrepareWindow(dialog);
var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
dialog.Closed += (_, _) =>
@@ -65,6 +78,8 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
dialog.Show();
dialog.Activate();
await closed.Task;
+ if (dialog.Result is not null && images)
+ vm.ApplyTo(preset!.Image);
return dialog.Result;
}
diff --git a/src/Filee.App/ViewModels/MergeOrderViewModel.cs b/src/Filee.App/ViewModels/MergeOrderViewModel.cs
index 0cf1a743..7710534b 100644
--- a/src/Filee.App/ViewModels/MergeOrderViewModel.cs
+++ b/src/Filee.App/ViewModels/MergeOrderViewModel.cs
@@ -1,10 +1,14 @@
-// The order of a merge into one PDF (issue #268): the files start sorted by name the way people count ("page 2" before
-// "page 10"), and the user moves them before the merge starts. Moving a row changes only this copy of the selection.
+// The order of a merge into one PDF (issue #268), one video or one image (#645): the files start sorted by name the way
+// people count ("page 2" before "page 10"), and the user moves them before the merge starts. Moving a row changes only
+// this copy of the selection. Pictures merged into one image also get their layout here: one under another or side by
+// side, the same width or their own sizes, the gap and the background.
using System.Collections.ObjectModel;
+using Avalonia.Media;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Filee.Core.Platform;
+using Filee.Core.Presets;
using Filee.Core.Web;
namespace Filee.App.ViewModels;
@@ -19,17 +23,91 @@ public sealed class MergeSource(string path)
public sealed partial class MergeOrderViewModel : ObservableObject
{
- public MergeOrderViewModel(IReadOnlyList<string> files)
+ /// <param name="files">The files to merge.</param>
+ /// <param name="images">
+ /// "Merge images" (#645): the layout the pictures are merged with last time, which the window also offers to change.
+ /// Null for other merges.
+ /// </param>
+ public MergeOrderViewModel(IReadOnlyList<string> files, ImageOptions? images = null)
{
Files = new(files
.OrderBy(file => System.IO.Path.GetFileName(file), NaturalComparer.Instance)
.ThenBy(file => file, NaturalComparer.Instance)
.Select(file => new MergeSource(file)));
SelectedFile = Files.FirstOrDefault();
+ if (images is null)
+ return;
+ MergesImages = true;
+ _sideBySide = images.JoinDirection == ImageJoinDirection.Horizontal;
+ _sameSize = images.JoinFit == ImageJoinFit.SameSize;
+ _gap = images.JoinSpacing;
+ _transparent = string.Equals(images.JoinBackground, ImageOptions.TransparentJoin, StringComparison.OrdinalIgnoreCase);
+ _backgroundColor = !_transparent && Color.TryParse(images.JoinBackground, out var colour) ? Color.FromRgb(colour.R, colour.G, colour.B) : Colors.White;
+ _backgroundHex = Hex(_backgroundColor);
}
public ObservableCollection<MergeSource> Files { get; }
+ /// <summary>The files are pictures that become one image: the window shows the layout too.</summary>
+ public bool MergesImages { get; }
+
+ /// <summary>Side by side (the first on the left); otherwise one under another (the first at the top).</summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(TopToBottom))]
+ private bool _sideBySide;
+
+ public bool TopToBottom
+ {
+ get => !SideBySide;
+ set => SideBySide = !value;
+ }
+
+ /// <summary>Pictures of different sizes scaled to the same width (or height side by side); otherwise kept, centred.</summary>
+ [ObservableProperty]
+ private bool _sameSize = true;
+
+ /// <summary>Pixels between two pictures.</summary>
+ [ObservableProperty]
+ private int _gap;
+
+ [ObservableProperty]
+ private Color _backgroundColor = Colors.White;
+
+ /// <summary><see cref="BackgroundColor"/> as <c>#RRGGBB</c>, to type one (as on the Theme page).</summary>
+ [ObservableProperty]
+ private string _backgroundHex = "#FFFFFF";
+
+ partial void OnBackgroundColorChanged(Color value)
+ {
+ var hex = Hex(value);
+ if (!string.Equals(BackgroundHex, hex, StringComparison.OrdinalIgnoreCase))
+ BackgroundHex = hex;
+ }
+
+ partial void OnBackgroundHexChanged(string value)
+ {
+ if (Color.TryParse(value.Trim(), out var colour) && Color.FromRgb(colour.R, colour.G, colour.B) is var opaque && opaque != BackgroundColor)
+ BackgroundColor = opaque;
+ }
+
+ private static string Hex(Color colour) => $"#{colour.R:X2}{colour.G:X2}{colour.B:X2}";
+
+ /// <summary>A see-through background instead of <see cref="BackgroundColor"/> (in a format that holds one).</summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(PicksColor))]
+ private bool _transparent;
+
+ public bool PicksColor => !Transparent;
+
+ /// <summary>Writes the layout chosen here into <paramref name="image"/>.</summary>
+ public void ApplyTo(ImageOptions image)
+ {
+ image.JoinDirection = SideBySide ? ImageJoinDirection.Horizontal : ImageJoinDirection.Vertical;
+ image.JoinFit = SameSize ? ImageJoinFit.SameSize : ImageJoinFit.Original;
+ image.JoinGap = Math.Clamp(Gap, 0, ImageOptions.MaxJoinGap);
+ image.JoinBackground = Transparent ? ImageOptions.TransparentJoin : Hex(BackgroundColor);
+ }
+
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(MoveUpCommand))]
[NotifyCanExecuteChangedFor(nameof(MoveDownCommand))]
diff --git a/src/Filee.App/Views/MergeOrderWindow.axaml b/src/Filee.App/Views/MergeOrderWindow.axaml
index aa913b68..5f5cb502 100644
--- a/src/Filee.App/Views/MergeOrderWindow.axaml
+++ b/src/Filee.App/Views/MergeOrderWindow.axaml
@@ -1,5 +1,6 @@
-<!-- Merge order: shown before files merge into one PDF from the donut (RadialController, issue #268). Merge starts the
- conversion in the order shown; Cancel or closing the window starts nothing. -->
+<!-- Merge order: shown before files merge into one PDF, video or image from the donut (RadialController, issue #268).
+ Merge starts the conversion in the order shown; Cancel or closing the window starts nothing. Pictures merged into
+ one image (#645) also get their layout here, below the list. -->
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:Filee.App.ViewModels"
@@ -13,6 +14,53 @@
<KeyBinding Gesture="Alt+Up" Command="{Binding MoveUpCommand}" />
<KeyBinding Gesture="Alt+Down" Command="{Binding MoveDownCommand}" />
</Window.KeyBindings>
+ <Window.Styles>
+ <!-- One under another / side by side: two segments in a pill, the chosen one filled with the accent (as the
+ toolbar editor's Front / Back switch). -->
+ <Style Selector="Border.directions">
+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />
+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />
+ <Setter Property="BorderThickness" Value="1" />
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="Padding" Value="3" />
+ </Style>
+ <Style Selector="RadioButton.direction">
+ <Setter Property="Background" Value="Transparent" />
+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />
+ <Setter Property="FontWeight" Value="SemiBold" />
+ <Setter Property="Cursor" Value="Hand" />
+ <Setter Property="Template">
+ <ControlTemplate>
+ <Border Background="{TemplateBinding Background}" CornerRadius="999" Padding="12,5">
+ <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"
+ Foreground="{TemplateBinding Foreground}" />
+ </Border>
+ </ControlTemplate>
+ </Setter>
+ </Style>
+ <Style Selector="RadioButton.direction:pointerover">
+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
+ </Style>
+ <Style Selector="RadioButton.direction:checked">
+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />
+ <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />
+ </Style>
+ <Style Selector="RadioButton.direction:focus-visible /template/ Border">
+ <Setter Property="BorderBrush" Value="{DynamicResource TextPrimaryBrush}" />
+ <Setter Property="BorderThickness" Value="2" />
+ </Style>
+ <!-- The colour's swatch fills the button: a white one would vanish into a white button, so the button keeps the
+ card's colour around it. -->
+ <Style Selector="ColorPicker#BackgroundPicker /template/ DropDownButton">
+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />
+ <Setter Property="BorderBrush" Value="{DynamicResource TextSecondaryBrush}" />
+ </Style>
+ <Style Selector="WrapPanel.layout > :is(Control)">
+ <Setter Property="Margin" Value="0,0,12,0" />
+ <Setter Property="MinHeight" Value="36" />
+ <Setter Property="VerticalAlignment" Value="Center" />
+ </Style>
+ </Window.Styles>
<DockPanel>
<Border DockPanel.Dock="Bottom" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{DynamicResource SubtleBorderBrush}"
Background="{DynamicResource SurfaceBrush}">
@@ -36,8 +84,50 @@
<DockPanel Margin="20,18,20,14">
<StackPanel DockPanel.Dock="Top" Spacing="6" Margin="0,0,0,12">
<TextBlock Classes="h2" Text="{DynamicResource merge.order_title}" />
- <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource merge.order_hint}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource merge.order_hint}" IsVisible="{Binding !MergesImages}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource merge.images_hint}" IsVisible="{Binding MergesImages}" />
</StackPanel>
+ <!-- "Merge images": how the pictures are laid out. -->
+ <Border x:Name="MergeLayout" DockPanel.Dock="Bottom" Margin="0,12,0,0" Padding="14,12" CornerRadius="10"
+ Background="{DynamicResource SurfaceAltBrush}" IsVisible="{Binding MergesImages}">
+ <Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto" ColumnSpacing="12" RowSpacing="10">
+ <!-- The direction, and next to it (below it when there's no room) whether the sizes line up. -->
+ <WrapPanel Grid.ColumnSpan="2" Classes="layout">
+ <Border Classes="directions">
+ <StackPanel Orientation="Horizontal">
+ <RadioButton x:Name="TopToBottom" Classes="direction" GroupName="MergeDirection" IsChecked="{Binding TopToBottom}"
+ Content="{DynamicResource merge.vertical}" AutomationProperties.Name="{DynamicResource merge.vertical}" />
+ <RadioButton x:Name="SideBySide" Classes="direction" GroupName="MergeDirection" IsChecked="{Binding SideBySide}"
+ Content="{DynamicResource merge.horizontal}" AutomationProperties.Name="{DynamicResource merge.horizontal}" />
+ </StackPanel>
+ </Border>
+ <Panel>
+ <CheckBox x:Name="SameWidth" Content="{DynamicResource merge.same_width}" IsChecked="{Binding SameSize}"
+ IsVisible="{Binding TopToBottom}" ToolTip.Tip="{DynamicResource merge.same_size_tip}" />
+ <CheckBox x:Name="SameHeight" Content="{DynamicResource merge.same_height}" IsChecked="{Binding SameSize}"
+ IsVisible="{Binding SideBySide}" ToolTip.Tip="{DynamicResource merge.same_size_tip}" />
+ </Panel>
+ </WrapPanel>
+ <TextBlock Grid.Row="1" Classes="label" Margin="0" VerticalAlignment="Center" Text="{DynamicResource merge.gap}" />
+ <NumericUpDown x:Name="GapBox" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" Value="{Binding Gap}" Minimum="0"
+ Maximum="1000" Increment="1" FormatString="0" Width="64" ShowButtonSpinner="False" HorizontalContentAlignment="Center"
+ AutomationProperties.Name="{DynamicResource merge.gap}" />
+ <TextBlock Grid.Row="2" Classes="label" Margin="0" VerticalAlignment="Center" Text="{DynamicResource merge.background}" />
+ <!-- The colour, picked or typed as on the Theme page, or none. -->
+ <WrapPanel Grid.Row="2" Grid.Column="1" Classes="layout">
+ <StackPanel Orientation="Horizontal" Spacing="6" IsEnabled="{Binding PicksColor}">
+ <ColorPicker x:Name="BackgroundPicker" Color="{Binding BackgroundColor, Mode=TwoWay}"
+ IsAlphaEnabled="False" IsAlphaVisible="False" IsColorSpectrumVisible="True" IsColorPaletteVisible="False"
+ IsColorComponentsVisible="False" IsColorModelVisible="False" IsColorPreviewVisible="True"
+ FlowDirection="LeftToRight" MinWidth="64" AutomationProperties.Name="{DynamicResource merge.background}" />
+ <TextBox x:Name="BackgroundHex" Text="{Binding BackgroundHex}" Width="84" PlaceholderText="#FFFFFF" FlowDirection="LeftToRight"
+ AutomationProperties.Name="{DynamicResource merge.background}" />
+ </StackPanel>
+ <CheckBox x:Name="Transparent" Content="{DynamicResource merge.transparent}" IsChecked="{Binding Transparent}"
+ ToolTip.Tip="{DynamicResource merge.transparent_tip}" />
+ </WrapPanel>
+ </Grid>
+ </Border>
<ListBox x:Name="FileOrder" ItemsSource="{Binding Files}" SelectedItem="{Binding SelectedFile}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.Styles>
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 1d835c29..7dfbce73 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -259,6 +259,30 @@ public interface IMediaJoiner
string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken);
}
+/// <summary>
+/// Puts several pictures into one image, one under another or side by side ("Merge images"). Implemented by the
+/// ImageMagick engine; <see cref="JobQueue"/> uses it when a preset merges pictures (<see cref="Preset.JoinsImages"/>).
+/// </summary>
+public interface IImageJoiner
+{
+ /// <summary>True if pictures of <paramref name="format"/> are read as they are; others become PNG first.</summary>
+ bool CanRead(string format);
+
+ /// <summary>True if the merged image can be written as <paramref name="format"/>.</summary>
+ bool CanWrite(string format);
+
+ /// <summary>
+ /// Writes the pictures of <paramref name="inputs"/>, in order, into one image laid out as
+ /// <paramref name="options"/> say (<see cref="ImageOptions.JoinDirection"/>, …). Refuses with
+ /// <c>error.merged_image_too_large</c> when the image would be too large to make.
+ /// </summary>
+ /// <param name="inputs">Each picture and its format id.</param>
+ /// <param name="outputPath">File to create.</param>
+ /// <param name="format">Target format id, one <see cref="CanWrite"/> takes.</param>
+ Task JoinAsync(IReadOnlyList<(string Path, string Format)> inputs, string outputPath, string format, ImageOptions options,
+ IProgress<double>? progress, CancellationToken cancellationToken);
+}
+
/// <summary>
/// Packs several files, unchanged, into one archive ("Compress into one archive"). Implemented by the archive engine;
/// <see cref="JobQueue"/> uses it when a preset sets <see cref="ArchiveOptions.CombineIntoOne"/>.
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index f826f669..b8d8ab01 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -113,9 +113,13 @@ public sealed class JobQueue : IAsyncDisposable
var multiPageTiff = job.Preset.Image.MultiPageTiff && job.Preset.TargetFormat == "tiff" && _tiffMerger is not null;
// Clips back to back, or pictures one after the other, in the order they were dropped.
var join = job.Preset.JoinsIntoOneMedia && _mediaJoiner is not null;
+ // Pictures one under another or side by side, in the order they were dropped.
+ var imageJoiner = job.Preset.JoinsImages ? _catalog.All.OfType<IImageJoiner>().FirstOrDefault() : null;
if (join)
await RunJoinedMediaAsync(job, planner, workDir);
+ else if (imageJoiner is not null)
+ await RunMergedImagesAsync(job, planner, workDir, imageJoiner);
else if (merge)
await RunMergedAsync(job, planner, workDir);
else if (multiPageTiff)
@@ -361,8 +365,11 @@ public sealed class JobQueue : IAsyncDisposable
Notify(job);
}
- /// <summary>Share of a slideshow's progress that preparing its pictures takes; encoding the video fills the rest.</summary>
- private const double SlidesReadyShare = 0.3;
+ /// <summary>
+ /// Share of a slideshow's (or a merge of pictures') progress that preparing its pictures takes; encoding the video
+ /// (or merging) fills the rest.
+ /// </summary>
+ private const double PicturesReadyShare = 0.3;
/// <summary>
/// "Merge videos" / "Merge audio": the videos or audio files go into one file as they are. "Video from images":
@@ -406,7 +413,7 @@ public sealed class JobQueue : IAsyncDisposable
parts[i] = source.Id == "png" && !job.Preset.Image.TurnsOrMirrors
? [file.SourcePath]
: await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false, intermediate: "png",
- ceiling: SlidesReadyShare);
+ ceiling: PicturesReadyShare);
return;
}
// A video's sound can join an audio file; a picture or a document joins nothing.
@@ -428,9 +435,73 @@ public sealed class JobQueue : IAsyncDisposable
return;
}
+ await WriteJoinedAsync(job, joined, inputs.Count, target.PrimaryExtension,
+ (output, progress) => _mediaJoiner!.JoinAsync(inputs, output, target.Id, job.Preset, workDir, progress, job.CancellationToken));
+ }
+
+ /// <summary>
+ /// "Merge images": the pictures go, in order, into one image named after the first, in the first one's format for
+ /// "same as source" (PNG when that one can't be written). A picture the joiner doesn't read as it is (ICNS, JPEG XR,
+ /// SVG, …) becomes a plain PNG in the work directory first; the preset's options apply once, as the pictures merge.
+ /// </summary>
+ private async Task RunMergedImagesAsync(ConversionJob job, RoutePlanner planner, string workDir, IImageJoiner joiner)
+ {
+ var plain = new Preset { TargetFormat = "png", Pdf = { RenderDpi = job.Preset.Pdf.RenderDpi } };
+ var parts = new (string Path, string Format)?[job.Files.Count];
+ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count),
+ new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
+ async (i, _) =>
+ {
+ var file = job.Files[i];
+ if (Stopped(file))
+ return;
+ var source = FormatRegistry.Detect(file.SourcePath);
+ if (source is null)
+ FailFile(job, file, "error.unsupported_source", "." + FormatRegistry.ExtensionOf(file.SourcePath));
+ else if (IsEmptyFile(file.SourcePath))
+ FailFile(job, file, "error.empty_file", null);
+ else if (source.Category is not (FormatCategory.Image or FormatCategory.Vector))
+ FailFile(job, file, "error.images_only", null);
+ else if (joiner.CanRead(source.Id))
+ parts[i] = (file.SourcePath, source.Id);
+ else if (await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false, intermediate: "png",
+ ceiling: PicturesReadyShare, options: plain) is [var png, ..])
+ parts[i] = (png, "png");
+ });
+
+ var joined = job.Files.Where((f, i) => parts[i] is not null && f.State != FileState.Failed).ToList();
+ var inputs = parts.OfType<(string Path, string Format)>().ToList();
+ if (joined.Count == 0 || job.CancellationToken.IsCancellationRequested)
+ {
+ Notify(job);
+ return;
+ }
+
+ var target = job.Preset.TargetFormat;
+ if (target == BuiltInData.SameAsSource)
+ target = FormatRegistry.Detect(joined[0].SourcePath) is { } first && joiner.CanWrite(first.Id) ? first.Id : "png";
+ else if (!joiner.CanWrite(target))
+ {
+ foreach (var f in joined)
+ FailFile(job, f, "error.no_route", $"{FormatRegistry.Detect(f.SourcePath)?.Id} → {target}");
+ return;
+ }
+
+ await WriteJoinedAsync(job, joined, inputs.Count, FormatRegistry.Get(target).PrimaryExtension,
+ (output, progress) => joiner.JoinAsync(inputs, output, target, job.Preset.Image, progress, job.CancellationToken));
+ }
+
+ /// <summary>
+ /// Writes the one file several sources become (merged videos, merged pictures), named after the first of
+ /// <paramref name="joined"/>. Their progress moves together; a write that fails or is cancelled is undone.
+ /// </summary>
+ /// <param name="write">Writes the file at the path it is given.</param>
+ private async Task WriteJoinedAsync(ConversionJob job, List<FileResult> joined, int inputCount, string extension,
+ Func<string, IProgress<double>, Task> write)
+ {
var first = joined[0];
var allocator = CreateFinalAllocator(job, first.SourcePath, 1, oneFile: true);
- var output = allocator.Allocate(target.PrimaryExtension);
+ var output = allocator.Allocate(extension);
if (output is null)
{
foreach (var f in joined)
@@ -459,8 +530,8 @@ public sealed class JobQueue : IAsyncDisposable
try
{
- await _mediaJoiner!.JoinAsync(inputs, output, target.Id, job.Preset, workDir, progress, job.CancellationToken);
- SizeLimit.Check(job.Preset, [output]); // joins aren't fitted: one over the limit is refused (#553)
+ await write(output, progress);
+ SizeLimit.Check(job.Preset, [output]); // joined media aren't fitted: one over the limit is refused (#553)
first.Outputs.Add(output);
foreach (var f in joined)
{
@@ -477,14 +548,14 @@ public sealed class JobQueue : IAsyncDisposable
catch (ConversionRefusedException ex)
{
allocator.Discard();
- _log.LogInformation("Joining {Count} file(s) into {Output} was refused: {Reason}", inputs.Count, output, ex.Message);
+ _log.LogInformation("Joining {Count} file(s) into {Output} was refused: {Reason}", inputCount, output, ex.Message);
foreach (var f in joined)
FailFile(job, f, ex.ErrorKey, ex.Detail);
}
catch (Exception ex)
{
allocator.Discard();
- _log.LogWarning(ex, "Joining {Count} file(s) into {Output} failed", inputs.Count, output);
+ _log.LogWarning(ex, "Joining {Count} file(s) into {Output} failed", inputCount, output);
foreach (var f in joined)
FailFile(job, f, "error.conversion_failed", ex.Message);
}
@@ -659,13 +730,15 @@ public sealed class JobQueue : IAsyncDisposable
/// Converts one source file along its planned route.
/// With <paramref name="finalOutput"/> false, results stay in the work directory as <paramref name="intermediate"/>
/// files (PDF for merging, TIFF pages for a multi-page TIFF). <paramref name="ceiling"/> is the file's progress once
- /// the route is done (a slideshow's pictures leave the rest to the video).
+ /// the route is done (a slideshow's pictures leave the rest to the video). <paramref name="options"/> is the preset
+ /// the route runs with, the job's unless given (the pictures of a merge become plain PNGs first).
/// </summary>
private async Task<IReadOnlyList<string>> RunFileAsync(
ConversionJob job, FileResult file, int index, RoutePlanner planner, string workDir, bool finalOutput,
- string intermediate = "pdf", double ceiling = 1)
+ string intermediate = "pdf", double ceiling = 1, Preset? options = null)
{
var ct = job.CancellationToken;
+ var runWith = options ?? job.Preset;
if (Stopped(file))
return [];
var source = FormatRegistry.Detect(file.SourcePath);
@@ -677,19 +750,19 @@ public sealed class JobQueue : IAsyncDisposable
return Fail(file, "error.empty_file", null);
var target = !finalOutput ? intermediate
- : job.Preset.TargetFormat == BuiltInData.SameAsSource ? source.Id
- : job.Preset.TargetFormat;
+ : runWith.TargetFormat == BuiltInData.SameAsSource ? source.Id
+ : runWith.TargetFormat;
// "Save every frame": a video becomes a folder of pictures in one step of its own; "Extract Live/Motion Photo
// video" likewise takes a photo's video, and "Live / Motion Photo" makes one of a video. Never for an
// intermediate file, and never on the way to another format (video → JPG is otherwise one still frame, photo →
// MP4 a video of the still picture).
- var frames = finalOutput && job.Preset.SavesFramesOf(source.Id);
- var motionPhoto = finalOutput && job.Preset.ExtractsMotionOf(source.Id);
- var livePhoto = finalOutput && job.Preset.MakesLivePhotoOf(source.Id);
+ var frames = finalOutput && runWith.SavesFramesOf(source.Id);
+ var motionPhoto = finalOutput && runWith.ExtractsMotionOf(source.Id);
+ var livePhoto = finalOutput && runWith.MakesLivePhotoOf(source.Id);
// "Recognize text": Tesseract writes a searchable PDF first, read on into DOCX, TXT, … from there. Also for the
// PDFs that are merged into one.
- var ocr = (finalOutput || target == "pdf") && job.Preset.RecognizesTextOf(source.Id);
+ var ocr = (finalOutput || target == "pdf") && runWith.RecognizesTextOf(source.Id);
var route = planner.Plan(source.Id, target, frames, motionPhoto: motionPhoto, livePhoto: livePhoto, ocr: ocr);
if (route is null)
return Fail(file, "error.no_route", $"{source.Id} → {target}");
@@ -721,10 +794,10 @@ public sealed class JobQueue : IAsyncDisposable
// Rotate / flip: only an engine that turns images does it. Without one the file would come out unturned
// (a PDF or a video re-encoded "as rotated"); with two in the route (EPS → PNG → JPG) it would turn twice.
- var turnAt = job.Preset.Image.TurnsOrMirrors ? route.FirstTransformStep() : -1;
- if (job.Preset.Image.TurnsOrMirrors && turnAt < 0)
+ var turnAt = runWith.Image.TurnsOrMirrors ? route.FirstTransformStep() : -1;
+ if (runWith.Image.TurnsOrMirrors && turnAt < 0)
return Fail(file, "error.cannot_turn", $"{source.Id} → {target}");
- var unturned = turnAt < 0 ? job.Preset : Unturned(job.Preset);
+ var unturned = turnAt < 0 ? runWith : Unturned(runWith);
file.State = FileState.Running;
Notify(job);
@@ -739,7 +812,7 @@ public sealed class JobQueue : IAsyncDisposable
{
IReadOnlyList<string> inputs = [file.SourcePath];
// "Save as ZIP": the last step writes into the work folder and the files are packed into one ZIP afterwards.
- var zipResult = finalOutput && job.Preset.Output.ZipResult;
+ var zipResult = finalOutput && runWith.Output.ZipResult;
for (var s = 0; s < route.Steps.Count; s++)
{
var step = route.Steps[s];
@@ -769,7 +842,7 @@ public sealed class JobQueue : IAsyncDisposable
{
// Turned once, in step turnAt: every other step gets the preset without rotation and flip,
// also one before it whose engine applies image options but doesn't say it turns.
- var preset = s == turnAt ? job.Preset : unturned;
+ var preset = s == turnAt ? runWith : unturned;
// Playback speed changes once, in the step that writes the output: an animation passed from one
// engine to another would otherwise change speed in both.
if (preset.Image.ChangesSpeed && !(isLast && finalOutput))
@@ -797,15 +870,15 @@ public sealed class JobQueue : IAsyncDisposable
}
// Under "Save as ZIP" the output is still in the work folder: the source copied over it goes into the ZIP.
- var copiedSource = finalOutput && job.Preset.Output.OnlyIfSmaller && inputs.Count == 1 && CopyIfNotSmaller(file.SourcePath, inputs[0]);
+ var copiedSource = finalOutput && runWith.Output.OnlyIfSmaller && inputs.Count == 1 && CopyIfNotSmaller(file.SourcePath, inputs[0]);
if (copiedSource)
file.NoticeKey = "notice.pdf_not_smaller";
// Watermark, page numbers, password: on every PDF this file became, from whichever engine.
- if (finalOutput && job.Preset.TargetFormat == "pdf")
- await FinishPdfsAsync(job.Preset, inputs, ct);
+ if (finalOutput && runWith.TargetFormat == "pdf")
+ await FinishPdfsAsync(runWith, inputs, ct);
// The size limit (#553): a result the engine couldn't fit (HEIC, a render, an animation) isn't handed over.
if (finalOutput)
- SizeLimit.Check(job.Preset, inputs);
+ SizeLimit.Check(runWith, inputs);
if (zipResult && inputs.Count > 0)
inputs = PackZip(job, file, index, inputs, ct);
@@ -814,7 +887,7 @@ public sealed class JobQueue : IAsyncDisposable
inputs = [NextToSource(job, file, index, inputs[0], final)];
// The source's dates are read now: "Replace the original" may send it to the Trash below.
- var dates = finalOutput && job.Preset.Output.KeepDates ? DatesOf(file.SourcePath) : null;
+ var dates = finalOutput && runWith.Output.KeepDates ? DatesOf(file.SourcePath) : null;
if (finalOutput && !zipResult && inputs.Count == 1)
inputs = [ReplaceOriginal(job, file, source.Id, inputs[0], copiedSource)];
diff --git a/src/Filee.Core/Presets/AskedLocation.cs b/src/Filee.Core/Presets/AskedLocation.cs
index f5af3b52..ff8c170b 100644
--- a/src/Filee.Core/Presets/AskedLocation.cs
+++ b/src/Filee.Core/Presets/AskedLocation.cs
@@ -8,14 +8,15 @@ public static class AskedLocation
{
/// <summary>
/// The batch makes one file, so the dialog asks for its name: one source, or several that become one (a merged
- /// PDF, a multi-page TIFF, one archive, joined videos). Otherwise it asks for a folder.
+ /// PDF, a multi-page TIFF, one archive, joined videos, merged pictures). Otherwise it asks for a folder.
/// </summary>
public static bool MakesOneResult(Preset preset, int sources) =>
sources == 1
|| preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle
|| preset.Image.MultiPageTiff && preset.TargetFormat == "tiff"
|| preset.PacksIntoOneArchive
- || preset.JoinsIntoOneMedia;
+ || preset.JoinsIntoOneMedia
+ || preset.JoinsImages;
/// <summary>
/// The name the save dialog suggests for <paramref name="source"/>: the preset's name pattern and renames, and the
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index ce888074..a0d0817d 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -115,6 +115,7 @@ public static class BuiltInData
.. LivePhotoPresets(),
.. ClipPresets(),
.. MediaToolPresets(),
+ .. MergeImagesPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -262,6 +263,20 @@ public static class BuiltInData
},
];
+ /// <summary>
+ /// "Merge images" (issue #645, added in settings schema 53): the dropped pictures, in the order set in the merge
+ /// order window, as one image, one under another or side by side, in the first picture's format. Quality 90 as the
+ /// JPG preset. On the back of the images donut next to "Merge PDF", where it took the slot of "GIF".
+ /// </summary>
+ public static List<Preset> MergeImagesPresets() =>
+ [
+ new()
+ {
+ Id = "merge-images", NameKey = "preset.merge_images", TargetFormat = SameAsSource,
+ Image = { JoinIntoOne = true, Quality = 90 }, Output = { FileNamePattern = "{name}_merged" },
+ },
+ ];
+
/// <summary>
/// "Compress PDF": pictures at 150 dpi, the rest compressed losslessly (added in settings schema 20). On no default
/// donut, the PDF donut is full: users add it in Settings → Toolbar.
@@ -528,9 +543,10 @@ public static class BuiltInData
Id = "images", NameKey = "profile.images",
Extensions = ExtensionsOf(FormatCategory.Image),
PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size"],
- // Full (ToolbarProfile.MaxSlices): "Extract Live Photo video" stays in the library, on no donut.
- BackPresetIds = ["tool-crop", "rotate", "flip", "remove-background", "trim-transparent", "grayscale", "to-avif", "to-gif", "merge-pdf",
- "compress-image", "remove-metadata", "zip-all"],
+ // Full (ToolbarProfile.MaxSlices): "Extract Live Photo video" stays in the library, on no donut, and "GIF"
+ // since "Merge images" took its slot (settings schema 53): a still picture as GIF is the least wanted here.
+ BackPresetIds = ["tool-crop", "rotate", "flip", "remove-background", "trim-transparent", "grayscale", "to-avif", "merge-images",
+ "merge-pdf", "compress-image", "remove-metadata", "zip-all"],
},
new()
{
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index a795927f..63d8fc89 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -184,6 +184,15 @@ public sealed class Preset
public bool JoinsIntoOneMedia =>
(Media.JoinIntoOne || Media.Slideshow) && MediaOptions.JoinTargets.Contains(TargetFormat);
+ /// <summary>
+ /// True for "Merge images": every dropped picture goes, in order, into one image (<see cref="ImageOptions.JoinIntoOne"/>)
+ /// of a picture format, or of the first picture's format for <see cref="BuiltInData.SameAsSource"/>.
+ /// </summary>
+ [JsonIgnore]
+ public bool JoinsImages =>
+ Image.JoinIntoOne
+ && (TargetFormat == BuiltInData.SameAsSource || Formats.FormatRegistry.FindById(TargetFormat)?.Category == Formats.FormatCategory.Image);
+
/// <summary>True for a <see cref="PresetKind.Tool"/>.</summary>
[JsonIgnore]
public bool IsTool => Kind == PresetKind.Tool;
@@ -288,6 +297,24 @@ public enum ImageFlip
Vertical,
}
+/// <summary>Which way merged pictures follow each other (<see cref="ImageOptions.JoinIntoOne"/>).</summary>
+public enum ImageJoinDirection
+{
+ /// <summary>One under another, the first at the top.</summary>
+ Vertical,
+ /// <summary>Side by side, the first on the left.</summary>
+ Horizontal,
+}
+
+/// <summary>How merged pictures of different sizes line up (<see cref="ImageOptions.JoinIntoOne"/>).</summary>
+public enum ImageJoinFit
+{
+ /// <summary>Scaled to the widest picture (one under another) or the tallest (side by side), so the edges line up.</summary>
+ SameSize,
+ /// <summary>Each at its own size, centred.</summary>
+ Original,
+}
+
/// <summary>TIFF compression schemes.</summary>
public enum TiffCompression
{
@@ -406,6 +433,40 @@ public sealed class ImageOptions
/// <summary>Use lossless WEBP encoding.</summary>
public bool WebpLossless { get; set; }
+ /// <summary>
+ /// "Merge images": every dropped picture goes, in order, into one image named after the first (<see cref="Preset.JoinsImages"/>),
+ /// one under another or side by side (<see cref="JoinDirection"/>). Each picture is turned as its EXIF and
+ /// <see cref="Rotation"/> say first; the other options (resize, grayscale, quality …) apply to the merged image.
+ /// </summary>
+ public bool JoinIntoOne { get; set; }
+
+ /// <summary>With <see cref="JoinIntoOne"/>: one under another or side by side. A direction from a newer Filee reads as vertical.</summary>
+ [JsonConverter(typeof(LenientEnumJsonConverter<ImageJoinDirection>))]
+ public ImageJoinDirection JoinDirection { get; set; }
+
+ /// <summary>With <see cref="JoinIntoOne"/>: pictures of different sizes scaled to line up, or kept as they are, centred.</summary>
+ [JsonConverter(typeof(LenientEnumJsonConverter<ImageJoinFit>))]
+ public ImageJoinFit JoinFit { get; set; }
+
+ /// <summary>Largest <see cref="JoinGap"/>.</summary>
+ public const int MaxJoinGap = 1000;
+
+ /// <summary>With <see cref="JoinIntoOne"/>: pixels of <see cref="JoinBackground"/> between two pictures (0 to <see cref="MaxJoinGap"/>).</summary>
+ public int JoinGap { get; set; }
+
+ /// <summary><see cref="JoinBackground"/> for a see-through background (in a format that holds one).</summary>
+ public const string TransparentJoin = "transparent";
+
+ /// <summary>
+ /// With <see cref="JoinIntoOne"/>: the colour of the gaps and of the room around smaller pictures, <c>#RRGGBB</c>, or
+ /// <see cref="TransparentJoin"/>. A format without transparency (JPG) gets <see cref="Background"/> there instead.
+ /// </summary>
+ public string JoinBackground { get; set; } = "#FFFFFF";
+
+ /// <summary><see cref="JoinGap"/> within its limits (a hand-edited preset file may hold anything).</summary>
+ [JsonIgnore]
+ public int JoinSpacing => Math.Clamp(JoinGap, 0, MaxJoinGap);
+
/// <summary>
/// FITS → TIFF: the data as it is (the default) or stretched. Either way the TIFF follows the file's BITPIX: 8 and
/// 16 bits stay so, 32-bit integer and floating-point data become 32-bit floating point.
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 731f3263..7e1f954f 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -123,7 +123,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 50;
+ public const int CurrentSchemaVersion = 53;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 6a2f68c2..f9f0a884 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -906,9 +906,49 @@ internal static class SettingsMigrations
// v50: Dahua DVR recordings (.dav) learn the video donut; custom claims stay put.
if (from < 50)
changed |= LearnExtensions(profiles, out _, ["dav"]);
+ // v53: "Merge images" (#645; 51 and 52 are kept for changes that came first, so this may be renumbered), after
+ // "Merge audio" as in a new library, and on the back of the images donut before "Merge PDF" when the user
+ // hasn't put it on either face: in a free slot, or in place of "GIF" (which stays in the library) on a
+ // full face. Present already but saved since by a Filee before 53: that one dropped the option and left a
+ // plain "same format" preset, so it is put back.
+ if (from < 53)
+ changed |= AddMergeImages(presets, profiles);
return changed;
}
+ private static bool AddMergeImages(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ var merge = BuiltInData.MergeImagesPresets().Single();
+ if (presets.FirstOrDefault(p => p.Id == merge.Id) is { } existing)
+ {
+ if (!existing.Image.JoinIntoOne && existing.TargetFormat == merge.TargetFormat)
+ {
+ existing.Image.JoinIntoOne = true;
+ changed = true;
+ }
+ }
+ else
+ {
+ var at = presets.FindLastIndex(p => p.Id is "remove-metadata" or "merge-audio" or "merge-videos");
+ presets.Insert(at < 0 ? presets.Count : at + 1, merge);
+ changed = true;
+ }
+ if (profiles.FirstOrDefault(p => p.Id == "images") is not { BackPresetIds: { } back } images
+ || back.Contains(merge.Id) || images.PresetIds.Contains(merge.Id))
+ return changed;
+ if (back.Count < ToolbarProfile.MaxSlices)
+ {
+ InsertBefore(back, merge.Id, back.Contains("merge-pdf") ? "merge-pdf" : "zip-all");
+ return true;
+ }
+ var gif = back.IndexOf("to-gif");
+ if (gif < 0)
+ return changed;
+ back[gif] = merge.Id;
+ return true;
+ }
+
private static bool AddCalendarPreset(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
diff --git a/src/Filee.Engines/Magick/ImageJoiner.cs b/src/Filee.Engines/Magick/ImageJoiner.cs
new file mode 100644
index 00000000..d9c8bb91
--- /dev/null
+++ b/src/Filee.Engines/Magick/ImageJoiner.cs
@@ -0,0 +1,175 @@
+// "Merge images" (issue #645): pictures one under another or side by side in one image, with a gap and a background
+// colour between them. The layout is worked out from the pictures' sizes first, so only one picture at a time (and the
+// merged image) is in memory.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+
+namespace Filee.Engines.Magick;
+
+internal static class ImageJoiner
+{
+ /// <summary>
+ /// The largest merged image Filee makes, the size of the longest "Long image" (PdfiumConverter.MaxStackedPixels):
+ /// about 800 MB of memory while it is put together.
+ /// </summary>
+ internal const long MaxPixels = Pdf.PdfiumConverter.MaxStackedPixels;
+
+ /// <summary>
+ /// Pictures read to measure them stay in memory up to this many pixels in all, for the merge: two or three photos are
+ /// read once, a long series a second time.
+ /// </summary>
+ private const long KeptPixels = 50_000_000;
+
+ /// <summary>Where one picture goes in the merged image, at which size.</summary>
+ internal readonly record struct Placement(int X, int Y, uint Width, uint Height);
+
+ /// <summary>The merged image's size and where each picture goes, in order.</summary>
+ internal sealed record Layout(uint Width, uint Height, IReadOnlyList<Placement> Pictures);
+
+ /// <summary>
+ /// Lays out pictures of <paramref name="sizes"/> (as they look, turned) as <paramref name="options"/> say. Refuses
+ /// with <c>error.merged_image_too_large</c> above <see cref="MaxPixels"/>.
+ /// </summary>
+ internal static Layout Plan(IReadOnlyList<(uint Width, uint Height)> sizes, ImageOptions options)
+ {
+ var sideBySide = options.JoinDirection == ImageJoinDirection.Horizontal;
+ var gap = options.JoinSpacing;
+ // "Across" is the side the pictures share (the width of a column, the height of a row), "along" the other.
+ var fitted = sizes.Select(s => (Across: (double)(sideBySide ? s.Height : s.Width), Along: (double)(sideBySide ? s.Width : s.Height)))
+ .ToList();
+ var across = fitted.Max(s => s.Across);
+ var placed = fitted.Select(s => options.JoinFit == ImageJoinFit.SameSize
+ ? (Across: across, Along: Math.Max(1, Math.Round(s.Along * across / s.Across)))
+ : s)
+ .ToList();
+ var along = placed.Sum(s => s.Along) + (double)gap * (placed.Count - 1);
+ if (across * along > MaxPixels)
+ {
+ var (w, h) = sideBySide ? (along, across) : (across, along);
+ throw new ConversionRefusedException("error.merged_image_too_large", $"{w:0} × {h:0} px");
+ }
+
+ var pictures = new List<Placement>();
+ double at = 0;
+ foreach (var (pictureAcross, pictureAlong) in placed)
+ {
+ // Centred across: only a smaller picture of "keep sizes" has room around it.
+ var offset = (int)Math.Floor((across - pictureAcross) / 2);
+ pictures.Add(sideBySide
+ ? new Placement((int)at, offset, (uint)pictureAlong, (uint)pictureAcross)
+ : new Placement(offset, (int)at, (uint)pictureAcross, (uint)pictureAlong));
+ at += pictureAlong + gap;
+ }
+ return sideBySide ? new Layout((uint)along, (uint)across, pictures) : new Layout((uint)across, (uint)along, pictures);
+ }
+
+ /// <summary>Writes the pictures of <paramref name="inputs"/> into one <paramref name="format"/> image at <paramref name="outputPath"/>.</summary>
+ internal static void Join(IReadOnlyList<(string Path, string Format)> inputs, string outputPath, string format, ImageOptions options,
+ IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ // The pictures are read with the preset's picture settings (a FITS stretch, a metafile's dpi).
+ var reading = new Preset { Image = options };
+ var kept = new IMagickImage<byte>?[inputs.Count];
+ try
+ {
+ var sizes = new (uint Width, uint Height)[inputs.Count];
+ long keptPixels = 0;
+ Density? density = null;
+ for (var i = 0; i < inputs.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var picture = Read(inputs[i], reading, options);
+ sizes[i] = (picture.Width, picture.Height);
+ density ??= picture.Density;
+ var pixels = (long)picture.Width * picture.Height;
+ if (keptPixels + pixels <= KeptPixels)
+ {
+ kept[i] = picture;
+ keptPixels += pixels;
+ }
+ else
+ picture.Dispose();
+ progress?.Report(0.4 * (i + 1) / inputs.Count);
+ }
+
+ var layout = Plan(sizes, options);
+ using var merged = new MagickImage(Background(options.JoinBackground), layout.Width, layout.Height);
+ for (var i = 0; i < inputs.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ using var picture = kept[i] ?? Read(inputs[i], reading, options);
+ kept[i] = null;
+ var place = layout.Pictures[i];
+ if (picture.Width != place.Width || picture.Height != place.Height)
+ picture.Resize(new MagickGeometry(place.Width, place.Height) { IgnoreAspectRatio = true });
+ merged.Composite(picture, place.X, place.Y, CompositeOperator.Over);
+ progress?.Report(0.4 + 0.4 * (i + 1) / inputs.Count);
+ }
+ if (density is { } first)
+ merged.Density = first;
+
+ // The pictures are turned already: the rest of the options (resize, grayscale, quality, a background for a
+ // format without transparency, what the format stores) apply to the merged image.
+ var rest = options.Clone();
+ rest.Rotation = ImageRotation.None;
+ rest.Flip = ImageFlip.None;
+ ImageEncoder.ApplyOptions(merged, rest, format);
+ cancellationToken.ThrowIfCancellationRequested();
+ ImageEncoder.WriteImage(merged, outputPath, format);
+ if (options.MaxSizeMb > 0)
+ ImageEncoder.FitToSize(merged, outputPath, ImageEncoder.OutputFormat(format, rest).Format, SizeLimit.Bytes(options.MaxSizeMb));
+ progress?.Report(1);
+ }
+ finally
+ {
+ foreach (var picture in kept)
+ picture?.Dispose();
+ }
+ }
+
+ /// <summary>
+ /// One picture as it looks: the first page or frame (an icon's largest size), turned by its EXIF orientation and the
+ /// preset, in sRGB so photos with different colour profiles match.
+ /// </summary>
+ private static IMagickImage<byte> Read((string Path, string Format) input, Preset reading, ImageOptions options)
+ {
+ using var images = ImageReader.Read(input.Path, input.Format, reading);
+ if (images.Count == 0)
+ throw new InvalidOperationException("The picture has no image in it.");
+ var picture = ImageEncoder.SelectFrames(images, input.Format, "png")[0].Clone();
+ try
+ {
+ picture.AutoOrient();
+ ImageEncoder.Turn(picture, options);
+ if (picture.GetColorProfile() is { } profile
+ && profile.Description?.Contains("sRGB", StringComparison.OrdinalIgnoreCase) != true)
+ picture.TransformColorSpace(ColorProfiles.SRGB);
+ else if (picture.ColorSpace == ColorSpace.CMYK)
+ picture.ColorSpace = ColorSpace.sRGB;
+ picture.ResetPage();
+ return picture;
+ }
+ catch
+ {
+ picture.Dispose();
+ throw;
+ }
+ }
+
+ /// <summary>The background colour: <c>#RRGGBB</c>, <see cref="ImageOptions.TransparentJoin"/>, white for anything else.</summary>
+ internal static MagickColor Background(string? colour)
+ {
+ if (string.Equals(colour, ImageOptions.TransparentJoin, StringComparison.OrdinalIgnoreCase))
+ return MagickColors.Transparent;
+ try
+ {
+ return new MagickColor(string.IsNullOrWhiteSpace(colour) ? "#FFFFFF" : colour.Trim());
+ }
+ catch (ArgumentException)
+ {
+ return MagickColors.White;
+ }
+ }
+}
diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.cs
index 2700afdb..dc079a78 100644
--- a/src/Filee.Engines/Magick/MagickImageConverter.cs
+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs
@@ -11,7 +11,7 @@ namespace Filee.Engines.Magick;
/// DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster and MIFF, and reads HEIC, XCF, camera RAW, DICOM,
/// Photo CD, OpenEXR, Radiance HDR, FITS and (on Windows) EMF/WMF.
/// </summary>
-public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransformer
+public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransformer, IImageJoiner
{
public string Id => "magick";
public string DisplayName => "ImageMagick";
@@ -66,6 +66,15 @@ public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransf
pages.Write(outputPath, MagickFormat.Tiff);
}, cancellationToken);
+ public bool CanRead(string format) => ImageEncoder.Sources.Contains(format);
+
+ public bool CanWrite(string format) => ImageEncoder.Writable.Contains(format);
+
+ /// <summary>"Merge images": the pictures one under another or side by side in one image (<see cref="ImageJoiner"/>).</summary>
+ public Task JoinAsync(IReadOnlyList<(string Path, string Format)> inputs, string outputPath, string format,
+ Filee.Core.Presets.ImageOptions options, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run(() => ImageJoiner.Join(inputs, outputPath, format, options, progress, cancellationToken), cancellationToken);
+
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
{
diff --git a/tests/Filee.App.Tests/MergeOrderTests.cs b/tests/Filee.App.Tests/MergeOrderTests.cs
index 751005cb..080193d8 100644
--- a/tests/Filee.App.Tests/MergeOrderTests.cs
+++ b/tests/Filee.App.Tests/MergeOrderTests.cs
@@ -1,4 +1,5 @@
-// Merge order (issue #268): the real chooser opened from the donut, then the pages of the merged PDF.
+// Merge order (issue #268): the real chooser opened from the donut, then the pages of the merged PDF; for "Merge images"
+// (#645) the layout below the list, the merged image and the choices remembered.
using Avalonia;
using Avalonia.Controls;
@@ -10,7 +11,9 @@ using Filee.App.Services;
using Filee.App.ViewModels;
using Filee.App.Views;
using Filee.Core.Conversion;
+using Filee.Core.Localization;
using Filee.Core.Settings;
+using ImageMagick;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
@@ -166,6 +169,238 @@ public class MergeOrderTests
finally { window.Close(); }
}
+ private static void ClickControl(Window window, string name)
+ {
+ var control = window.FindControl<Control>(name)!;
+ var at = control.TranslatePoint(new Point(control.Bounds.Width / 2, control.Bounds.Height / 2), window)!.Value;
+ window.MouseDown(at, MouseButton.Left);
+ window.MouseUp(at, MouseButton.Left);
+ RenderTests.Pump();
+ }
+
+ private static string Picture(string folder, string name, MagickColor colour, uint width, uint height)
+ {
+ using var image = new MagickImage(colour, width, height);
+ var path = Path.Combine(folder, name);
+ image.Write(path, MagickFormat.Png);
+ return path;
+ }
+
+ /// <summary>
+ /// "Merge images" (#645): the same chooser, with the layout below the list. The choices go into the merge and are
+ /// remembered for the next one; Cancel starts nothing and remembers nothing.
+ /// </summary>
+ [AvaloniaTheory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task Donut_merge_of_pictures_takes_the_layout_chosen_and_remembers_it(bool cancel)
+ {
+ TestServices.EnsureInitialized();
+ var folder = Directory.CreateTempSubdirectory("filee-merge-images-").FullName;
+ var store = AppHost.Get<UserDataStore>();
+ var profile = store.Profiles.Single(p => p.Id == "images");
+ var previous = profile.PresetIds;
+ var preset = store.FindPreset("merge-images")!;
+ var (previousOutput, previousImage) = (preset.Output, preset.Image.Clone());
+ var conversions = AppHost.Get<ConversionService>();
+ var before = conversions.Jobs.Select(j => j.Job.Id).ToHashSet();
+ var radial = AppHost.Get<RadialController>();
+ var windows = AppHost.Get<WindowService>();
+ try
+ {
+ var wide = Picture(folder, "1 front.png", MagickColors.Red, 100, 40);
+ var tall = Picture(folder, "2 back.png", MagickColors.Blue, 50, 80);
+ profile.PresetIds = ["merge-images"];
+ preset.Output = new()
+ {
+ Location = Filee.Core.Presets.OutputLocation.CustomFolder,
+ CustomFolder = folder,
+ FileNamePattern = previousOutput.FileNamePattern,
+ };
+ radial.ShowForFiles(450, 400, [tall, wide]);
+ var donut = radial.Window!.DonutControl;
+ Assert.True(donut.HandleKey(Key.Right));
+ Assert.True(donut.HandleKey(Key.Enter));
+ RenderTests.Pump();
+
+ var dialog = Assert.IsType<MergeOrderWindow>(windows.MergeOrder);
+ var vm = Assert.IsType<MergeOrderViewModel>(dialog.DataContext);
+ Assert.True(vm.MergesImages);
+ Assert.True(dialog.FindControl<Border>("MergeLayout")!.IsEffectivelyVisible);
+ Assert.Equal("Merge images", dialog.StartMerge.Content);
+ Assert.Equal([wide, tall], vm.OrderedFiles);
+ // As the preset says: one under another, the same width, no gap, white.
+ Assert.True(dialog.FindControl<RadioButton>("TopToBottom")!.IsChecked);
+ Assert.True(dialog.FindControl<CheckBox>("SameWidth")!.IsEffectivelyVisible);
+ Assert.False(dialog.FindControl<CheckBox>("SameHeight")!.IsEffectivelyVisible);
+
+ ClickControl(dialog, "SideBySide");
+ Assert.True(vm.SideBySide);
+ Assert.False(dialog.FindControl<RadioButton>("TopToBottom")!.IsChecked);
+ Assert.True(dialog.FindControl<CheckBox>("SameHeight")!.IsEffectivelyVisible);
+ ClickControl(dialog, "SameHeight"); // keep their sizes, centred
+ Assert.False(vm.SameSize);
+ dialog.FindControl<NumericUpDown>("GapBox")!.Value = 6;
+ RenderTests.Pump();
+ Assert.Equal(6, vm.Gap);
+ ClickControl(dialog, "Transparent");
+ Assert.True(vm.Transparent);
+ Assert.False(dialog.FindControl<ColorPicker>("BackgroundPicker")!.IsEffectivelyEnabled);
+ ClickControl(dialog, cancel ? "CancelMerge" : "StartMerge");
+
+ var saved = store.FindPreset("merge-images")!.Image;
+ if (cancel)
+ {
+ await Task.Delay(50, TestContext.Current.CancellationToken);
+ Dispatcher.UIThread.RunJobs();
+ Assert.DoesNotContain(conversions.Jobs, j => !before.Contains(j.Job.Id));
+ Assert.Equal(Filee.Core.Presets.ImageJoinDirection.Vertical, saved.JoinDirection);
+ Assert.Equal("#FFFFFF", saved.JoinBackground);
+ return;
+ }
+
+ JobViewModel? started = null;
+ for (var i = 0; i < 300; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ started = conversions.Jobs.FirstOrDefault(j => !before.Contains(j.Job.Id));
+ if (started?.Job.State is JobState.Completed or JobState.Failed) break;
+ await Task.Delay(20, TestContext.Current.CancellationToken);
+ }
+ Assert.NotNull(started);
+ Assert.Equal(JobState.Completed, started.Job.State);
+ var output = Assert.Single(started.Job.Outputs);
+ Assert.Equal("1 front_merged.png", Path.GetFileName(output));
+ using (var merged = new MagickImage(output))
+ {
+ // Side by side at their own sizes, 6 px apart; the low one centred on a see-through background.
+ Assert.Equal((156u, 80u), (merged.Width, merged.Height));
+ using var pixels = merged.GetPixels();
+ Assert.Equal(0, pixels.GetPixel(50, 5).ToColor()!.A);
+ Assert.Equal(MagickColors.Red, pixels.GetPixel(50, 40).ToColor());
+ Assert.Equal(MagickColors.Blue, pixels.GetPixel(130, 5).ToColor());
+ }
+
+ // Remembered in the library, also on disk, for the next merge.
+ Assert.Equal((Filee.Core.Presets.ImageJoinDirection.Horizontal, Filee.Core.Presets.ImageJoinFit.Original, 6, "transparent"),
+ (saved.JoinDirection, saved.JoinFit, saved.JoinGap, saved.JoinBackground));
+ var reloaded = new UserDataStore(store.Directory);
+ reloaded.Load();
+ Assert.Equal(Filee.Core.Presets.ImageJoinDirection.Horizontal, reloaded.FindPreset("merge-images")!.Image.JoinDirection);
+ Assert.True(new MergeOrderViewModel([wide, tall], saved).SideBySide);
+ }
+ finally
+ {
+ windows.MergeOrder?.Close();
+ radial.Close(animate: false);
+ profile.PresetIds = previous;
+ preset.Output = previousOutput;
+ preset.Image = previousImage;
+ store.SaveLibrary();
+ Directory.Delete(folder, true);
+ }
+ }
+
+ public static TheoryData<string, bool> MergeImagesLooks => new()
+ {
+ { "en", false }, { "en", true }, { "de", false }, { "de", true }, { "ar", false }, { "ar", true }, { "ko", false }, { "ko", true },
+ { "ru", false }, { "hi", true }, { "ne", false }, { "th", true },
+ };
+
+ /// <summary>
+ /// The layout of "Merge images" at the smallest size the window opens with for it: every choice whole and inside
+ /// the window in long languages, mirrored in Arabic, in light and dark.
+ /// </summary>
+ [AvaloniaTheory]
+ [MemberData(nameof(MergeImagesLooks))]
+ public void Merge_images_layout_fits_at_its_minimum_size(string language, bool dark)
+ {
+ TestServices.EnsureInitialized(language);
+ var theme = AppHost.Get<ThemeService>();
+ theme.Apply(new ThemeSettings { Mode = dark ? ThemeMode.Dark : ThemeMode.Light }, language);
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "merge-images");
+ var vm = new MergeOrderViewModel([
+ @"C:\Users\me\Pictures\Passport front.jpg",
+ @"C:\Users\me\Pictures\Passport back.jpg",
+ @"C:\Users\me\Downloads\Driving licence, both sides, scanned at 600 dpi.png"], preset.Image);
+ var window = new MergeOrderWindow { DataContext = vm, Width = 440, Height = 540 };
+ window.StartMerge.Content = AppHost.Get<ILocalizer>().DisplayName(preset);
+ try
+ {
+ window.Show();
+ RenderTests.Pump();
+ Rect Box(string name)
+ {
+ var control = window.FindControl<Control>(name)!;
+ return new Rect(control.Bounds.Size).TransformToAABB(control.TransformToVisual(window)!.Value);
+ }
+ var layout = Box("MergeLayout");
+ string[] choices = ["TopToBottom", "SideBySide", "SameWidth", "GapBox", "BackgroundPicker", "BackgroundHex", "Transparent"];
+ var boxes = choices.ToDictionary(name => name, Box);
+ foreach (var (name, box) in boxes)
+ {
+ Assert.True(box.Width > 0 && box.Left >= layout.Left - 0.5 && box.Right <= layout.Right + 0.5 && box.Bottom <= layout.Bottom + 0.5,
+ $"{name} {box} outside {layout}");
+ foreach (var (other, otherBox) in boxes.Where(b => b.Key != name))
+ Assert.False(box.Deflate(1).Intersects(otherBox.Deflate(1)), $"{name} {box} overlaps {other} {otherBox}");
+ }
+ // The checkbox text is shown whole (not cut at the window's edge).
+ var sameWidth = window.FindControl<CheckBox>("SameWidth")!;
+ Assert.True(sameWidth.Bounds.Width >= sameWidth.DesiredSize.Width - 0.5);
+ // Arabic mirrors the switch: "top to bottom" comes first, on the right.
+ if (language == "ar")
+ Assert.True(boxes["TopToBottom"].Left > boxes["SideBySide"].Left);
+ else
+ Assert.True(boxes["TopToBottom"].Right <= boxes["SideBySide"].Left + 0.5);
+ Assert.True(window.FindControl<ListBox>("FileOrder")!.Bounds.Height > 60);
+ Assert.True(Box("StartMerge").Right <= window.Bounds.Width && Box("StartMerge").Left >= 0);
+ RenderTests.Save(window, $"merge-images-{language}-{(dark ? "dark" : "light")}.png");
+
+ // The other choices: side by side, see-through.
+ vm.SideBySide = true;
+ vm.Transparent = true;
+ RenderTests.Pump();
+ Assert.True(window.FindControl<CheckBox>("SameHeight")!.IsEffectivelyVisible);
+ RenderTests.Save(window, $"merge-images-{language}-{(dark ? "dark" : "light")}-side-by-side.png");
+ }
+ finally
+ {
+ window.Close();
+ theme.Apply(new ThemeSettings(), language);
+ }
+ }
+
+ [Fact]
+ public void The_layout_chosen_is_written_into_the_merge_and_other_merges_show_none()
+ {
+ var image = new Filee.Core.Presets.ImageOptions { JoinGap = 30, JoinBackground = "#102030" };
+ var vm = new MergeOrderViewModel(["a.png", "b.png"], image);
+ Assert.True(vm.MergesImages);
+ Assert.Equal((false, true, 30, Avalonia.Media.Color.Parse("#102030")), (vm.SideBySide, vm.SameSize, vm.Gap, vm.BackgroundColor));
+
+ vm.TopToBottom = false;
+ vm.SameSize = false;
+ vm.Gap = 5000;
+ vm.BackgroundColor = Avalonia.Media.Colors.Black;
+ vm.ApplyTo(image);
+ Assert.Equal((Filee.Core.Presets.ImageJoinDirection.Horizontal, Filee.Core.Presets.ImageJoinFit.Original, Filee.Core.Presets.ImageOptions.MaxJoinGap, "#000000"),
+ (image.JoinDirection, image.JoinFit, image.JoinGap, image.JoinBackground));
+ vm.BackgroundHex = "#336699";
+ Assert.Equal(Avalonia.Media.Color.Parse("#336699"), vm.BackgroundColor);
+ vm.ApplyTo(image);
+ Assert.Equal("#336699", image.JoinBackground);
+ vm.BackgroundColor = Avalonia.Media.Colors.Red;
+ Assert.Equal("#FF0000", vm.BackgroundHex);
+ vm.Transparent = true;
+ Assert.False(vm.PicksColor);
+ vm.ApplyTo(image);
+ Assert.Equal("transparent", image.JoinBackground);
+
+ Assert.False(new MergeOrderViewModel(["a.pdf", "b.pdf"]).MergesImages);
+ // A colour that isn't one (a hand-edited file) shows white.
+ Assert.Equal(Avalonia.Media.Colors.White, new MergeOrderViewModel(["a.png"], new() { JoinBackground = "blue-ish" }).BackgroundColor);
+ }
+
[Fact]
public void Files_start_in_name_order_counting_numbers_and_browser_files_show_no_folder()
{
diff --git a/tests/Filee.Core.Tests/MergeImagesTests.cs b/tests/Filee.Core.Tests/MergeImagesTests.cs
new file mode 100644
index 00000000..265d8c11
--- /dev/null
+++ b/tests/Filee.Core.Tests/MergeImagesTests.cs
@@ -0,0 +1,277 @@
+// "Merge images" (#645): the preset, its place on the images donut, how existing libraries get it (settings schema 53),
+// presets files older and newer Filee versions read, and the queue merging pictures into one image.
+
+using System.Text.Json;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class MergeImagesTests
+{
+ private static Preset BuiltIn(string id) => BuiltInData.CreatePresets().Single(p => p.Id == id);
+
+ /// <summary>The images donut's back face of settings schema 37 to 52.</summary>
+ private static readonly string[] BackBefore53 =
+ ["tool-crop", "rotate", "flip", "remove-background", "trim-transparent", "grayscale", "to-avif", "to-gif", "merge-pdf",
+ "compress-image", "remove-metadata", "zip-all"];
+
+ [Fact]
+ public void A_new_library_merges_pictures_in_their_first_format_next_to_merge_pdf()
+ {
+ var merge = BuiltIn("merge-images");
+ Assert.Equal("preset.merge_images", merge.NameKey);
+ Assert.True(merge.JoinsImages);
+ Assert.False(merge.JoinsIntoOneMedia);
+ Assert.Equal(BuiltInData.SameAsSource, merge.TargetFormat);
+ Assert.Equal("{name}_merged", merge.Output.FileNamePattern); // as "Merge videos": named after the first file
+ Assert.Equal((ImageJoinDirection.Vertical, ImageJoinFit.SameSize, 0, "#FFFFFF"),
+ (merge.Image.JoinDirection, merge.Image.JoinFit, merge.Image.JoinGap, merge.Image.JoinBackground));
+
+ var back = BuiltInData.CreateProfiles().Single(p => p.Id == "images").BackPresetIds!;
+ Assert.Equal(ToolbarProfile.MaxSlices, back.Count);
+ Assert.Equal(["to-avif", "merge-images", "merge-pdf"], back[6..9]);
+ // GIF gave its slot: still a preset of the library, and on the video donut's front.
+ Assert.DoesNotContain("to-gif", back);
+ Assert.Single(BuiltInData.CreatePresets(), p => p.Id == "to-gif");
+ Assert.Equal(["merge-images"], BuiltInData.CreatePresets().Where(p => p.JoinsImages).Select(p => p.Id));
+ }
+
+ [Theory]
+ [InlineData("*", true)]
+ [InlineData("png", true)]
+ [InlineData("jpg", true)]
+ [InlineData("pdf", false)]
+ [InlineData("mp4", false)]
+ public void Only_a_picture_target_merges_pictures(string target, bool merges)
+ {
+ Assert.Equal(merges, new Preset { TargetFormat = target, Image = { JoinIntoOne = true } }.JoinsImages);
+ Assert.False(new Preset { TargetFormat = target }.JoinsImages);
+ }
+
+ [Fact]
+ public void A_merge_of_pictures_is_saved_as_one_file()
+ {
+ Assert.True(AskedLocation.MakesOneResult(BuiltIn("merge-images"), 3));
+ Assert.False(AskedLocation.MakesOneResult(BuiltIn("to-png"), 3));
+ }
+
+ [Fact]
+ public void The_gap_stays_within_its_limits()
+ {
+ Assert.Equal(0, new ImageOptions { JoinGap = -5 }.JoinSpacing);
+ Assert.Equal(12, new ImageOptions { JoinGap = 12 }.JoinSpacing);
+ Assert.Equal(ImageOptions.MaxJoinGap, new ImageOptions { JoinGap = 1_000_000 }.JoinSpacing);
+ }
+
+ [Fact]
+ public void Schema_53_puts_merge_images_in_place_of_gif_on_a_full_images_back_face()
+ {
+ var presets = BuiltInData.CreatePresets().Where(p => p.Id != "merge-images").ToList();
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.BackPresetIds = [.. BackBefore53];
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
+
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "images").BackPresetIds, images.BackPresetIds);
+ // In the library after the media tools, as in a new one.
+ Assert.Equal(presets.FindIndex(p => p.Id == "remove-metadata") + 1, presets.FindIndex(p => p.Id == "merge-images"));
+ Assert.Single(presets, p => p.Id == "to-gif");
+ Assert.False(SettingsMigrations.ApplyToLibrary(AppSettings.CurrentSchemaVersion, presets, profiles));
+ }
+
+ [Fact]
+ public void Schema_53_takes_a_free_slot_before_merge_pdf_and_leaves_gif()
+ {
+ var presets = BuiltInData.CreatePresets().Where(p => p.Id != "merge-images").ToList();
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.BackPresetIds = ["tool-crop", "to-gif", "merge-pdf", "zip-all"];
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
+
+ Assert.Equal(["tool-crop", "to-gif", "merge-images", "merge-pdf", "zip-all"], images.BackPresetIds);
+ }
+
+ [Fact]
+ public void Schema_53_leaves_a_donut_where_the_user_put_merge_images_or_has_no_gif_to_give()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.PresetIds = ["merge-images", "to-png"];
+ images.BackPresetIds = [.. BackBefore53];
+
+ Assert.False(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
+ Assert.Equal(BackBefore53, images.BackPresetIds);
+
+ // A full face the user laid out without GIF: nothing of theirs goes.
+ images.PresetIds = ["to-png"];
+ images.BackPresetIds = [.. BackBefore53.Select(id => id == "to-gif" ? "to-bmp" : id)];
+ Assert.False(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
+ Assert.DoesNotContain("merge-images", images.BackPresetIds);
+ }
+
+ [Fact]
+ public void Schema_53_puts_the_option_back_when_an_older_filee_dropped_it()
+ {
+ // A Filee before 53 saved the library again: the preset is left with what it knows, its name kept.
+ var presets = BuiltInData.CreatePresets();
+ var stripped = presets.Single(p => p.Id == "merge-images");
+ stripped.Image.JoinIntoOne = false;
+ stripped.Name = "Stack my scans";
+ var profiles = BuiltInData.CreateProfiles();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
+
+ Assert.True(stripped.JoinsImages);
+ Assert.Equal("Stack my scans", stripped.Name);
+ Assert.Single(presets, p => p.Id == "merge-images");
+ }
+
+ [Fact]
+ public void A_presets_file_keeps_the_layout_and_reads_a_newer_filee_s_values_as_the_defaults()
+ {
+ var merge = BuiltIn("merge-images");
+ merge.Image.JoinDirection = ImageJoinDirection.Horizontal;
+ merge.Image.JoinFit = ImageJoinFit.Original;
+ merge.Image.JoinGap = 24;
+ merge.Image.JoinBackground = ImageOptions.TransparentJoin;
+ var json = JsonSerializer.Serialize([merge], FileeJsonContext.Default.ListPreset);
+ Assert.Contains("\"joinDirection\": \"Horizontal\"", json); // by name, as the other enums
+ var read = Assert.Single(JsonSerializer.Deserialize(json, FileeJsonContext.Default.ListPreset)!);
+ Assert.Equal((ImageJoinDirection.Horizontal, ImageJoinFit.Original, 24, "transparent"),
+ (read.Image.JoinDirection, read.Image.JoinFit, read.Image.JoinGap, read.Image.JoinBackground));
+
+ // A direction or fit this version doesn't know (a newer Filee's) doesn't lose the presets file.
+ var newer = json.Replace("\"Horizontal\"", "\"Diagonal\"").Replace("\"Original\"", "7");
+ var fallback = Assert.Single(JsonSerializer.Deserialize(newer, FileeJsonContext.Default.ListPreset)!);
+ Assert.Equal((ImageJoinDirection.Vertical, ImageJoinFit.SameSize), (fallback.Image.JoinDirection, fallback.Image.JoinFit));
+ }
+
+ private static async Task<ConversionJob> Run(JobQueue queue, IReadOnlyList<string> sources, Preset preset)
+ {
+ var job = new ConversionJob(sources, preset, "Merge images");
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ [Fact]
+ public async Task Pictures_merge_in_order_into_one_file_in_the_first_one_s_format()
+ {
+ using var dir = new TempDir();
+ var second = dir.File("b.png");
+ var first = dir.File("a.jpg");
+ var joiner = new FakeImageJoiner();
+ await using var queue = new JobQueue(new ConverterCatalog([joiner]));
+
+ var job = await Run(queue, [first, second], BuiltIn("merge-images"));
+
+ Assert.Equal(JobState.Completed, job.State);
+ var output = Assert.Single(job.Outputs);
+ Assert.Equal("a_merged.jpg", Path.GetFileName(output));
+ Assert.Equal([(first, "jpg"), (second, "png")], joiner.Inputs);
+ Assert.Equal("jpg", joiner.Format);
+ Assert.All(job.Files, f => Assert.Equal(FileState.Done, f.State));
+ Assert.Equal("a.jpg|b.png", await File.ReadAllTextAsync(output, TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public async Task A_picture_the_joiner_cannot_read_becomes_a_plain_png_and_a_first_format_it_cannot_write_gives_png()
+ {
+ using var dir = new TempDir();
+ var icon = dir.File("a.icns");
+ var photo = dir.File("b.jpg");
+ var document = dir.File("c.docx");
+ var joiner = new FakeImageJoiner { Unreadable = ["icns"], Unwritable = ["icns"] };
+ var engine = new FakeConverter("icns", new ConversionEdge("icns", "png"));
+ await using var queue = new JobQueue(new ConverterCatalog([engine, joiner]));
+ var preset = BuiltIn("merge-images").Clone();
+ preset.Image.Resize = ResizeMode.Percent; // the merged image's: not applied to the picture on its way
+ preset.Image.Rotation = ImageRotation.Right90;
+
+ var job = await Run(queue, [icon, photo, document], preset);
+
+ Assert.Equal(JobState.CompletedWithErrors, job.State);
+ Assert.Equal("error.images_only", job.Files[2].ErrorKey);
+ Assert.Equal("a_merged.png", Path.GetFileName(Assert.Single(job.Outputs)));
+ Assert.Equal("png", joiner.Format);
+ Assert.Equal(2, joiner.Inputs.Count);
+ Assert.Equal("png", joiner.Inputs[0].Format);
+ Assert.StartsWith(Path.Combine(Path.GetTempPath(), "Filee"), joiner.Inputs[0].Path); // in the job's work folder
+ Assert.Equal((photo, "jpg"), joiner.Inputs[1]);
+ var step = Assert.Single(engine.Presets);
+ Assert.Equal((ResizeMode.None, ImageRotation.None, false), (step.Image.Resize, step.Image.Rotation, step.Image.JoinIntoOne));
+ Assert.Equal(ImageRotation.Right90, joiner.Options!.Rotation); // turned once, as the pictures merge
+ }
+
+ [Fact]
+ public async Task A_target_the_joiner_cannot_write_fails_every_picture()
+ {
+ using var dir = new TempDir();
+ var joiner = new FakeImageJoiner { Unwritable = ["heic"] };
+ await using var queue = new JobQueue(new ConverterCatalog([joiner]));
+ var preset = BuiltIn("merge-images").Clone();
+ preset.TargetFormat = "heic";
+
+ var job = await Run(queue, [dir.File("a.png"), dir.File("b.png")], preset);
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.All(job.Files, f => Assert.Equal("error.no_route", f.ErrorKey));
+ Assert.Empty(joiner.Inputs);
+ }
+
+ [Fact]
+ public async Task A_merge_refused_as_too_large_says_why_and_leaves_no_file()
+ {
+ using var dir = new TempDir();
+ var joiner = new FakeImageJoiner { Refusal = new ConversionRefusedException("error.merged_image_too_large", "30000 × 9000 px") };
+ await using var queue = new JobQueue(new ConverterCatalog([joiner]));
+
+ var job = await Run(queue, [dir.File("a.png"), dir.File("b.png")], BuiltIn("merge-images"));
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.All(job.Files, f => Assert.Equal(("error.merged_image_too_large", "30000 × 9000 px"), (f.ErrorKey, f.ErrorDetail)));
+ Assert.Empty(job.Outputs);
+ Assert.False(File.Exists(Path.Combine(dir.Path, "a_merged.png")));
+ }
+}
+
+/// <summary>Test double for the image engine's merging: records what it was given and writes the pictures' names.</summary>
+internal sealed class FakeImageJoiner : IConverter, IImageJoiner
+{
+ public string Id => "fake-joiner";
+ public string DisplayName => Id;
+ public IReadOnlyList<ConversionEdge> Edges => [];
+ public int MaxParallelism => 0;
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ throw new NotSupportedException();
+
+ public HashSet<string> Unreadable { get; init; } = [];
+ public HashSet<string> Unwritable { get; init; } = [];
+ public Exception? Refusal { get; init; }
+ public List<(string Path, string Format)> Inputs { get; } = [];
+ public string? Format { get; private set; }
+ public ImageOptions? Options { get; private set; }
+
+ public bool CanRead(string format) => !Unreadable.Contains(format);
+ public bool CanWrite(string format) => !Unwritable.Contains(format);
+
+ public async Task JoinAsync(IReadOnlyList<(string Path, string Format)> inputs, string outputPath, string format, ImageOptions options,
+ IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ // Something written first, as a real merge would: a refused one must not leave it behind.
+ await File.WriteAllTextAsync(outputPath, "", cancellationToken);
+ if (Refusal is not null)
+ throw Refusal;
+ Inputs.AddRange(inputs);
+ Format = format;
+ Options = options;
+ await File.WriteAllTextAsync(outputPath, string.Join("|", inputs.Select(i => Path.GetFileName(i.Path))), cancellationToken);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/MergeImagesEngineTests.cs b/tests/Filee.Engines.Tests/MergeImagesEngineTests.cs
new file mode 100644
index 00000000..9f751e7d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MergeImagesEngineTests.cs
@@ -0,0 +1,229 @@
+// "Merge images" (#645) with ImageMagick: generated pictures merged one under another and side by side, with a gap,
+// pictures of different sizes, a background colour or transparency, and the limit on the merged image's size.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Magick;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+public class MergeImagesEngineTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static Preset Merge(Action<ImageOptions>? set = null)
+ {
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "merge-images").Clone();
+ set?.Invoke(preset.Image);
+ return preset;
+ }
+
+ private static string Picture(string folder, string name, MagickColor colour, uint width, uint height, MagickFormat format = MagickFormat.Png)
+ {
+ using var image = new MagickImage(colour, width, height);
+ var path = Path.Combine(folder, name);
+ image.Write(path, format);
+ return path;
+ }
+
+ private static string Output(ConversionJob job)
+ {
+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));
+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");
+ return Assert.Single(job.Outputs);
+ }
+
+ private static IMagickColor<byte> Colour(IMagickImage<byte> image, int x, int y)
+ {
+ using var pixels = image.GetPixels();
+ return pixels.GetPixel(x, y).ToColor()!;
+ }
+
+ /// <summary>The colour at (x, y) as #RRGGBBAA.</summary>
+ private static string At(IMagickImage<byte> image, int x, int y)
+ {
+ var colour = Colour(image, x, y);
+ return $"#{colour.R:X2}{colour.G:X2}{colour.B:X2}{(image.HasAlpha ? colour.A : 255):X2}";
+ }
+
+ [Fact]
+ public async Task Pictures_of_different_widths_stack_at_the_same_width_with_a_white_gap()
+ {
+ var dir = fx.NewFolder();
+ var wide = Picture(dir, "1 front.png", MagickColors.Red, 200, 100);
+ var narrow = Picture(dir, "2 back.png", MagickColors.Blue, 100, 100);
+
+ var output = Output(await fx.ConvertAsync([wide, narrow], Merge(i => i.JoinGap = 10)));
+
+ Assert.Equal("1 front_merged.png", Path.GetFileName(output));
+ using var merged = new MagickImage(output);
+ // The narrow one is scaled up to the width of the wide one: 100 + 10 + 200.
+ Assert.Equal((200u, 310u), (merged.Width, merged.Height));
+ Assert.Equal("#FF0000FF", At(merged, 100, 50));
+ Assert.Equal("#FFFFFFFF", At(merged, 100, 105));
+ Assert.Equal("#0000FFFF", At(merged, 100, 210));
+ Assert.Equal("#0000FFFF", At(merged, 199, 309));
+ }
+
+ [Fact]
+ public async Task Side_by_side_pictures_keep_their_sizes_centred_on_a_transparent_background()
+ {
+ var dir = fx.NewFolder();
+ var low = Picture(dir, "a.png", MagickColors.Red, 100, 50);
+ var tall = Picture(dir, "b.png", MagickColors.Lime, 60, 100);
+
+ var output = Output(await fx.ConvertAsync([low, tall], Merge(i =>
+ {
+ i.JoinDirection = ImageJoinDirection.Horizontal;
+ i.JoinFit = ImageJoinFit.Original;
+ i.JoinGap = 8;
+ i.JoinBackground = ImageOptions.TransparentJoin;
+ })));
+
+ using var merged = new MagickImage(output);
+ Assert.Equal((168u, 100u), (merged.Width, merged.Height));
+ Assert.EndsWith("00", At(merged, 50, 10)); // above the low picture: see-through
+ Assert.Equal("#FF0000FF", At(merged, 50, 50)); // centred: rows 25 to 74
+ Assert.EndsWith("00", At(merged, 50, 80));
+ Assert.EndsWith("00", At(merged, 104, 50)); // the gap
+ Assert.Equal("#00FF00FF", At(merged, 140, 5));
+ }
+
+ [Fact]
+ public async Task Side_by_side_pictures_of_the_same_height_into_a_jpg_get_a_coloured_gap()
+ {
+ var dir = fx.NewFolder();
+ var photo = Picture(dir, "card front.jpg", MagickColors.White, 300, 200, MagickFormat.Jpeg);
+ var gray = Path.Combine(dir, "card back.png");
+ using (var image = new MagickImage(new MagickColor("#808080"), 150, 50))
+ {
+ image.ColorType = ColorType.Grayscale; // a greyscale picture joins a colour one
+ image.Write(gray, MagickFormat.Png);
+ }
+
+ var output = Output(await fx.ConvertAsync([photo, gray], Merge(i =>
+ {
+ i.JoinDirection = ImageJoinDirection.Horizontal;
+ i.JoinGap = 20;
+ i.JoinBackground = "#000080";
+ })));
+
+ Assert.Equal("card front_merged.jpg", Path.GetFileName(output)); // the first picture's format
+ using var merged = new MagickImage(output);
+ Assert.Equal(MagickFormat.Jpeg, merged.Format);
+ // The greyscale one scaled to the height of the photo: 150 × 50 → 600 × 200.
+ Assert.Equal((300u + 20 + 600, 200u), (merged.Width, merged.Height));
+ var gap = Colour(merged, 310, 100);
+ Assert.InRange(gap.B, 100, 150); // navy, give or take JPEG
+ Assert.InRange(gap.R, 0, 30);
+ var back = Colour(merged, 600, 100);
+ Assert.InRange(back.R, 115, 140);
+ Assert.InRange(back.B, 115, 140);
+ }
+
+ [Fact]
+ public async Task Each_picture_turns_before_the_merge_and_a_transparent_gap_turns_white_in_a_jpg()
+ {
+ var dir = fx.NewFolder();
+ var first = Picture(dir, "a.jpg", MagickColors.Red, 200, 100, MagickFormat.Jpeg);
+ var second = Picture(dir, "b.jpg", MagickColors.Blue, 200, 100, MagickFormat.Jpeg);
+
+ var output = Output(await fx.ConvertAsync([first, second], Merge(i =>
+ {
+ i.Rotation = ImageRotation.Right90;
+ i.JoinDirection = ImageJoinDirection.Horizontal;
+ i.JoinGap = 10;
+ i.JoinBackground = ImageOptions.TransparentJoin;
+ })));
+
+ using var merged = new MagickImage(output);
+ // Two 100 × 200 pictures, not one 200 × 210 picture turned on its side.
+ Assert.Equal((210u, 200u), (merged.Width, merged.Height));
+ var gap = Colour(merged, 105, 100);
+ Assert.True(gap.R > 240 && gap.G > 240 && gap.B > 240, $"{gap}");
+ }
+
+ [Fact]
+ public async Task A_drawing_becomes_a_picture_first_and_merges_with_a_photo()
+ {
+ var dir = fx.NewFolder();
+ var svg = Path.Combine(dir, "logo.svg");
+ await File.WriteAllTextAsync(svg,
+ """<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50"><rect width="100" height="50" fill="#00FF00"/></svg>""",
+ TestContext.Current.CancellationToken);
+ var photo = Picture(dir, "photo.png", MagickColors.Red, 100, 100);
+
+ var output = Output(await fx.ConvertAsync([svg, photo], Merge()));
+
+ // Named after the drawing, written as PNG: a merged picture can't be an SVG.
+ Assert.Equal("logo_merged.png", Path.GetFileName(output));
+ using var merged = new MagickImage(output);
+ // The drawing is rendered at the vector engine's size, the photo scaled to its width.
+ var width = (int)merged.Width;
+ Assert.Equal(width / 2 + width, (int)merged.Height);
+ Assert.Equal("#00FF00FF", At(merged, width / 2, width / 4));
+ Assert.Equal("#FF0000FF", At(merged, width / 2, width));
+ }
+
+ [Fact]
+ public async Task The_preset_s_resize_applies_to_the_merged_image()
+ {
+ var dir = fx.NewFolder();
+ var a = Picture(dir, "a.png", MagickColors.Red, 200, 100);
+ var b = Picture(dir, "b.png", MagickColors.Blue, 200, 100);
+
+ var output = Output(await fx.ConvertAsync([a, b], Merge(i =>
+ {
+ i.Resize = ResizeMode.Percent;
+ i.ResizePercent = 50;
+ })));
+
+ using var merged = new MagickImage(output);
+ Assert.Equal((100u, 100u), (merged.Width, merged.Height));
+ }
+
+ [Fact]
+ public void A_merged_image_beyond_the_limit_is_refused_with_its_size()
+ {
+ // 12 photos of 24 MP side by side: 288 MP.
+ var sizes = Enumerable.Repeat((6000u, 4000u), 12).ToList();
+ var refused = Assert.Throws<ConversionRefusedException>(() =>
+ ImageJoiner.Plan(sizes, new ImageOptions { JoinDirection = ImageJoinDirection.Horizontal }));
+ Assert.Equal("error.merged_image_too_large", refused.ErrorKey);
+ Assert.Equal("72000 × 4000 px", refused.Detail);
+
+ // Eight of them fit.
+ var layout = ImageJoiner.Plan(sizes.Take(8).ToList(), new ImageOptions { JoinDirection = ImageJoinDirection.Horizontal });
+ Assert.Equal((48000u, 4000u), (layout.Width, layout.Height));
+ Assert.True((long)layout.Width * layout.Height <= ImageJoiner.MaxPixels);
+ }
+
+ [Fact]
+ public void The_layout_scales_to_the_widest_or_centres_the_original_sizes()
+ {
+ (uint, uint)[] sizes = [(400, 300), (200, 200), (100, 50)];
+
+ var same = ImageJoiner.Plan(sizes, new ImageOptions { JoinGap = 5 });
+ Assert.Equal((400u, 300u + 5 + 400 + 5 + 200), (same.Width, same.Height));
+ Assert.Equal([new(0, 0, 400, 300), new(0, 305, 400, 400), new(0, 710, 400, 200)], same.Pictures);
+
+ var kept = ImageJoiner.Plan(sizes, new ImageOptions { JoinFit = ImageJoinFit.Original });
+ Assert.Equal((400u, 550u), (kept.Width, kept.Height));
+ Assert.Equal([new(0, 0, 400, 300), new(100, 300, 200, 200), new(150, 500, 100, 50)], kept.Pictures);
+
+ var row = ImageJoiner.Plan(sizes, new ImageOptions { JoinDirection = ImageJoinDirection.Horizontal, JoinFit = ImageJoinFit.Original, JoinGap = 2 });
+ Assert.Equal((704u, 300u), (row.Width, row.Height));
+ Assert.Equal([new(0, 0, 400, 300), new(402, 50, 200, 200), new(604, 125, 100, 50)], row.Pictures);
+ }
+
+ [Theory]
+ [InlineData("#00FF00", "#00FF00FF")]
+ [InlineData("transparent", "#00000000")]
+ [InlineData("TRANSPARENT", "#00000000")]
+ [InlineData("not a colour", "#FFFFFFFF")]
+ [InlineData("", "#FFFFFFFF")]
+ public void The_background_reads_a_colour_or_transparency_and_falls_back_to_white(string setting, string expected)
+ {
+ var colour = ImageJoiner.Background(setting);
+ Assert.Equal(expected, $"#{colour.R:X2}{colour.G:X2}{colour.B:X2}{colour.A:X2}");
+ }
+}