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.

Read FITS astrophotos: stretched pictures, TIFF at the file's own depth (#460)

KnifeLemon2da70f97b569
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 0d7a6c39..d59705f4 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "WEBP دون فقدان",
"presets.multipage_tiff": "جمع كل الملفات في TIFF واحد متعدد الصفحات",
"presets.multipage_tiff_hint": "تصبح كل صورة وكل صفحة PDF أو TIFF صفحةً بالترتيب.\nيكفي ملف PDF واحد لإنشاء TIFF متعدد الصفحات.",
+ "presets.fits_tiff": "FITS (صور فلكية) إلى TIFF",
+ "presets.fits_tiff.Linear": "خطي: البيانات كما هي",
+ "presets.fits_tiff.Stretched": "ممدود، كما في المعاينة",
+ "presets.fits_tiff_hint": "لصور كاميرات التلسكوب. يحافظ TIFF على عمق البتات في الملف: تبقى 8 و16 بت كما هي، وتصبح بيانات 32 بت والفاصلة العائمة فاصلةً عائمة بـ32 بت.",
+ "presets.fits_debayer": "إزالة نمط Bayer من FITS لكاميرا ملونة",
+ "presets.fits_debayer_hint": "تُمدّ صور FITS تلقائيًا. يصبح الإطار الخام من كاميرا ملونة ملونًا بنمط Bayer المذكور في ترويسته؛ وعند الإيقاف يبقى أحادي اللون.",
"presets.animation_speed": "سرعة التشغيل",
"presets.animation_speed_hint": "يعرض كل إطار من الصورة المتحركة لمدة أقصر أو أطول.\nتعرض المشغّلات 50 إطارًا في الثانية كحد أقصى، لذا قد تُحذف إطارات عند زيادة السرعة.",
"presets.animation_speed.original": "1× (الأصلية)",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 18728c16..e4c4680c 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "Lossless WEBP",
"presets.multipage_tiff": "Put every file into one multi-page TIFF",
"presets.multipage_tiff_hint": "Each image and each PDF or TIFF page becomes a page, in order.\nOne PDF is enough for a multi-page TIFF.",
+ "presets.fits_tiff": "FITS (astronomy) to TIFF",
+ "presets.fits_tiff.Linear": "Linear: the data as it is",
+ "presets.fits_tiff.Stretched": "Stretched, like a preview",
+ "presets.fits_tiff_hint": "For pictures from a telescope camera. The TIFF keeps the file's bit depth: 8 and 16 bits stay as they are, 32-bit and floating-point data become 32-bit floating point.",
+ "presets.fits_debayer": "Debayer FITS from a colour camera",
+ "presets.fits_debayer_hint": "FITS pictures are stretched automatically. A raw frame from a colour camera becomes colour with the Bayer pattern in its header; off keeps it mono.",
"presets.animation_speed": "Playback speed",
"presets.animation_speed_hint": "Shows each frame of an animation for a shorter or longer time.\nPlayers show at most 50 frames a second, so a faster animation leaves frames out.",
"presets.animation_speed.original": "1× (original)",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 1bf67b28..28a5f9e5 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "WEBP sin pérdida",
"presets.multipage_tiff": "Poner todos los archivos en un TIFF multipágina",
"presets.multipage_tiff_hint": "Cada imagen y cada página de PDF o TIFF pasa a ser una página, en orden.\nCon un PDF basta para un TIFF multipágina.",
+ "presets.fits_tiff": "FITS (astronomía) a TIFF",
+ "presets.fits_tiff.Linear": "Lineal: los datos tal cual",
+ "presets.fits_tiff.Stretched": "Estirado, como una vista previa",
+ "presets.fits_tiff_hint": "Para imágenes de una cámara de telescopio. El TIFF conserva la profundidad de bits del archivo: 8 y 16 bits se quedan igual, los datos de 32 bits y de coma flotante pasan a coma flotante de 32 bits.",
+ "presets.fits_debayer": "Debayerizar FITS de una cámara a color",
+ "presets.fits_debayer_hint": "Las imágenes FITS se estiran automáticamente. Un fotograma en bruto de una cámara a color pasa a color con el patrón Bayer de su cabecera; desactivado, queda en monocromo.",
"presets.animation_speed": "Velocidad de reproducción",
"presets.animation_speed_hint": "Acorta o alarga el tiempo que se muestra cada fotograma de una animación.\nLos reproductores muestran como máximo 50 fotogramas por segundo, así que una animación más rápida omite fotogramas.",
"presets.animation_speed.original": "1× (original)",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 8405ed0a..8df8e92f 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "WEBP sans perte",
"presets.multipage_tiff": "Réunir tous les fichiers dans un TIFF multipage",
"presets.multipage_tiff_hint": "Chaque image et chaque page de PDF ou de TIFF devient une page, dans l'ordre.\nUn seul PDF suffit pour un TIFF multipage.",
+ "presets.fits_tiff": "FITS (astronomie) en TIFF",
+ "presets.fits_tiff.Linear": "Linéaire : les données telles quelles",
+ "presets.fits_tiff.Stretched": "Étiré, comme un aperçu",
+ "presets.fits_tiff_hint": "Pour les images d'une caméra de télescope. Le TIFF garde la profondeur du fichier : 8 et 16 bits restent tels quels, les données 32 bits et à virgule flottante deviennent de la virgule flottante 32 bits.",
+ "presets.fits_debayer": "Dématricer les FITS d'une caméra couleur",
+ "presets.fits_debayer_hint": "Les images FITS sont étirées automatiquement. Une image brute d'une caméra couleur passe en couleur avec la matrice de Bayer de son en-tête ; désactivé, elle reste monochrome.",
"presets.animation_speed": "Vitesse de lecture",
"presets.animation_speed_hint": "Affiche chaque image d'une animation plus ou moins longtemps.\nLes lecteurs affichent au plus 50 images par seconde : une animation plus rapide saute donc des images.",
"presets.animation_speed.original": "1× (original)",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 1e950027..2c9e8dd3 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "लॉसलेस WEBP",
"presets.multipage_tiff": "सभी फ़ाइलों को एक मल्टी-पेज TIFF में रखें",
"presets.multipage_tiff_hint": "हर इमेज और हर PDF या TIFF पेज क्रम से एक पेज बनता है।\nमल्टी-पेज TIFF के लिए एक PDF भी काफ़ी है।",
+ "presets.fits_tiff": "FITS (खगोल) से TIFF",
+ "presets.fits_tiff.Linear": "लीनियर: डेटा जैसा है वैसा",
+ "presets.fits_tiff.Stretched": "स्ट्रेच किया हुआ, प्रीव्यू की तरह",
+ "presets.fits_tiff_hint": "टेलीस्कोप कैमरे की इमेज के लिए। TIFF फ़ाइल की बिट डेप्थ रखता है: 8 और 16 बिट वैसे ही रहते हैं, 32-बिट और फ़्लोटिंग-पॉइंट डेटा 32-बिट फ़्लोटिंग पॉइंट बनता है।",
+ "presets.fits_debayer": "कलर कैमरे की FITS को डीबेयर करें",
+ "presets.fits_debayer_hint": "FITS इमेज अपने-आप स्ट्रेच होती हैं। कलर कैमरे का रॉ फ़्रेम उसके हेडर के Bayer पैटर्न से रंगीन बनता है; बंद होने पर मोनो रहता है।",
"presets.animation_speed": "प्लेबैक स्पीड",
"presets.animation_speed_hint": "एनिमेशन के हर फ़्रेम को कम या ज़्यादा समय तक दिखाता है।\nप्लेयर एक सेकंड में ज़्यादा से ज़्यादा 50 फ़्रेम दिखाते हैं, इसलिए तेज़ एनिमेशन में कुछ फ़्रेम छूट जाते हैं।",
"presets.animation_speed.original": "1× (मूल)",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 8c1c8845..1ba978de 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "WEBP(可逆圧縮)",
"presets.multipage_tiff": "すべてのファイルを1つのマルチページTIFFにまとめる",
"presets.multipage_tiff_hint": "各画像と、PDFやTIFFの各ページを順番に1ページずつ配置します。\nPDF1つからでもマルチページTIFFを作成できます。",
+ "presets.fits_tiff": "FITS(天体写真)→ TIFF",
+ "presets.fits_tiff.Linear": "リニア:データをそのまま",
+ "presets.fits_tiff.Stretched": "ストレッチ:プレビューのように",
+ "presets.fits_tiff_hint": "望遠鏡カメラの画像向けです。TIFFはファイルのビット深度を保ちます:8ビットと16ビットはそのまま、32ビットと浮動小数点のデータは32ビット浮動小数点になります。",
+ "presets.fits_debayer": "カラーカメラのFITSをディベイヤー",
+ "presets.fits_debayer_hint": "FITS画像は自動でストレッチされます。カラーカメラのRAWフレームはヘッダーのベイヤーパターンでカラーになります。オフにするとモノクロのままです。",
"presets.animation_speed": "再生速度",
"presets.animation_speed_hint": "アニメーションの各フレームを表示する時間を短く、または長くします。\nプレーヤーは1秒あたり最大50フレームまでしか表示できないため、それより速いアニメーションでは一部のフレームが省かれます。",
"presets.animation_speed.original": "1倍(元の速度)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index d28d12be..c94a990a 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "무손실 WEBP",
"presets.multipage_tiff": "모든 파일을 여러 페이지짜리 TIFF 하나로 합치기",
"presets.multipage_tiff_hint": "이미지 한 장, PDF·TIFF 한 페이지가 순서대로 한 페이지씩 들어가요.\nPDF 하나만 넣어도 여러 페이지 TIFF가 돼요.",
+ "presets.fits_tiff": "FITS(천체 사진)를 TIFF로",
+ "presets.fits_tiff.Linear": "선형: 데이터 그대로",
+ "presets.fits_tiff.Stretched": "스트레치: 미리보기처럼",
+ "presets.fits_tiff_hint": "망원경 카메라로 찍은 사진용이에요. TIFF는 파일의 비트 깊이를 따라가요: 8비트와 16비트는 그대로, 32비트와 부동소수점 데이터는 32비트 부동소수점이 돼요.",
+ "presets.fits_debayer": "컬러 카메라 FITS 디베이어",
+ "presets.fits_debayer_hint": "FITS 사진은 자동으로 스트레치돼요. 컬러 카메라의 RAW 프레임은 헤더의 베이어 패턴으로 컬러가 되고, 끄면 흑백 그대로 남아요.",
"presets.animation_speed": "재생 속도",
"presets.animation_speed_hint": "애니메이션의 각 프레임을 보여 주는 시간을 줄이거나 늘려요.\n뷰어는 1초에 50프레임까지만 보여 줘서, 그보다 빨라지면 프레임을 건너뛰어요.",
"presets.animation_speed.original": "1× (원본)",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index ee1c1ef4..02b6d78d 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "लसलेस WEBP",
"presets.multipage_tiff": "प्रत्येक फाइललाई बहु-पृष्ठ TIFF मा राख्नुहोस्",
"presets.multipage_tiff_hint": "प्रत्येक छवि र प्रत्येक PDF वा TIFF पृष्ठ क्रमबद्ध रूपमा पृष्ठ बन्दछ।\nबहु-पृष्ठ TIFF का लागि एउटा PDF पनि पर्याप्त हुन्छ।",
+ "presets.fits_tiff": "FITS (खगोलीय) बाट TIFF",
+ "presets.fits_tiff.Linear": "लिनियर: डेटा जस्तो छ त्यस्तै",
+ "presets.fits_tiff.Stretched": "स्ट्रेच गरिएको, प्रिभ्यूजस्तै",
+ "presets.fits_tiff_hint": "टेलिस्कोप क्यामेराका तस्बिरका लागि। TIFF ले फाइलको बिट डेप्थ राख्छ: 8 र 16 बिट जस्ताको तस्तै रहन्छन्, 32-बिट र फ्लोटिङ-पोइन्ट डेटा 32-बिट फ्लोटिङ पोइन्ट हुन्छ।",
+ "presets.fits_debayer": "रङ्गीन क्यामेराको FITS डिबेयर गर्नुहोस्",
+ "presets.fits_debayer_hint": "FITS तस्बिरहरू आफैँ स्ट्रेच हुन्छन्। रङ्गीन क्यामेराको र फ्रेम यसको हेडरको Bayer ढाँचाले रङ्गीन बन्छ; बन्द गर्दा मोनो नै रहन्छ।",
"presets.animation_speed": "प्लेब्याक गति",
"presets.animation_speed_hint": "एनिमेसनको प्रत्येक फ्रेम छोटो वा लामो समयका लागि देखाउँछ।\nप्लेयरहरूले प्रति सेकेन्ड बढीमा ५० फ्रेम देखाउँछन्, त्यसैले छिटो एनिमेसनमा केही फ्रेमहरू छुट्न सक्छन्।",
"presets.animation_speed.original": "१× (मूल)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 6efd97f6..e4ee5a8b 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "Bezstratny WEBP",
"presets.multipage_tiff": "Umieść wszystkie pliki w jednym wielostronicowym TIFF",
"presets.multipage_tiff_hint": "Każdy obraz i każda strona PDF lub TIFF staje się stroną, po kolei.\nJeden PDF wystarczy do wielostronicowego TIFF.",
+ "presets.fits_tiff": "FITS (astronomia) do TIFF",
+ "presets.fits_tiff.Linear": "Liniowo: dane bez zmian",
+ "presets.fits_tiff.Stretched": "Rozciągnięte, jak podgląd",
+ "presets.fits_tiff_hint": "Dla zdjęć z kamery teleskopowej. TIFF zachowuje głębię bitową pliku: 8 i 16 bitów zostaje bez zmian, dane 32-bitowe i zmiennoprzecinkowe stają się 32-bitowymi zmiennoprzecinkowymi.",
+ "presets.fits_debayer": "Debayeryzuj FITS z kamery kolorowej",
+ "presets.fits_debayer_hint": "Zdjęcia FITS są rozciągane automatycznie. Surowa klatka z kamery kolorowej staje się kolorowa dzięki wzorowi Bayera z nagłówka; po wyłączeniu zostaje monochromatyczna.",
"presets.animation_speed": "Prędkość odtwarzania",
"presets.animation_speed_hint": "Skraca lub wydłuża czas wyświetlania każdej klatki animacji.\nOdtwarzacze pokazują najwyżej 50 klatek na sekundę, więc szybsza animacja pomija część klatek.",
"presets.animation_speed.original": "1× (oryginalna)",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index bab61f71..b06ec074 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "WEBP sem perdas",
"presets.multipage_tiff": "Colocar todos os arquivos num único TIFF de várias páginas",
"presets.multipage_tiff_hint": "Cada imagem e cada página de PDF ou TIFF vira uma página, em ordem.\nUm PDF basta para um TIFF de várias páginas.",
+ "presets.fits_tiff": "FITS (astronomia) para TIFF",
+ "presets.fits_tiff.Linear": "Linear: os dados como estão",
+ "presets.fits_tiff.Stretched": "Esticado, como uma prévia",
+ "presets.fits_tiff_hint": "Para imagens de uma câmera de telescópio. O TIFF mantém a profundidade de bits do arquivo: 8 e 16 bits ficam como estão, dados de 32 bits e de ponto flutuante viram ponto flutuante de 32 bits.",
+ "presets.fits_debayer": "Fazer debayer de FITS de câmera colorida",
+ "presets.fits_debayer_hint": "Imagens FITS são esticadas automaticamente. Um quadro bruto de uma câmera colorida vira colorido com o padrão Bayer do cabeçalho; desligado, fica monocromático.",
"presets.animation_speed": "Velocidade de reprodução",
"presets.animation_speed_hint": "Mostra cada quadro de uma animação por menos ou mais tempo.\nOs reprodutores mostram no máximo 50 quadros por segundo, então uma animação mais rápida deixa quadros de fora.",
"presets.animation_speed.original": "1× (original)",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 01fc79be..b8359182 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "WEBP без потерь",
"presets.multipage_tiff": "Собрать все файлы в один многостраничный TIFF",
"presets.multipage_tiff_hint": "Каждая картинка и каждая страница PDF или TIFF становится страницей, по порядку.\nДля многостраничного TIFF хватит одного PDF.",
+ "presets.fits_tiff": "FITS (астрофото) в TIFF",
+ "presets.fits_tiff.Linear": "Линейно: данные как есть",
+ "presets.fits_tiff.Stretched": "С растяжкой, как в превью",
+ "presets.fits_tiff_hint": "Для снимков с телескопной камеры. TIFF сохраняет разрядность файла: 8 и 16 бит остаются как есть, 32-битные целые и данные с плавающей точкой становятся 32-битными с плавающей точкой.",
+ "presets.fits_debayer": "Дебайеризовать FITS с цветной камеры",
+ "presets.fits_debayer_hint": "Снимки FITS растягиваются автоматически. Сырой кадр с цветной камеры становится цветным по шаблону Байера из заголовка; если выключить, останется монохромным.",
"presets.animation_speed": "Скорость воспроизведения",
"presets.animation_speed_hint": "Показывает каждый кадр анимации дольше или короче.\nПроигрыватели показывают не больше 50 кадров в секунду, поэтому в более быстрой анимации кадры пропадают.",
"presets.animation_speed.original": "1× (исходная)",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index dea6b097..b1ac90e4 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -503,6 +503,12 @@
"presets.webp_lossless": "WEBP แบบไม่สูญเสียรายละเอียด (Lossless)",
"presets.multipage_tiff": "รวมทุกไฟล์เป็น TIFF หลายหน้าไฟล์เดียว",
"presets.multipage_tiff_hint": "แต่ละภาพและแต่ละหน้าของ PDF หรือ TIFF จะกลายเป็นหน้าหนึ่งตามลำดับ\nใช้ PDF เพียงไฟล์เดียวก็สร้าง TIFF หลายหน้าได้",
+ "presets.fits_tiff": "FITS (ภาพดาราศาสตร์) เป็น TIFF",
+ "presets.fits_tiff.Linear": "เชิงเส้น: ข้อมูลตามเดิม",
+ "presets.fits_tiff.Stretched": "ยืดค่า (Stretch) แบบภาพพรีวิว",
+ "presets.fits_tiff_hint": "สำหรับภาพจากกล้องติดกล้องโทรทรรศน์ TIFF จะคงความลึกบิตของไฟล์ไว้: 8 และ 16 บิตคงเดิม ส่วนข้อมูล 32 บิตและทศนิยมลอยตัวจะเป็นทศนิยมลอยตัว 32 บิต",
+ "presets.fits_debayer": "ดีเบเยอร์ FITS จากกล้องสี",
+ "presets.fits_debayer_hint": "ภาพ FITS จะถูกยืดค่าโดยอัตโนมัติ เฟรมดิบจากกล้องสีจะกลายเป็นภาพสีตามรูปแบบ Bayer ในส่วนหัวของไฟล์ หากปิดไว้จะคงเป็นขาวดำ",
"presets.animation_speed": "ความเร็วในการเล่น",
"presets.animation_speed_hint": "แสดงแต่ละเฟรมของภาพเคลื่อนไหวให้เร็วขึ้นหรือช้าลง\nโปรแกรมเล่นส่วนใหญ่แสดงผลได้สูงสุด 50 เฟรมต่อวินาที ภาพเคลื่อนไหวที่เร็วขึ้นจึงอาจมีการข้ามบางเฟรมไป",
"presets.animation_speed.original": "1× (ต้นฉบับ)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index e6927560..4e0e61e5 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "无损 WEBP",
"presets.multipage_tiff": "将所有文件合并为一个多页 TIFF",
"presets.multipage_tiff_hint": "每张图片以及 PDF、TIFF 的每一页按顺序各成一页。\n只放一个 PDF 也能得到多页 TIFF。",
+ "presets.fits_tiff": "FITS(天文图像)转 TIFF",
+ "presets.fits_tiff.Linear": "线性:数据保持原样",
+ "presets.fits_tiff.Stretched": "拉伸:如同预览",
+ "presets.fits_tiff_hint": "适用于望远镜相机拍摄的图像。TIFF 保留文件的位深:8 位和 16 位保持不变,32 位整数和浮点数据转为 32 位浮点。",
+ "presets.fits_debayer": "对彩色相机的 FITS 去马赛克",
+ "presets.fits_debayer_hint": "FITS 图像会自动拉伸。彩色相机的原始帧按文件头中的拜耳阵列转为彩色;关闭时保持黑白。",
"presets.animation_speed": "播放速度",
"presets.animation_speed_hint": "缩短或延长动画每一帧的显示时间。\n播放器每秒最多显示 50 帧,更快时会跳过部分帧。",
"presets.animation_speed.original": "1×(原速)",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 6134c61f..eb08a973 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -518,6 +518,12 @@
"presets.webp_lossless": "無損 WEBP",
"presets.multipage_tiff": "將所有檔案合併為一個多頁 TIFF",
"presets.multipage_tiff_hint": "每張圖片以及 PDF、TIFF 的每一頁按順序各成一頁。\n只放一個 PDF 也能得到多頁 TIFF。",
+ "presets.fits_tiff": "FITS(天文影像)轉 TIFF",
+ "presets.fits_tiff.Linear": "線性:資料保持原樣",
+ "presets.fits_tiff.Stretched": "拉伸:如同預覽",
+ "presets.fits_tiff_hint": "適用於望遠鏡相機拍攝的影像。TIFF 保留檔案的位元深度:8 位元和 16 位元保持不變,32 位元整數和浮點資料轉為 32 位元浮點。",
+ "presets.fits_debayer": "對彩色相機的 FITS 去馬賽克",
+ "presets.fits_debayer_hint": "FITS 影像會自動拉伸。彩色相機的原始畫格依檔頭中的拜耳陣列轉為彩色;關閉時維持黑白。",
"presets.animation_speed": "播放速度",
"presets.animation_speed_hint": "縮短或延長動畫每個影格的顯示時間。\n播放器每秒最多顯示 50 個影格,更快時會跳過部分影格。",
"presets.animation_speed.original": "1×(原速)",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 81c655c3..5e6eedf2 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -94,6 +94,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
Locations = Enum.GetValues<OutputLocation>().Select(v => new Choice<OutputLocation>(v, loc[$"presets.location.{v}"])).ToList();
Conflicts = Enum.GetValues<ConflictPolicy>().Select(v => new Choice<ConflictPolicy>(v, loc[$"presets.conflict.{v}"])).ToList();
TiffCompressions = Enum.GetValues<TiffCompression>().Select(v => new Choice<TiffCompression>(v, v.ToString().ToUpperInvariant())).ToList();
+ FitsTiffModes = Enum.GetValues<FitsTiffMode>().Select(v => new Choice<FitsTiffMode>(v, loc[$"presets.fits_tiff.{v}"])).ToList();
MediaQualities = Enum.GetValues<MediaQuality>().Select(v => new Choice<MediaQuality>(v, loc[$"presets.media_quality.{v}"])).ToList();
MaxHeights = Steps(MaxHeightSteps, _edit.Media.MaxHeight, h => h == 0 ? loc["presets.max_height.original"] : $"{h}p");
AudioBitrates = Steps(BitrateSteps, _edit.Media.AudioBitrateKbps, k => k == 0 ? loc["presets.audio_bitrate.auto"] : $"{k} kbps");
@@ -120,6 +121,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_location = Locations.First(l => l.Value == _edit.Output.Location);
_conflict = Conflicts.First(c => c.Value == _edit.Output.Conflict);
_tiffCompression = TiffCompressions.First(t => t.Value == _edit.Image.TiffCompression);
+ _fitsTiffMode = FitsTiffModes.FirstOrDefault(m => m.Value == _edit.Image.FitsTiff) ?? FitsTiffModes[0];
+ _fitsDebayer = _edit.Image.FitsDebayer;
_mediaQuality = MediaQualities.First(q => q.Value == _edit.Media.Quality);
_maxHeight = MaxHeights.First(h => h.Value == _edit.Media.MaxHeight);
_audioBitrate = AudioBitrates.First(b => b.Value == _edit.Media.AudioBitrateKbps);
@@ -204,6 +207,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public IReadOnlyList<Choice<OutputLocation>> Locations { get; }
public IReadOnlyList<Choice<ConflictPolicy>> Conflicts { get; }
public IReadOnlyList<Choice<TiffCompression>> TiffCompressions { get; }
+
+ /// <summary>FITS → TIFF: the data as it is, or stretched (ImageOptions.FitsTiff).</summary>
+ public IReadOnlyList<Choice<FitsTiffMode>> FitsTiffModes { get; }
public IReadOnlyList<Choice<MediaQuality>> MediaQualities { get; }
public IReadOnlyList<Choice<int>> MaxHeights { get; }
public IReadOnlyList<Choice<int>> AudioBitrates { get; }
@@ -221,6 +227,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
+ nameof(ShowFitsTiff), nameof(ShowFitsDebayer),
nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowOcr), nameof(ShowPageSize),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
@@ -360,6 +367,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private Choice<ConflictPolicy> _conflict;
[ObservableProperty] private Choice<TiffCompression> _tiffCompression;
+ [ObservableProperty] private Choice<FitsTiffMode> _fitsTiffMode;
+
+ /// <summary>FITS → other pictures: debayer a colour camera's raw frame (ImageOptions.FitsDebayer).</summary>
+ [ObservableProperty] private bool _fitsDebayer;
[ObservableProperty] private int _quality;
[ObservableProperty] private int _resizePercent;
[ObservableProperty] private int _longEdge;
@@ -481,6 +492,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
partial void OnConflictChanged(Choice<ConflictPolicy>? oldValue, Choice<ConflictPolicy> newValue) => Choices.Restore(oldValue, newValue, v => Conflict = v);
partial void OnTiffCompressionChanged(Choice<TiffCompression>? oldValue, Choice<TiffCompression> newValue) =>
Choices.Restore(oldValue, newValue, v => TiffCompression = v);
+ partial void OnFitsTiffModeChanged(Choice<FitsTiffMode>? oldValue, Choice<FitsTiffMode> newValue) =>
+ Choices.Restore(oldValue, newValue, v => FitsTiffMode = v);
partial void OnMediaQualityChanged(Choice<MediaQuality>? oldValue, Choice<MediaQuality> newValue) => Choices.Restore(oldValue, newValue, v => MediaQuality = v);
partial void OnMaxHeightChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => MaxHeight = v);
partial void OnAudioBitrateChanged(Choice<int>? oldValue, Choice<int> newValue) => Choices.Restore(oldValue, newValue, v => AudioBitrate = v);
@@ -519,6 +532,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowTiff => TargetId is "tiff" or BuiltInData.SameAsSource;
public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;
public bool ShowMultiPageTiff => TargetId is "tiff";
+ /// <summary>FITS (astronomy) → TIFF: linear or stretched, at the file's own depth.</summary>
+ public bool ShowFitsTiff => !IsTool && TargetId is "tiff";
+ /// <summary>FITS → any other picture is stretched; a colour camera's raw frame can be debayered or kept mono.</summary>
+ public bool ShowFitsDebayer => !IsTool && TargetCategory == FormatCategory.Image && TargetId != "tiff";
public bool ShowIco => TargetId == "ico";
/// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font, subtitle, data, e-mail, 3D and geospatial targets.</summary>
public bool ShowPdf => !IsTool && !IsLivePhoto && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
@@ -622,6 +639,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
image.TiffCompression = TiffCompression.Value;
image.WebpLossless = WebpLossless;
image.MultiPageTiff = MultiPageTiff;
+ image.FitsTiff = FitsTiffMode.Value;
+ image.FitsDebayer = FitsDebayer;
image.IcoSizes = IcoSizes.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(s => int.TryParse(s, out var v) ? v : 0)
.Where(v => v is > 0 and <= 256)
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 8d8e132a..404b5edb 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -173,6 +173,15 @@
</Grid>
<CheckBox Content="{DynamicResource presets.multipage_tiff}" IsChecked="{Binding MultiPageTiff}" IsVisible="{Binding ShowMultiPageTiff}"
ToolTip.Tip="{DynamicResource presets.multipage_tiff_hint}" />
+ <Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowFitsTiff}">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.fits_tiff}" />
+ <ComboBox ItemsSource="{Binding FitsTiffModes}" SelectedItem="{Binding FitsTiffMode}" HorizontalAlignment="Stretch"
+ ToolTip.Tip="{DynamicResource presets.fits_tiff_hint}" />
+ </StackPanel>
+ </Grid>
+ <CheckBox Content="{DynamicResource presets.fits_debayer}" IsChecked="{Binding FitsDebayer}" IsVisible="{Binding ShowFitsDebayer}"
+ ToolTip.Tip="{DynamicResource presets.fits_debayer_hint}" />
<StackPanel Spacing="6" IsVisible="{Binding ShowSaveEveryFrame}">
<CheckBox Content="{DynamicResource presets.save_every_frame}" IsChecked="{Binding SaveEveryFrame}"
ToolTip.Tip="{DynamicResource presets.save_every_frame_hint}" />
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 28ccc18b..24c69e5d 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -47,6 +47,9 @@ public static class FormatRegistry
new("pcd", "Photo CD", FormatCategory.Image, ["pcd"], Writable: false),
new("exr", "OpenEXR", FormatCategory.Image, ["exr"], Writable: false),
new("hdr", "Radiance HDR", FormatCategory.Image, ["hdr"], Writable: false),
+ // Astronomy pictures from telescope cameras and stacking software, read by Filee itself (issue #460). ".fit" is
+ // left to Garmin's FIT activity files (issue #451).
+ new("fits", "FITS", FormatCategory.Image, ["fits", "fts"], Writable: false),
// Read on Windows only, with its own codec (HDR screenshots of Windows are JPEG XR).
new("jxr", "JPEG XR", FormatCategory.Image, ["jxr", "wdp", "hdp"], Writable: false),
new("xcf", "XCF", FormatCategory.Image, ["xcf"], Writable: false),
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index b543e8b9..2c33189c 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -249,6 +249,15 @@ public enum TiffCompression
Zip,
}
+/// <summary>What a FITS astronomy picture becomes in a TIFF (<see cref="ImageOptions.FitsTiff"/>).</summary>
+public enum FitsTiffMode
+{
+ /// <summary>The data as it is, at the file's own bit depth: for further processing.</summary>
+ Linear,
+ /// <summary>Automatically stretched like a capture program's preview, at the file's own bit depth.</summary>
+ Stretched,
+}
+
/// <summary>Raster image encoding options.</summary>
public sealed class ImageOptions
{
@@ -340,6 +349,19 @@ public sealed class ImageOptions
/// <summary>Use lossless WEBP encoding.</summary>
public bool WebpLossless { get; set; }
+ /// <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.
+ /// </summary>
+ [JsonConverter(typeof(LenientEnumJsonConverter<FitsTiffMode>))]
+ public FitsTiffMode FitsTiff { get; set; }
+
+ /// <summary>
+ /// FITS → any other picture (stretched automatically): a raw frame of a colour camera becomes colour with the Bayer
+ /// pattern in its header. Off keeps it mono. Mono cameras and three-plane colour files are not affected.
+ /// </summary>
+ public bool FitsDebayer { get; set; } = true;
+
/// <summary>Icon sizes embedded in an ICO file.</summary>
public List<int> IcoSizes { get; set; } = [256, 128, 64, 48, 32, 16];
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 5c678059..ef6a3867 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 = 41;
+ public const int CurrentSchemaVersion = 42;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 19a310b4..3ec195be 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -807,6 +807,10 @@ internal static class SettingsMigrations
// v41: PNG/JPEG download aliases learn the images donut; custom claims stay put.
if (from < 41)
changed |= LearnExtensions(profiles, out _, ["png_large", "jpg_large"]);
+ // v42: FITS astronomy pictures (.fits, .fts) learn the images donut; custom claims stay put. (Schema 42 may be
+ // renumbered if another change takes it first.)
+ if (from < 42)
+ changed |= LearnExtensions(profiles, out _, ["fits", "fts"]);
return changed;
}
diff --git a/src/Filee.Engines/Magick/Fits.cs b/src/Filee.Engines/Magick/Fits.cs
new file mode 100644
index 00000000..c011bcae
--- /dev/null
+++ b/src/Filee.Engines/Magick/Fits.cs
@@ -0,0 +1,308 @@
+// FITS images (Flexible Image Transport System: telescope cameras, capture and stacking software), read by Filee itself
+// from the FITS standard 4.0: 2880-byte blocks, a header of 80-character cards, big-endian data. ImageMagick's Q8 build
+// would cut 16- and 32-bit data down to 8 bits and knows nothing of Bayer patterns, so the values are read here as they
+// are (BZERO + BSCALE × stored) for FitsRendering to stretch, debayer or write into a TIFF of the file's own depth.
+// The first HDU holding a picture is read: the primary one, or else the first IMAGE extension. Tile-compressed images
+// (fpack, ".fz") are not read.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Text;
+
+namespace Filee.Engines.Magick;
+
+/// <summary>
+/// A FITS picture: the physical values of its planes in the order the file stores them, and what the header says
+/// about them.
+/// </summary>
+internal sealed class FitsImage
+{
+ public required int Width { get; init; }
+ public required int Height { get; init; }
+
+ /// <summary>One plane (mono, or the mosaic of a colour camera) or three (red, green, blue).</summary>
+ public required float[][] Planes { get; init; }
+
+ /// <summary>BITPIX: 8, 16, 32 or 64 for integers, -32 or -64 for floating point.</summary>
+ public required int Bitpix { get; init; }
+
+ /// <summary>Smallest and largest finite value of all planes (0 and 0 when there is none).</summary>
+ public required float Min { get; init; }
+ public required float Max { get; init; }
+
+ /// <summary>Every value is a whole number (integer data with a whole BZERO and BSCALE and no BLANK pixels).</summary>
+ public required bool Integral { get; init; }
+
+ /// <summary>The colour filter pattern at the first stored pixel (RGGB, BGGR, GRBG or GBRG), or null.</summary>
+ public string? BayerPattern { get; init; }
+
+ /// <summary>XBAYROFF / YBAYROFF: where the pattern starts, 0 or 1.</summary>
+ public int BayerOffsetX { get; init; }
+ public int BayerOffsetY { get; init; }
+
+ /// <summary>ROWORDER = 'BOTTOM-UP': the first stored row is the bottom of the picture.</summary>
+ public bool BottomUp { get; init; }
+}
+
+/// <summary>Reads the picture of a FITS file.</summary>
+internal static class Fits
+{
+ private const int BlockSize = 2880;
+ private const int CardSize = 80;
+
+ /// <summary>Most values one picture may have (a 1 GB array of floats, about a 16 000 × 16 000 mosaic).</summary>
+ private const long MaxSamples = 256L * 1024 * 1024;
+
+ /// <summary>Header blocks one HDU may have before its END card (36 cards each): far more than any real file.</summary>
+ private const int MaxHeaderBlocks = 10_000;
+
+ private static readonly string[] Patterns = ["RGGB", "BGGR", "GRBG", "GBRG"];
+
+ /// <summary>Keywords that name the Bayer pattern, in the order they are looked for.</summary>
+ private static readonly string[] PatternKeywords = ["BAYERPAT", "COLORTYP"];
+
+ /// <exception cref="InvalidDataException">The file is not FITS, is damaged, or has no picture Filee reads.</exception>
+ public static FitsImage Read(string path, CancellationToken cancellationToken = default)
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16);
+ Dictionary<string, string>? primary = null;
+ var compressed = false;
+ long position = 0;
+ for (var hdu = 0; position < stream.Length; hdu++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ stream.Position = position;
+ var header = ReadHeader(stream, hdu == 0);
+ primary ??= header;
+ var bitpix = (int)Integer(header, "BITPIX");
+ if (bitpix is not (8 or 16 or 32 or 64 or -32 or -64))
+ throw new InvalidDataException($"This FITS file has an unknown BITPIX ({bitpix}).");
+ var naxis = Integer(header, "NAXIS");
+ if (naxis is < 0 or > 999)
+ throw new InvalidDataException("This FITS file is damaged (NAXIS).");
+ var axes = new long[naxis];
+ for (var i = 0; i < axes.Length; i++)
+ {
+ axes[i] = Integer(header, $"NAXIS{i + 1}");
+ if (axes[i] < 0)
+ throw new InvalidDataException("This FITS file is damaged (a negative axis length).");
+ }
+ var dataStart = stream.Position;
+ var extension = hdu == 0 ? null : Text(header, "XTENSION");
+ if (axes.Length >= 2 && axes[0] > 0 && axes[1] > 0 && (hdu == 0 || extension == "IMAGE"))
+ return ReadImage(stream, dataStart, header, primary, bitpix, axes, cancellationToken);
+ if (extension == "BINTABLE" && Text(header, "ZIMAGE") == "T")
+ compressed = true;
+
+ // Skip the data: |BITPIX| / 8 × GCOUNT × (PCOUNT + NAXIS1 × … × NAXISn), padded to whole blocks.
+ long elements = axes.Length == 0 ? 0 : 1;
+ foreach (var axis in axes)
+ elements = checked(elements * axis);
+ var groups = hdu == 0 ? 1 : Optional(header, "GCOUNT", 1);
+ var parameters = hdu == 0 ? 0 : Optional(header, "PCOUNT", 0);
+ var bytes = elements == 0 && parameters == 0 ? 0 : checked(Math.Abs(bitpix) / 8 * groups * (parameters + elements));
+ position = dataStart + (bytes + BlockSize - 1) / BlockSize * BlockSize;
+ }
+ throw new InvalidDataException(compressed
+ ? "This FITS file is tile-compressed (fpack). Uncompress it first (funpack) and try again."
+ : "This FITS file has no picture: it holds only tables or an empty header.");
+ }
+
+ private static FitsImage ReadImage(Stream stream, long dataStart, Dictionary<string, string> header,
+ Dictionary<string, string> primary, int bitpix, long[] axes, CancellationToken cancellationToken)
+ {
+ var (width, height) = (axes[0], axes[1]);
+ // A cube of three planes is red, green and blue; of any other depth, the first plane is read.
+ var planeCount = axes.Length >= 3 && axes[2] == 3 && axes.Skip(3).All(a => a == 1) ? 3 : 1;
+ if (width > MaxSamples || height > MaxSamples || width * height > MaxSamples / planeCount)
+ throw new InvalidDataException($"This FITS picture is too large ({width} × {height}).");
+
+ var bzero = Real(header, "BZERO", 0);
+ var bscale = Real(header, "BSCALE", 1);
+ long? blank = bitpix > 0 && header.ContainsKey("BLANK") ? Integer(header, "BLANK") : null;
+ var bytesPerValue = Math.Abs(bitpix) / 8;
+ var pixels = (int)(width * height);
+ var row = new byte[(int)width * bytesPerValue];
+ var planes = new float[planeCount][];
+ var (min, max) = (float.PositiveInfinity, float.NegativeInfinity);
+ var blanks = false;
+ stream.Position = dataStart;
+ for (var p = 0; p < planeCount; p++)
+ {
+ var plane = planes[p] = new float[pixels];
+ for (var y = 0; y < height; y++)
+ {
+ if ((y & 63) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ stream.ReadExactly(row);
+ var values = plane.AsSpan(y * (int)width, (int)width);
+ blanks |= Decode(row, values, bitpix, bzero, bscale, blank);
+ foreach (var value in values)
+ {
+ if (float.IsFinite(value))
+ {
+ if (value < min)
+ min = value;
+ if (value > max)
+ max = value;
+ }
+ }
+ }
+ }
+ if (min > max)
+ (min, max) = (0, 0);
+
+ string? pattern = null;
+ if (planeCount == 1)
+ {
+ foreach (var keyword in PatternKeywords)
+ {
+ var text = (Text(header, keyword) ?? Text(primary, keyword))?.Trim().ToUpperInvariant();
+ if (text is not null && Patterns.Contains(text))
+ {
+ pattern = text;
+ break;
+ }
+ }
+ }
+ return new FitsImage
+ {
+ Width = (int)width,
+ Height = (int)height,
+ Planes = planes,
+ Bitpix = bitpix,
+ Min = min,
+ Max = max,
+ Integral = bitpix > 0 && bzero == Math.Floor(bzero) && bscale == Math.Floor(bscale) && !blanks,
+ BayerPattern = pattern,
+ BayerOffsetX = Parity(Optional(header, "XBAYROFF", Optional(primary, "XBAYROFF", 0))),
+ BayerOffsetY = Parity(Optional(header, "YBAYROFF", Optional(primary, "YBAYROFF", 0))),
+ BottomUp = (Text(header, "ROWORDER") ?? Text(primary, "ROWORDER"))?.Trim().ToUpperInvariant() == "BOTTOM-UP",
+ };
+ }
+
+ /// <summary>
+ /// One row of big-endian stored values as physical values (BZERO + BSCALE × stored); BLANK integers become NaN.
+ /// Returns true if there was one.
+ /// </summary>
+ private static bool Decode(ReadOnlySpan<byte> row, Span<float> values, int bitpix, double bzero, double bscale, long? blank)
+ {
+ var blanks = false;
+ var (hasBlank, blankValue) = (blank.HasValue, blank.GetValueOrDefault());
+ float Scaled(long stored)
+ {
+ if (hasBlank && stored == blankValue)
+ {
+ blanks = true;
+ return float.NaN;
+ }
+ return (float)(bzero + bscale * stored);
+ }
+
+ switch (bitpix)
+ {
+ case 8:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = Scaled(row[i]);
+ break;
+ case 16:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = Scaled(BinaryPrimitives.ReadInt16BigEndian(row[(i * 2)..]));
+ break;
+ case 32:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = Scaled(BinaryPrimitives.ReadInt32BigEndian(row[(i * 4)..]));
+ break;
+ case 64:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = Scaled(BinaryPrimitives.ReadInt64BigEndian(row[(i * 8)..]));
+ break;
+ case -32:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = (float)(bzero + bscale * BinaryPrimitives.ReadSingleBigEndian(row[(i * 4)..]));
+ break;
+ default:
+ for (var i = 0; i < values.Length; i++)
+ values[i] = (float)(bzero + bscale * BinaryPrimitives.ReadDoubleBigEndian(row[(i * 8)..]));
+ break;
+ }
+ return blanks;
+ }
+
+ private static int Parity(long value) => (int)(((value % 2) + 2) % 2);
+
+ /// <summary>
+ /// The keyword = value cards of one header, read up to its END card (the stream is left at the first data block).
+ /// The first card of a file is SIMPLE = T; an extension's is XTENSION. Repeated keywords keep their first value.
+ /// </summary>
+ private static Dictionary<string, string> ReadHeader(Stream stream, bool primary)
+ {
+ var cards = new Dictionary<string, string>(StringComparer.Ordinal);
+ var block = new byte[BlockSize];
+ for (var b = 0; b < MaxHeaderBlocks; b++)
+ {
+ if (stream.ReadAtLeast(block, BlockSize, throwOnEndOfStream: false) < BlockSize)
+ throw new InvalidDataException(b == 0 && primary ? "This is not a FITS file." : "This FITS file is cut short.");
+ for (var c = 0; c < BlockSize / CardSize; c++)
+ {
+ var card = Encoding.ASCII.GetString(block, c * CardSize, CardSize);
+ var keyword = card[..8].TrimEnd();
+ if (b == 0 && c == 0 && keyword != (primary ? "SIMPLE" : "XTENSION"))
+ throw new InvalidDataException(primary ? "This is not a FITS file." : "This FITS file is damaged (an extension without XTENSION).");
+ if (keyword == "END")
+ return cards;
+ if (keyword.Length > 0 && card[8] == '=' && card[9] == ' ' && !cards.ContainsKey(keyword))
+ cards[keyword] = Value(card[10..]);
+ }
+ }
+ throw new InvalidDataException("This FITS file is damaged (its header has no END).");
+ }
+
+ /// <summary>A card's value: a string between quotes ('' is a quote), else the text before the comment.</summary>
+ private static string Value(string field)
+ {
+ var text = field.TrimStart();
+ if (!text.StartsWith('\''))
+ {
+ var slash = text.IndexOf('/');
+ return (slash < 0 ? text : text[..slash]).Trim();
+ }
+ var value = new StringBuilder();
+ for (var i = 1; i < text.Length; i++)
+ {
+ if (text[i] == '\'')
+ {
+ if (i + 1 < text.Length && text[i + 1] == '\'')
+ {
+ value.Append('\'');
+ i++;
+ continue;
+ }
+ break;
+ }
+ value.Append(text[i]);
+ }
+ // Trailing spaces of a string are not significant; leading ones are.
+ return value.ToString().TrimEnd();
+ }
+
+ private static string? Text(Dictionary<string, string> header, string keyword) => header.GetValueOrDefault(keyword);
+
+ private static double? Number(Dictionary<string, string> header, string keyword) =>
+ header.TryGetValue(keyword, out var text)
+ && double.TryParse(text.Replace('D', 'E').Replace('d', 'e'), NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
+ && double.IsFinite(value)
+ ? value
+ : null;
+
+ private static long Integer(Dictionary<string, string> header, string keyword) =>
+ Number(header, keyword) is { } value && value == Math.Floor(value) && Math.Abs(value) < 9e15
+ ? (long)value
+ : throw new InvalidDataException($"This FITS file is damaged (no valid {keyword}).");
+
+ private static long Optional(Dictionary<string, string> header, string keyword, long fallback) =>
+ Number(header, keyword) is { } value && value == Math.Floor(value) && Math.Abs(value) < 9e15 ? (long)value : fallback;
+
+ private static double Real(Dictionary<string, string> header, string keyword, double fallback) =>
+ Number(header, keyword) ?? fallback;
+}
diff --git a/src/Filee.Engines/Magick/FitsRendering.cs b/src/Filee.Engines/Magick/FitsRendering.cs
new file mode 100644
index 00000000..498bd1ca
--- /dev/null
+++ b/src/Filee.Engines/Magick/FitsRendering.cs
@@ -0,0 +1,272 @@
+// What a FITS picture (Magick/Fits.cs) becomes: a picture for the eye or the data for further processing.
+//
+// - PNG, JPG and every other picture: stretched automatically, the way capture programs show a preview. The values are
+// scaled to 0–1 over their range; per channel, the shadows are clipped 2.8 normalized MADs (median absolute deviation
+// × 1.4826) below the median, and a midtones transfer function takes the median to 0.2 of the output. A raw frame of
+// a colour camera is debayered first (bilinear, from the BAYERPAT pattern and XBAYROFF / YBAYROFF), unless the preset
+// keeps it mono; its channels are stretched one by one, so the sky comes out neutral.
+// - TIFF (Filee's own writer, as ImageMagick's Q8 build stores 8 bits): the data as it is, or stretched, at the file's
+// own depth. 8- and 16-bit data stay so (BZERO / BSCALE applied: unsigned 16-bit is written as unsigned 16-bit),
+// 32-bit integer and floating-point data become 32-bit floating point. Never debayered: the mosaic stays for the
+// program that processes it.
+// Files that say ROWORDER = 'BOTTOM-UP' are turned upright; others are taken as stored top-down, as capture programs
+// write them.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+
+namespace Filee.Engines.Magick;
+
+/// <summary>Stretches, debayers and writes FITS pictures.</summary>
+internal static class FitsRendering
+{
+ /// <summary>Where the median (the sky background) lands after stretching.</summary>
+ public const double TargetBackground = 0.2;
+
+ /// <summary>Shadows are clipped this many normalized MADs from the median.</summary>
+ public const double ShadowClipping = -2.8;
+
+ private const int HistogramBins = 65536;
+
+ /// <summary>The picture for ImageMagick: stretched, debayered if asked, 8 bits per channel, upright.</summary>
+ public static MagickImage ToMagick(FitsImage image, bool debayer, CancellationToken cancellationToken = default)
+ {
+ var planes = Stretch(image, debayer, cancellationToken);
+ if (image.BottomUp)
+ planes = [.. planes.Select(p => FlipVertically(p, image.Width, image.Height))];
+ var pixels = image.Width * image.Height;
+ var rgb = new byte[pixels * 3];
+ ForChunks(pixels, (start, end) =>
+ {
+ for (var i = start; i < end; i++)
+ {
+ for (var c = 0; c < 3; c++)
+ rgb[i * 3 + c] = (byte)(planes[planes.Length == 3 ? c : 0][i] * 255 + 0.5f);
+ }
+ });
+ var result = new MagickImage();
+ result.ReadPixels(rgb, new PixelReadSettings((uint)image.Width, (uint)image.Height, StorageType.Char, PixelMapping.RGB));
+ if (planes.Length == 1)
+ result.ColorType = ColorType.Grayscale;
+ return result;
+ }
+
+ /// <summary>
+ /// FITS → TIFF: the data as it is or stretched (<see cref="ImageOptions.FitsTiff"/>) at the file's own depth, turned
+ /// and mirrored as the preset asks; compressed as the preset asks.
+ /// </summary>
+ public static IReadOnlyList<string> WriteTiff(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var image = Fits.Read(step.InputPath, cancellationToken);
+ progress?.Report(0.3);
+ float[][] planes;
+ TiffSampleKind kind;
+ if (step.Preset.Image.FitsTiff == FitsTiffMode.Stretched)
+ {
+ kind = image.Bitpix switch { 8 => TiffSampleKind.UInt8, 16 => TiffSampleKind.UInt16, _ => TiffSampleKind.Float32 };
+ planes = Stretch(image, debayer: false, cancellationToken);
+ var full = kind switch { TiffSampleKind.UInt8 => 255f, TiffSampleKind.UInt16 => 65535f, _ => 1f };
+ if (full != 1)
+ {
+ foreach (var plane in planes)
+ {
+ for (var i = 0; i < plane.Length; i++)
+ plane[i] *= full;
+ }
+ }
+ }
+ else
+ {
+ kind = LinearKind(image);
+ planes = image.Planes;
+ }
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.6);
+
+ var (width, height) = (image.Width, image.Height);
+ if (image.BottomUp)
+ planes = [.. planes.Select(p => FlipVertically(p, width, height))];
+ var turned = new float[planes.Length][];
+ var (turnedWidth, turnedHeight) = (width, height);
+ for (var p = 0; p < planes.Length; p++)
+ (turned[p], turnedWidth, turnedHeight) = Turn(planes[p], width, height, step.Preset.Image.Rotation, step.Preset.Image.Flip);
+
+ var output = step.Output.Allocate("tiff");
+ if (output is null)
+ return [];
+ TiffWriter.Write(output, turned, turnedWidth, turnedHeight, kind, step.Preset.Image.TiffCompression,
+ step.Preset.Image.Dpi ?? 72, cancellationToken);
+ progress?.Report(1);
+ return [output];
+ }
+
+ /// <summary>
+ /// The TIFF sample type that holds the data as it is: 8-bit data of whole numbers 0–255 stays 8-bit, 16-bit data
+ /// of whole numbers 0–65535 (unsigned 16-bit through BZERO 32768) stays 16-bit, anything else is 32-bit floating
+ /// point so nothing is cut (signed or scaled values, 32-bit integers, floating point).
+ /// </summary>
+ public static TiffSampleKind LinearKind(FitsImage image) => image.Bitpix switch
+ {
+ 8 when image.Integral && image.Min >= 0 && image.Max <= 255 => TiffSampleKind.UInt8,
+ 16 when image.Integral && image.Min >= 0 && image.Max <= 65535 => TiffSampleKind.UInt16,
+ _ => TiffSampleKind.Float32,
+ };
+
+ /// <summary>
+ /// The planes scaled to 0–1 over the picture's range and stretched channel by channel; a colour camera's mosaic is
+ /// debayered first when <paramref name="debayer"/> is set. Rows stay in the stored order.
+ /// </summary>
+ public static float[][] Stretch(FitsImage image, bool debayer, CancellationToken cancellationToken = default)
+ {
+ var (low, high) = (image.Min, image.Max);
+ var scale = high > low ? 1.0 / ((double)high - low) : 0;
+ var planes = new float[image.Planes.Length][];
+ for (var p = 0; p < planes.Length; p++)
+ {
+ var source = image.Planes[p];
+ var plane = planes[p] = new float[source.Length];
+ ForChunks(plane.Length, (start, end) =>
+ {
+ for (var i = start; i < end; i++)
+ plane[i] = float.IsFinite(source[i]) ? (float)Math.Clamp((source[i] - low) * scale, 0, 1) : 0;
+ });
+ }
+ cancellationToken.ThrowIfCancellationRequested();
+ if (debayer && planes.Length == 1 && image.BayerPattern is { } pattern && image.Width >= 2 && image.Height >= 2)
+ planes = Debayer(planes[0], image.Width, image.Height, pattern, image.BayerOffsetX, image.BayerOffsetY);
+ cancellationToken.ThrowIfCancellationRequested();
+ Parallel.ForEach(planes, plane =>
+ {
+ var (shadows, midtones) = StretchParameters(plane);
+ var range = 1 - shadows;
+ ForChunks(plane.Length, (start, end) =>
+ {
+ for (var i = start; i < end; i++)
+ plane[i] = (float)Midtones(midtones, Math.Clamp((plane[i] - shadows) / range, 0, 1));
+ });
+ });
+ return planes;
+ }
+
+ /// <summary>Runs <paramref name="body"/> over 0 … <paramref name="length"/> in chunks, on several cores.</summary>
+ private static void ForChunks(int length, Action<int, int> body)
+ {
+ const int Chunk = 1 << 16;
+ Parallel.For(0, (length + Chunk - 1) / Chunk, c => body(c * Chunk, Math.Min(length, (c + 1) * Chunk)));
+ }
+
+ /// <summary>The shadows clipping point and the midtones balance of one channel's values (0–1).</summary>
+ internal static (double Shadows, double Midtones) StretchParameters(float[] values)
+ {
+ var histogram = new int[HistogramBins];
+ foreach (var value in values)
+ histogram[Bin(value)]++;
+ var median = Median(histogram, values.LongLength);
+ Array.Clear(histogram);
+ foreach (var value in values)
+ histogram[Bin(Math.Abs(value - median))]++;
+ var deviation = 1.4826 * Median(histogram, values.LongLength);
+ var shadows = deviation > 0 ? Math.Clamp(median + ShadowClipping * deviation, 0, 0.99) : 0;
+ var background = (median - shadows) / (1 - shadows);
+ // The balance m with Midtones(m, background) = TargetBackground is Midtones(TargetBackground, background).
+ var midtones = background > 0 ? Midtones(TargetBackground, background) : 0.5;
+ return (shadows, midtones is > 0 and < 1 ? midtones : 0.5);
+ }
+
+ /// <summary>The midtones transfer function: 0 → 0, 1 → 1, <paramref name="balance"/> → 0.5.</summary>
+ internal static double Midtones(double balance, double x) =>
+ x <= 0 ? 0 : x >= 1 ? 1 : (balance - 1) * x / ((2 * balance - 1) * x - balance);
+
+ private static int Bin(double value) => (int)(Math.Clamp(value, 0, 1) * (HistogramBins - 1) + 0.5);
+
+ /// <summary>The median of <paramref name="count"/> values in 0–1 from their histogram (65 536 bins).</summary>
+ private static double Median(int[] histogram, long count)
+ {
+ var half = (count + 1) / 2;
+ long seen = 0;
+ for (var bin = 0; bin < HistogramBins; bin++)
+ {
+ seen += histogram[bin];
+ if (seen >= half)
+ return (double)bin / (HistogramBins - 1);
+ }
+ return 0;
+ }
+
+ /// <summary>
+ /// Bilinear debayering: each pixel keeps its own colour and takes the others from the average of its eight
+ /// neighbours of that colour (two or four of them). <paramref name="pattern"/> is the colour of the stored pixels
+ /// (0, 0), (1, 0), (0, 1) and (1, 1), shifted by the offsets.
+ /// </summary>
+ internal static float[][] Debayer(float[] mosaic, int width, int height, string pattern, int offsetX, int offsetY)
+ {
+ var colours = pattern.Select(c => c switch { 'R' => 0, 'G' => 1, _ => 2 }).ToArray();
+ var planes = new[] { new float[mosaic.Length], new float[mosaic.Length], new float[mosaic.Length] };
+ Parallel.For(0, height, y =>
+ {
+ Span<double> sum = stackalloc double[3];
+ Span<int> count = stackalloc int[3];
+ for (var x = 0; x < width; x++)
+ {
+ sum.Clear();
+ count.Clear();
+ for (var dy = -1; dy <= 1; dy++)
+ {
+ var ny = y + dy;
+ if (ny < 0 || ny >= height)
+ continue;
+ for (var dx = -1; dx <= 1; dx++)
+ {
+ var nx = x + dx;
+ if ((dx == 0 && dy == 0) || nx < 0 || nx >= width)
+ continue;
+ var colour = colours[((ny + offsetY) & 1) * 2 + ((nx + offsetX) & 1)];
+ sum[colour] += mosaic[ny * width + nx];
+ count[colour]++;
+ }
+ }
+ var index = y * width + x;
+ var own = colours[((y + offsetY) & 1) * 2 + ((x + offsetX) & 1)];
+ for (var c = 0; c < 3; c++)
+ planes[c][index] = c == own ? mosaic[index] : count[c] > 0 ? (float)(sum[c] / count[c]) : 0;
+ }
+ });
+ return planes;
+ }
+
+ private static float[] FlipVertically(float[] plane, int width, int height)
+ {
+ var flipped = new float[plane.Length];
+ for (var y = 0; y < height; y++)
+ Array.Copy(plane, y * width, flipped, (height - 1 - y) * width, width);
+ return flipped;
+ }
+
+ /// <summary>Turns, then mirrors, one plane (what ImageMagick does for the other targets, see ImageEncoder).</summary>
+ internal static (float[] Plane, int Width, int Height) Turn(float[] plane, int width, int height, ImageRotation rotation, ImageFlip flip)
+ {
+ if (rotation == ImageRotation.None && flip == ImageFlip.None)
+ return (plane, width, height);
+ var (w, h) = rotation is ImageRotation.Right90 or ImageRotation.Left90 ? (height, width) : (width, height);
+ var result = new float[plane.Length];
+ for (var y = 0; y < h; y++)
+ {
+ for (var x = 0; x < w; x++)
+ {
+ // The output pixel (x, y) after the flip is (fx, fy) after the rotation alone.
+ var fx = flip == ImageFlip.Horizontal ? w - 1 - x : x;
+ var fy = flip == ImageFlip.Vertical ? h - 1 - y : y;
+ var (sx, sy) = rotation switch
+ {
+ ImageRotation.Right90 => (fy, height - 1 - fx),
+ ImageRotation.Left90 => (width - 1 - fy, fx),
+ ImageRotation.Rotate180 => (width - 1 - fx, height - 1 - fy),
+ _ => (fx, fy),
+ };
+ result[y * w + x] = plane[sy * width + sx];
+ }
+ }
+ return (result, w, h);
+ }
+}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index e4192445..2ee7fe8b 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -11,16 +11,17 @@ internal static class ImageEncoder
{
/// <summary>
/// Image formats ImageMagick can read (see <see cref="ImageReader"/> for RAW, layered and metafile sources).
- /// Camera RAW is decoded by LibRaw; XCF, HEIC, DICOM, Photo CD, OpenEXR and Radiance HDR are read only. EMF/WMF
+ /// Camera RAW is decoded by LibRaw; XCF, HEIC, DICOM, Photo CD, OpenEXR, Radiance HDR and FITS are read only. EMF/WMF
/// are Windows metafiles, which ImageMagick renders through GDI+ on Windows only (<see cref="Metafiles"/>). APNG is
- /// read and written by Filee's own <see cref="Apng"/> (its frames decoded and encoded by ImageMagick).
+ /// read and written by Filee's own <see cref="Apng"/> (its frames decoded and encoded by ImageMagick); FITS is read
+ /// by Filee's own <see cref="Fits"/> and written to TIFF by <see cref="FitsRendering"/>.
/// </summary>
public static readonly string[] Readable =
[
"png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif", "heic",
"jxl", "jp2", "psd", "psb", "tga", "ppm", "xcf", "raw",
"apng", "mng", "qoi", "dds", "pcx", "cur", "xpm", "xbm", "wbmp", "pam", "pfm", "sgi", "ras", "miff",
- "dcm", "pcd", "exr", "hdr",
+ "dcm", "pcd", "exr", "hdr", "fits",
];
/// <summary>Vector metafiles ImageMagick rasterizes (Windows only: it uses GDI+).</summary>
@@ -50,10 +51,13 @@ internal static class ImageEncoder
/// The edge an image engine offers from a picture in <paramref name="source"/> to <paramref name="target"/>. GIF
/// holds 256 colours, so a still picture costs more there: it reaches video through a full-colour PNG instead
/// (FFmpeg), while animations and multi-page files still go through GIF and keep their frames. Still picture → APNG
- /// costs as much, so photos never reach video as a one-frame animation.
+ /// costs as much, so photos never reach video as a one-frame animation. FITS → TIFF is the data for further
+ /// processing (linear by default, 16 or 32 bits): it costs a little more, so FITS reaches other formats through a
+ /// stretched PNG or JPG instead.
/// </summary>
public static ConversionEdge Edge(string source, string target) =>
- new(source, target, target is "gif" or "apng" && !MultiFrame.Contains(source) && !Animated.Contains(source) ? 12 : 10);
+ new(source, target, target is "gif" or "apng" && !MultiFrame.Contains(source) && !Animated.Contains(source) ? 12
+ : source == "fits" && target == "tiff" ? 11 : 10);
/// <summary>True when frames of <paramref name="sourceFormat"/> are written as one animation in <paramref name="targetFormat"/>.</summary>
public static bool KeepsAnimation(string sourceFormat, string targetFormat) =>
diff --git a/src/Filee.Engines/Magick/ImageReader.cs b/src/Filee.Engines/Magick/ImageReader.cs
index 8d60c350..d88b5185 100644
--- a/src/Filee.Engines/Magick/ImageReader.cs
+++ b/src/Filee.Engines/Magick/ImageReader.cs
@@ -1,8 +1,8 @@
// Reads source images with ImageMagick, handling the formats that need more than "open the file": camera RAW
// (LibRaw settings), layered PSD/PSB/XCF (one flattened picture instead of one file per layer) and Windows
// metafiles (rendered at the preset's DPI), APNG (Filee's own reader composes the frames) and uncompressed DICOM
-// (Filee's own reader, as ImageMagick's Q8 build reads only 8-bit DICOM) and the photo of an iPhone LIVP. Used by every
-// engine that takes a raster image as input.
+// (Filee's own reader, as ImageMagick's Q8 build reads only 8-bit DICOM), FITS (Filee's own reader, stretched and
+// debayered as the preset says) and the photo of an iPhone LIVP. Used by every engine that takes a raster image as input.
using System.Buffers.Binary;
using Filee.Core.Presets;
@@ -29,6 +29,8 @@ internal static class ImageReader
return scan;
if (formatId == "livp")
return ReadLivePhoto(path, preset);
+ if (formatId == "fits")
+ return [FitsRendering.ToMagick(Fits.Read(path), preset.Image.FitsDebayer)];
var images = new MagickImageCollection();
var settings = Settings(formatId, preset);
diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.cs
index ebfe2972..2700afdb 100644
--- a/src/Filee.Engines/Magick/MagickImageConverter.cs
+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs
@@ -9,7 +9,7 @@ namespace Filee.Engines.Magick;
/// <summary>
/// Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, APNG, MNG, QOI,
/// 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 and (on Windows) EMF/WMF.
+/// Photo CD, OpenEXR, Radiance HDR, FITS and (on Windows) EMF/WMF.
/// </summary>
public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransformer
{
@@ -69,6 +69,9 @@ public sealed class MagickImageConverter : IConverter, ITiffMerger, IImageTransf
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
{
+ // FITS → TIFF keeps the file's depth (16 or 32 bits), which the Q8 build can't: Filee writes it.
+ if (step.From == "fits" && step.To == "tiff")
+ return FitsRendering.WriteTiff(step, progress, cancellationToken);
// Animated PNGs are often saved as .png: read them as APNG, so they stay animated as GIF or WebP.
var from = step.From == "png" && Apng.IsAnimated(step.InputPath) ? "apng" : step.From;
using var images = ImageReader.Read(step.InputPath, from, step.Preset);
diff --git a/src/Filee.Engines/Magick/TiffWriter.cs b/src/Filee.Engines/Magick/TiffWriter.cs
new file mode 100644
index 00000000..5e4a2ef9
--- /dev/null
+++ b/src/Filee.Engines/Magick/TiffWriter.cs
@@ -0,0 +1,284 @@
+// A small baseline TIFF writer (TIFF 6.0) for pictures deeper than ImageMagick's Q8 build stores: 8-bit, 16-bit or 32-bit
+// floating-point samples, grey or RGB, little-endian, in strips, uncompressed or with LZW or Deflate (the preset's TIFF
+// compression; integer samples with the horizontal predictor). Used for FITS → TIFF (FitsRendering).
+
+using System.Buffers.Binary;
+using System.IO.Compression;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Magick;
+
+/// <summary>How <see cref="TiffWriter"/> stores a sample.</summary>
+internal enum TiffSampleKind
+{
+ UInt8,
+ UInt16,
+ Float32,
+}
+
+/// <summary>Writes planes of samples as a TIFF.</summary>
+internal static class TiffWriter
+{
+ /// <summary>Uncompressed bytes per strip, about: small enough to compress strip by strip, large enough to be quick.</summary>
+ private const int StripBytes = 256 * 1024;
+
+ private const ushort Short = 3, Long = 4, Rational = 5;
+
+ /// <summary>
+ /// Writes one (grey) or three (RGB) planes of <paramref name="width"/> × <paramref name="height"/> values. Integer
+ /// kinds are rounded and clamped to their range; floating point is written as it is.
+ /// </summary>
+ public static void Write(string path, IReadOnlyList<float[]> planes, int width, int height, TiffSampleKind kind,
+ TiffCompression compression, int dpi, CancellationToken cancellationToken = default)
+ {
+ var samples = planes.Count;
+ var bytesPerSample = kind switch { TiffSampleKind.UInt8 => 1, TiffSampleKind.UInt16 => 2, _ => 4 };
+ var rowBytes = (long)width * samples * bytesPerSample;
+ var rowsPerStrip = (int)Math.Clamp(StripBytes / rowBytes, 1, height);
+ var strips = (height + rowsPerStrip - 1) / rowsPerStrip;
+ // The horizontal predictor (differences along a row) helps integer samples compress; it is not for floats.
+ var predictor = compression != TiffCompression.None && kind != TiffSampleKind.Float32;
+ var offsets = new uint[strips];
+ var counts = new uint[strips];
+
+ using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16);
+ file.Write("II*\0"u8);
+ file.Write(new byte[4]); // the IFD's offset, written at the end
+ var strip = new byte[rowsPerStrip * rowBytes];
+ var lzw = compression == TiffCompression.Lzw ? new LzwEncoder() : null;
+ for (var s = 0; s < strips; s++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var firstRow = s * rowsPerStrip;
+ var rows = Math.Min(rowsPerStrip, height - firstRow);
+ var data = strip.AsSpan(0, (int)(rows * rowBytes));
+ for (var r = 0; r < rows; r++)
+ FillRow(data.Slice((int)(r * rowBytes), (int)rowBytes), planes, (firstRow + r) * width, width, kind, predictor);
+
+ byte[] encoded = compression switch
+ {
+ TiffCompression.Lzw => lzw!.Encode(data),
+ TiffCompression.Zip => Deflate(data),
+ _ => data.ToArray(),
+ };
+ offsets[s] = Offset(file.Position);
+ counts[s] = (uint)encoded.Length;
+ file.Write(encoded);
+ if ((file.Position & 1) != 0)
+ file.WriteByte(0);
+ }
+
+ var bits = (ushort)(bytesPerSample * 8);
+ var format = (ushort)(kind == TiffSampleKind.Float32 ? 3 : 1);
+ var entries = new List<(ushort Tag, ushort Type, uint Count, byte[] Value)>
+ {
+ (256, Long, 1, UInt32s((uint)width)),
+ (257, Long, 1, UInt32s((uint)height)),
+ (258, Short, (uint)samples, UInt16s([.. Enumerable.Repeat(bits, samples)])),
+ (259, Short, 1, UInt16s(compression switch { TiffCompression.Lzw => 5, TiffCompression.Zip => 8, _ => 1 })),
+ (262, Short, 1, UInt16s((ushort)(samples == 3 ? 2 : 1))), // RGB, or grey with 0 = black
+ (273, Long, (uint)strips, UInt32s(offsets)),
+ (277, Short, 1, UInt16s((ushort)samples)),
+ (278, Long, 1, UInt32s((uint)rowsPerStrip)),
+ (279, Long, (uint)strips, UInt32s(counts)),
+ (282, Rational, 1, UInt32s((uint)Math.Max(1, dpi), 1)),
+ (283, Rational, 1, UInt32s((uint)Math.Max(1, dpi), 1)),
+ (284, Short, 1, UInt16s(1)), // samples of a pixel side by side
+ (296, Short, 1, UInt16s(2)), // inches
+ };
+ if (predictor)
+ entries.Add((317, Short, 1, UInt16s(2)));
+ entries.Add((339, Short, (uint)samples, UInt16s([.. Enumerable.Repeat(format, samples)])));
+
+ // The IFD, then the values that don't fit into its entries' four bytes.
+ var ifd = file.Position;
+ var extra = ifd + 2 + entries.Count * 12 + 4;
+ var directory = new MemoryStream();
+ var values = new MemoryStream();
+ Span<byte> number = stackalloc byte[4];
+ BinaryPrimitives.WriteUInt16LittleEndian(number, (ushort)entries.Count);
+ directory.Write(number[..2]);
+ foreach (var (tag, type, count, value) in entries)
+ {
+ BinaryPrimitives.WriteUInt16LittleEndian(number, tag);
+ directory.Write(number[..2]);
+ BinaryPrimitives.WriteUInt16LittleEndian(number, type);
+ directory.Write(number[..2]);
+ BinaryPrimitives.WriteUInt32LittleEndian(number, count);
+ directory.Write(number);
+ if (value.Length <= 4)
+ {
+ directory.Write(value);
+ directory.Write(new byte[4 - value.Length]);
+ continue;
+ }
+ BinaryPrimitives.WriteUInt32LittleEndian(number, Offset(extra + values.Length));
+ directory.Write(number);
+ values.Write(value);
+ if ((values.Length & 1) != 0)
+ values.WriteByte(0);
+ }
+ directory.Write(new byte[4]); // no next IFD
+ directory.WriteTo(file);
+ values.WriteTo(file);
+ Offset(file.Position);
+ file.Position = 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(number, Offset(ifd));
+ file.Write(number);
+ }
+
+ /// <summary>One row of samples, pixel by pixel, little-endian; with the predictor, each sample minus the one before.</summary>
+ private static void FillRow(Span<byte> row, IReadOnlyList<float[]> planes, int start, int width, TiffSampleKind kind, bool predictor)
+ {
+ var samples = planes.Count;
+ switch (kind)
+ {
+ case TiffSampleKind.UInt8:
+ for (var x = 0; x < width; x++)
+ {
+ for (var c = 0; c < samples; c++)
+ row[x * samples + c] = (byte)Math.Clamp(Math.Round(Finite(planes[c][start + x])), 0, 255);
+ }
+ if (predictor)
+ {
+ for (var i = row.Length - 1; i >= samples; i--)
+ row[i] = unchecked((byte)(row[i] - row[i - samples]));
+ }
+ break;
+ case TiffSampleKind.UInt16:
+ Span<ushort> previous = stackalloc ushort[3];
+ for (var x = 0; x < width; x++)
+ {
+ for (var c = 0; c < samples; c++)
+ {
+ var value = (ushort)Math.Clamp(Math.Round(Finite(planes[c][start + x])), 0, 65535);
+ var stored = value;
+ if (predictor)
+ {
+ stored = unchecked((ushort)(value - previous[c]));
+ previous[c] = value;
+ }
+ BinaryPrimitives.WriteUInt16LittleEndian(row[((x * samples + c) * 2)..], stored);
+ }
+ }
+ break;
+ default:
+ for (var x = 0; x < width; x++)
+ {
+ for (var c = 0; c < samples; c++)
+ BinaryPrimitives.WriteSingleLittleEndian(row[((x * samples + c) * 4)..], planes[c][start + x]);
+ }
+ break;
+ }
+ }
+
+ private static double Finite(float value) => float.IsFinite(value) ? value : 0;
+
+ private static byte[] Deflate(ReadOnlySpan<byte> data)
+ {
+ using var output = new MemoryStream();
+ using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true))
+ zlib.Write(data);
+ return output.ToArray();
+ }
+
+ /// <summary>A classic TIFF addresses at most 4 GB.</summary>
+ private static uint Offset(long position) =>
+ position <= uint.MaxValue ? (uint)position : throw new InvalidOperationException("The picture is too large for a TIFF file (over 4 GB).");
+
+ private static byte[] UInt16s(params ushort[] values)
+ {
+ var bytes = new byte[values.Length * 2];
+ for (var i = 0; i < values.Length; i++)
+ BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(i * 2), values[i]);
+ return bytes;
+ }
+
+ private static byte[] UInt32s(params uint[] values)
+ {
+ var bytes = new byte[values.Length * 4];
+ for (var i = 0; i < values.Length; i++)
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(i * 4), values[i]);
+ return bytes;
+ }
+
+ /// <summary>
+ /// TIFF's LZW (TIFF 6.0 section 13): codes of 9 to 12 bits, most significant bit first, starting with a clear code,
+ /// one bit wider as soon as the next code would not fit ("early change"), a clear code when the table is full.
+ /// </summary>
+ private sealed class LzwEncoder
+ {
+ private const int Clear = 256, End = 257, First = 258, Full = 4094;
+
+ // The table: (prefix code << 8 | next byte) → code, valid where its stamp is the current generation.
+ private readonly short[] _codes = new short[1 << 20];
+ private readonly int[] _stamps = new int[1 << 20];
+ private int _generation;
+
+ public byte[] Encode(ReadOnlySpan<byte> data)
+ {
+ var output = new MemoryStream(data.Length / 2 + 16);
+ ulong buffer = 0;
+ var buffered = 0;
+ void Put(int code, int width)
+ {
+ buffer = (buffer << width) | (uint)code;
+ buffered += width;
+ while (buffered >= 8)
+ {
+ buffered -= 8;
+ output.WriteByte((byte)(buffer >> buffered));
+ }
+ }
+
+ var width = 9;
+ var next = First;
+ _generation++;
+ Put(Clear, width);
+ if (data.Length > 0)
+ {
+ int prefix = data[0];
+ for (var i = 1; i < data.Length; i++)
+ {
+ var key = (prefix << 8) | data[i];
+ if (_stamps[key] == _generation)
+ {
+ prefix = _codes[key];
+ continue;
+ }
+ Put(prefix, width);
+ _stamps[key] = _generation;
+ _codes[key] = (short)next++;
+ prefix = data[i];
+ if (next == Full)
+ {
+ Put(Clear, width);
+ _generation++;
+ next = First;
+ width = 9;
+ }
+ else if (next > (1 << width) - 1)
+ {
+ width++;
+ }
+ }
+ Put(prefix, width);
+ // The reader adds a table entry for the last code too, and may widen before the end code.
+ next++;
+ if (next == Full)
+ {
+ Put(Clear, width);
+ width = 9;
+ }
+ else if (next > (1 << width) - 1)
+ {
+ width++;
+ }
+ }
+ Put(End, width);
+ if (buffered > 0)
+ output.WriteByte((byte)(buffer << (8 - buffered)));
+ return output.ToArray();
+ }
+ }
+}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 3501cd99..5337f998 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1198,6 +1198,45 @@ public class RenderTests
Assert.False(preset.Pdf.Ocr);
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ public void Preset_editor_shows_and_saves_the_fits_options(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "tiff", Name = "Astro TIFF" };
+ var vm = new PresetEditorViewModel(preset, loc);
+ // TIFF: linear (the default) or stretched; pictures: debayer (the default) or mono.
+ Assert.True(vm.ShowFitsTiff);
+ Assert.False(vm.ShowFitsDebayer);
+ Assert.Equal(Filee.Core.Presets.FitsTiffMode.Linear, vm.FitsTiffMode.Value);
+ Assert.Equal(loc["presets.fits_tiff.Stretched"], vm.FitsTiffModes[1].Label);
+
+ var window = new PresetEditorWindow { DataContext = vm, Height = 1400 };
+ window.Show();
+ Pump();
+ Save(window, $"preset-fits-tiff-{language}.png");
+ window.Close();
+
+ vm.FitsTiffMode = vm.FitsTiffModes.Single(m => m.Value == Filee.Core.Presets.FitsTiffMode.Stretched);
+ Assert.True(vm.Apply());
+ Assert.Equal(Filee.Core.Presets.FitsTiffMode.Stretched, preset.Image.FitsTiff);
+
+ vm = new PresetEditorViewModel(preset, loc);
+ vm.Target = vm.Targets.Single(t => t.Value == "png");
+ Assert.False(vm.ShowFitsTiff);
+ Assert.True(vm.ShowFitsDebayer);
+ Assert.True(vm.FitsDebayer);
+ vm.FitsDebayer = false;
+ Assert.True(vm.Apply());
+ Assert.False(preset.Image.FitsDebayer);
+
+ // Neither is offered where no picture is written.
+ vm.Target = vm.Targets.Single(t => t.Value == "pdf");
+ Assert.False(vm.ShowFitsTiff || vm.ShowFitsDebayer);
+ }
+
[AvaloniaFact]
public void Preset_editor_hides_and_clears_what_text_recognition_does_not_do()
{
diff --git a/tests/Filee.Core.Tests/FitsFormatTests.cs b/tests/Filee.Core.Tests/FitsFormatTests.cs
new file mode 100644
index 00000000..04d63d40
--- /dev/null
+++ b/tests/Filee.Core.Tests/FitsFormatTests.cs
@@ -0,0 +1,64 @@
+// FITS astronomy pictures (issue #460): .fits and .fts are FITS, ".fit" is left for Garmin's FIT; the images donut
+// learns the extensions in schema 42 without taking them from a donut of the user's.
+
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class FitsFormatTests
+{
+ [Theory]
+ [InlineData("m31.fits")]
+ [InlineData("Light_001.FTS")]
+ public void Fits_extensions_are_read_only_images(string file)
+ {
+ var format = FormatRegistry.Detect(file);
+
+ Assert.Equal("fits", format?.Id);
+ Assert.Equal(FormatCategory.Image, format!.Category);
+ Assert.False(format.Writable);
+ }
+
+ [Fact]
+ public void Fit_is_not_taken_for_fits() =>
+ Assert.NotEqual("fits", FormatRegistry.Detect("ride.fit")?.Id);
+
+ [Fact]
+ public void Fresh_profiles_open_the_images_donut_for_fits() =>
+ Assert.Equal("images", ProfileSelector.Select(BuiltInData.CreateProfiles(), ["a.fits", "b.fts"])?.Id);
+
+ [Fact]
+ public void Version_41_libraries_learn_fits_once_and_keep_a_custom_claim()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.Extensions.RemoveAll(e => e is "fits" or "fts");
+ profiles.Add(new ToolbarProfile { Id = "astro", Extensions = ["fts"] });
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(41, presets, profiles));
+
+ Assert.Contains("fits", images.Extensions);
+ Assert.DoesNotContain("fts", images.Extensions);
+ Assert.Equal("astro", ProfileSelector.Select(profiles, ["light.fts"])?.Id);
+ Assert.False(SettingsMigrations.ApplyToLibrary(41, presets, profiles));
+ }
+
+ [Fact]
+ public void Presets_saved_before_the_options_debayer_and_keep_tiffs_linear()
+ {
+ var old = System.Text.Json.JsonSerializer.Deserialize("""{"TargetFormat":"png","Image":{"Quality":80}}""",
+ FileeJsonContext.Default.Preset)!;
+ var newer = System.Text.Json.JsonSerializer.Deserialize("""{"TargetFormat":"tiff","Image":{"FitsTiff":"Sharpened"}}""",
+ FileeJsonContext.Default.Preset)!;
+
+ Assert.True(old.Image.FitsDebayer);
+ Assert.Equal(FitsTiffMode.Linear, old.Image.FitsTiff);
+ Assert.Equal(FitsTiffMode.Linear, newer.Image.FitsTiff); // a mode from a newer Filee
+ var stretched = new ImageOptions { FitsTiff = FitsTiffMode.Stretched, FitsDebayer = false }.Clone();
+ Assert.Equal((FitsTiffMode.Stretched, false), (stretched.FitsTiff, stretched.FitsDebayer));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/FitsTests.cs b/tests/Filee.Engines.Tests/FitsTests.cs
new file mode 100644
index 00000000..82e30e06
--- /dev/null
+++ b/tests/Filee.Engines.Tests/FitsTests.cs
@@ -0,0 +1,521 @@
+// FITS: Filee's reader (Magick/Fits.cs), the stretch and debayering for pictures (FitsRendering) and the TIFF of the
+// file's own depth (TiffWriter). The files are written in the tests (FitsBuilder), card by card as capture programs do.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Magick;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+public class FitsTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private string Save(byte[] fits, string name = "light.fits")
+ {
+ var path = Path.Combine(fx.NewFolder(), name);
+ File.WriteAllBytes(path, fits);
+ return path;
+ }
+
+ private static void AssertDone(ConversionJob job) =>
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+
+ private async Task<string> ConvertAsync(string source, string target, Action<ImageOptions>? options = null)
+ {
+ var preset = new Preset { TargetFormat = target };
+ options?.Invoke(preset.Image);
+ var job = await fx.ConvertAsync([source], preset);
+ AssertDone(job);
+ return job.Outputs.Single();
+ }
+
+ /// <summary>A sky of about <paramref name="sky"/> with a little noise, the same for every seed.</summary>
+ private static double[] Sky(int width, int height, double sky, double noise, int seed = 1)
+ {
+ var random = new Random(seed);
+ return [.. Enumerable.Range(0, width * height).Select(_ => sky + (random.NextDouble() - 0.5) * 2 * noise)];
+ }
+
+ private static IPixel<byte> Pixel(IMagickImage<byte> image, int x, int y) => image.GetPixels().GetPixel(x, y);
+
+ [Fact]
+ public async Task Unsigned_16_bit_data_stays_16_bit_and_exact_in_a_linear_tiff()
+ {
+ // Unsigned 16-bit as cameras write it: stored signed, BZERO 32768.
+ var values = Enumerable.Range(0, 64 * 8).Select(i => i * 128.0 + (i % 7)).ToArray();
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 64, Height = 8, Values = values, Bzero = 32768 }.Build());
+
+ var tiff = await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None);
+
+ var probe = TiffProbe.Read(tiff);
+ Assert.Equal((64, 8, 16, 1, 1), (probe.Width, probe.Height, probe.Bits, probe.SampleFormat, probe.Samples));
+ Assert.Equal(values, probe.Values);
+ Assert.Contains(values, v => v > 32767); // the upper half survives as unsigned
+ }
+
+ [Theory]
+ [InlineData(TiffCompression.Lzw)]
+ [InlineData(TiffCompression.Zip)]
+ public async Task Compressed_16_bit_tiffs_read_back_in_other_programs(TiffCompression compression)
+ {
+ var values = Sky(300, 200, 12000, 3000);
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 300, Height = 200, Values = values, Bzero = 32768 }.Build());
+
+ var tiff = await ConvertAsync(source, "tiff", o => o.TiffCompression = compression);
+
+ // libtiff (in ImageMagick) decodes the strips; the Q8 build keeps the top 8 bits of each sample.
+ using var image = new MagickImage(tiff);
+ Assert.Equal((300u, 200u, 16u), (image.Width, image.Height, image.Depth));
+ for (var i = 0; i < values.Length; i += 997)
+ Assert.InRange(Pixel(image, i % 300, i / 300).GetChannel(0), Math.Round(values[i]) / 257 - 1, Math.Round(values[i]) / 257 + 1);
+ }
+
+ [Fact]
+ public async Task Lzw_strips_full_of_noise_reset_the_table_and_read_back_exactly()
+ {
+ // Random 8-bit data fills the 4096-entry table again and again: every clear code must be where readers expect it.
+ var random = new Random(7);
+ var values = Enumerable.Range(0, 640 * 480).Select(i => i < 640 * 240 ? random.Next(256) : (double)(i / 640 % 3 * 80)).ToArray();
+ var source = Save(new FitsBuilder { Bitpix = 8, Width = 640, Height = 480, Values = values }.Build());
+
+ var tiff = await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.Lzw);
+
+ using var image = new MagickImage(tiff);
+ var pixels = image.GetPixels().ToByteArray(PixelMapping.RGB)!;
+ for (var i = 0; i < values.Length; i++)
+ Assert.Equal((byte)values[i], pixels[i * 3]);
+ Assert.True(new FileInfo(tiff).Length < 640 * 480, "the repeating half compresses");
+ }
+
+ [Fact]
+ public async Task Eight_bit_data_stays_8_bit()
+ {
+ var values = Enumerable.Range(0, 32 * 4).Select(i => (double)(i * 2)).ToArray();
+ var source = Save(new FitsBuilder { Bitpix = 8, Width = 32, Height = 4, Values = values }.Build());
+
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None));
+
+ Assert.Equal((8, 1), (probe.Bits, probe.SampleFormat));
+ Assert.Equal(values, probe.Values);
+ }
+
+ [Theory]
+ [InlineData(32)]
+ [InlineData(-32)]
+ [InlineData(-64)]
+ public async Task Wide_and_floating_point_data_becomes_32_bit_floating_point(int bitpix)
+ {
+ // Values far beyond 16 bits (32-bit integers), or fractions (floating point): neither may be cut.
+ var values = Enumerable.Range(0, 16 * 4).Select(i => bitpix == 32 ? i * 100_000.0 - 50_000 : i * 0.015625 - 0.25).ToArray();
+ var source = Save(new FitsBuilder { Bitpix = bitpix, Width = 16, Height = 4, Values = values }.Build());
+
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None));
+
+ Assert.Equal((32, 3), (probe.Bits, probe.SampleFormat));
+ Assert.Equal(values.Select(v => (double)(float)v), probe.Values);
+ }
+
+ [Fact]
+ public async Task Signed_16_bit_data_with_negative_values_is_not_clipped()
+ {
+ // A calibrated frame without BZERO: negative values don't fit unsigned 16 bits, so the TIFF takes floats.
+ double[] values = [-120, -1, 0, 5, 300, 32000, -32768, 7];
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 8, Height = 1, Values = values }.Build());
+
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None));
+
+ Assert.Equal((32, 3), (probe.Bits, probe.SampleFormat));
+ Assert.Equal(values, probe.Values);
+ }
+
+ [Fact]
+ public async Task A_stretched_tiff_keeps_the_depth_and_lifts_the_sky()
+ {
+ var values = Sky(200, 100, 1000, 40);
+ values[5050] = 60000; // a star
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 200, Height = 100, Values = values, Bzero = 32768 }.Build());
+
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o =>
+ {
+ o.TiffCompression = TiffCompression.None;
+ o.FitsTiff = FitsTiffMode.Stretched;
+ }));
+
+ Assert.Equal((16, 1), (probe.Bits, probe.SampleFormat));
+ var sorted = probe.Values.Order().ToArray();
+ // The sky's median lands at about 0.2 of the range, the star at the top.
+ Assert.InRange(sorted[sorted.Length / 2], 0.17 * 65535, 0.23 * 65535);
+ Assert.Equal(65535, probe.Values[5050]);
+ }
+
+ [Fact]
+ public async Task A_mono_frame_becomes_a_stretched_grey_png()
+ {
+ var values = Sky(120, 80, 2000, 60);
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 120, Height = 80, Values = values, Bzero = 32768 }.Build());
+
+ using var png = new MagickImage(await ConvertAsync(source, "png"));
+
+ Assert.Equal((120u, 80u), (png.Width, png.Height));
+ Assert.Equal(ColorType.Grayscale, png.ColorType);
+ var grey = png.GetPixels().ToByteArray(PixelMapping.RGB)!.Where((_, i) => i % 3 == 0).Order().ToArray();
+ Assert.InRange(grey[grey.Length / 2], 45, 58); // 0.2 × 255 ≈ 51
+ }
+
+ /// <summary>
+ /// A colour camera's mosaic in the RGGB layout: a red nebula left of the middle (its red pixels bright, from an
+ /// eighth to three eighths of the width and the middle third of the height), neutral sky around it.
+ /// </summary>
+ private static double[] RedNebula(int width, int height)
+ {
+ var values = Sky(width, height, 1500, 50, seed: 3);
+ for (var y = height / 3; y < height * 2 / 3; y++)
+ {
+ for (var x = width / 8; x < width * 3 / 8; x++)
+ {
+ if (y % 2 == 0 && x % 2 == 0)
+ values[y * width + x] += 6000;
+ }
+ }
+ return values;
+ }
+
+ [Theory]
+ [InlineData("RGGB", 0, 0, "BAYERPAT", 0)] // red
+ [InlineData("BGGR", 0, 0, "BAYERPAT", 2)] // the same pixels read as blue
+ [InlineData("GRBG", 1, 0, "BAYERPAT", 0)] // shifted by one column: RGGB again
+ [InlineData("GBRG", 0, 1, "BAYERPAT", 0)] // shifted by one row: RGGB again
+ [InlineData("RGGB", 0, 0, "COLORTYP", 0)] // the other keyword
+ public async Task A_colour_camera_frame_is_debayered_with_the_header_pattern(string pattern, int offsetX, int offsetY, string keyword, int bright)
+ {
+ var builder = new FitsBuilder { Bitpix = 16, Width = 80, Height = 60, Values = RedNebula(80, 60), Bzero = 32768 };
+ builder.Cards.Add((keyword, $"'{pattern}'"));
+ if (offsetX != 0)
+ builder.Cards.Add(("XBAYROFF", offsetX.ToString(CultureInfo.InvariantCulture)));
+ if (offsetY != 0)
+ builder.Cards.Add(("YBAYROFF", offsetY.ToString(CultureInfo.InvariantCulture)));
+ var source = Save(builder.Build());
+
+ using var png = new MagickImage(await ConvertAsync(source, "png"));
+
+ var nebula = Pixel(png, 20, 30);
+ var others = Enumerable.Range(0, 3).Where(c => c != bright).Select(c => (int)nebula.GetChannel((uint)c)).ToArray();
+ Assert.True(nebula.GetChannel((uint)bright) > others.Max() + 60, $"nebula {nebula.ToColor()}");
+ // The unlinked stretch leaves the sky neutral.
+ var sky = Pixel(png, 60, 30);
+ Assert.InRange(Math.Abs(sky.GetChannel(0) - sky.GetChannel(1)) + Math.Abs(sky.GetChannel(2) - sky.GetChannel(1)), 0, 40);
+ }
+
+ [Fact]
+ public async Task A_colour_camera_frame_stays_mono_when_the_preset_says_so()
+ {
+ var builder = new FitsBuilder { Bitpix = 16, Width = 80, Height = 60, Values = RedNebula(80, 60), Bzero = 32768 };
+ builder.Cards.Add(("BAYERPAT", "'RGGB'"));
+ var source = Save(builder.Build());
+
+ using var jpg = new MagickImage(await ConvertAsync(source, "jpg", o => o.FitsDebayer = false));
+
+ // The mosaic as it is: the red pixels bright, their neighbours dark, all grey.
+ var rgb = jpg.GetPixels().ToByteArray(PixelMapping.RGB)!;
+ Assert.All(Enumerable.Range(0, rgb.Length / 3), i => Assert.True(rgb[i * 3] == rgb[i * 3 + 1] && rgb[i * 3] == rgb[i * 3 + 2]));
+ Assert.True(Pixel(jpg, 20, 30).GetChannel(0) > Pixel(jpg, 21, 30).GetChannel(0) + 60);
+ }
+
+ [Fact]
+ public async Task A_linear_tiff_of_a_colour_camera_frame_keeps_the_mosaic()
+ {
+ var values = RedNebula(40, 20);
+ var builder = new FitsBuilder { Bitpix = 16, Width = 40, Height = 20, Values = values, Bzero = 32768 };
+ builder.Cards.Add(("BAYERPAT", "'RGGB'"));
+ var source = Save(builder.Build());
+
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None));
+
+ Assert.Equal(1, probe.Samples);
+ Assert.Equal(values.Select(v => Math.Round(v)), probe.Values);
+ }
+
+ [Fact]
+ public async Task Three_planes_are_red_green_and_blue()
+ {
+ const int width = 50, height = 40;
+ var red = Sky(width, height, 800, 30, 1);
+ var green = Sky(width, height, 800, 30, 2);
+ var blue = Sky(width, height, 800, 30, 3);
+ for (var y = 10; y < 30; y++)
+ {
+ for (var x = 5; x < 20; x++)
+ blue[y * width + x] += 5000;
+ }
+ var source = Save(new FitsBuilder
+ {
+ Bitpix = -32,
+ Width = width,
+ Height = height,
+ Planes = 3,
+ Values = [.. red, .. green, .. blue],
+ }.Build());
+
+ using var png = new MagickImage(await ConvertAsync(source, "png"));
+ var probe = TiffProbe.Read(await ConvertAsync(source, "tiff", o => o.TiffCompression = TiffCompression.None));
+
+ var nebula = Pixel(png, 10, 20);
+ Assert.True(nebula.GetChannel(2) > Math.Max(nebula.GetChannel(0), nebula.GetChannel(1)) + 60, $"{nebula.ToColor()}");
+ Assert.Equal((3, 32, 3), (probe.Samples, probe.Bits, probe.SampleFormat));
+ Assert.Equal((float)blue[20 * width + 10], probe.Values[(20 * width + 10) * 3 + 2]);
+ }
+
+ [Fact]
+ public async Task Bottom_up_files_are_turned_upright_and_presets_turn_tiffs()
+ {
+ // A bright first stored row: the bottom of the picture when the file says BOTTOM-UP, the top otherwise.
+ var values = Enumerable.Range(0, 30 * 20).Select(i => i < 30 ? 50000.0 : 1000 + i % 13).ToArray();
+ var bottomUp = new FitsBuilder { Bitpix = 16, Width = 30, Height = 20, Values = values, Bzero = 32768 };
+ bottomUp.Cards.Add(("ROWORDER", "'BOTTOM-UP'"));
+ var topDown = new FitsBuilder { Bitpix = 16, Width = 30, Height = 20, Values = values, Bzero = 32768 };
+ topDown.Cards.Add(("ROWORDER", "'TOP-DOWN'"));
+
+ using (var png = new MagickImage(await ConvertAsync(Save(bottomUp.Build()), "png")))
+ {
+ Assert.Equal(255, Pixel(png, 3, 19).GetChannel(0));
+ Assert.True(Pixel(png, 3, 0).GetChannel(0) < 200);
+ }
+ using (var png = new MagickImage(await ConvertAsync(Save(topDown.Build()), "png")))
+ Assert.Equal(255, Pixel(png, 3, 0).GetChannel(0));
+
+ // Turned right: the top row becomes the right-hand column.
+ var probe = TiffProbe.Read(await ConvertAsync(Save(topDown.Build()), "tiff", o =>
+ {
+ o.TiffCompression = TiffCompression.None;
+ o.Rotation = ImageRotation.Right90;
+ }));
+ Assert.Equal((20, 30), (probe.Width, probe.Height));
+ Assert.All(Enumerable.Range(0, 30), y => Assert.Equal(50000, probe.Values[y * 20 + 19]));
+ Assert.True(probe.Values[0] < 2000);
+ }
+
+ [Fact]
+ public void The_header_is_read_like_the_standard_says()
+ {
+ var builder = new FitsBuilder { Bitpix = 16, Width = 4, Height = 2, Values = [0, 1, 2, 3, 4, 5, 6, 7] };
+ builder.Cards.Add(("BZERO", "3.2768D+04 / unsigned, Fortran exponent"));
+ builder.Cards.Add(("BSCALE", "1.0"));
+ builder.Cards.Add(("BAYERPAT", "'gbrg ' / lower case and padded"));
+ builder.Cards.Add(("OBJECT", "'M 31 ''Andromeda'''"));
+ builder.Cards.Add(("XBAYROFF", "-1"));
+ builder.Cards.Add(("BZERO", "0")); // repeated: the first one counts
+ var path = Save(builder.Build(writeScale: false));
+
+ var image = Fits.Read(path, TestContext.Current.CancellationToken);
+
+ Assert.Equal((4, 2, 16), (image.Width, image.Height, image.Bitpix));
+ Assert.Equal("GBRG", image.BayerPattern);
+ Assert.Equal(1, image.BayerOffsetX);
+ Assert.Equal(32768f, image.Planes[0][0]);
+ Assert.True(image.Integral);
+ }
+
+ [Fact]
+ public async Task A_picture_in_an_image_extension_is_found()
+ {
+ // fpack-free pipelines write an empty primary HDU and the picture in an IMAGE extension.
+ var values = Sky(40, 30, 500, 20);
+ var source = Save(new FitsBuilder { Bitpix = -32, Width = 40, Height = 30, Values = values, InExtension = true }.Build());
+
+ using var png = new MagickImage(await ConvertAsync(source, "png"));
+
+ Assert.Equal((40u, 30u), (png.Width, png.Height));
+ }
+
+ [Fact]
+ public async Task Tile_compressed_and_damaged_files_fail_with_a_reason()
+ {
+ var compressed = Save(new FitsBuilder { CompressedTable = true }.Build(), "packed.fits");
+ var notFits = Save(Encoding.ASCII.GetBytes(new string('x', 3000)), "fake.fts");
+ var cut = new FitsBuilder { Bitpix = 16, Width = 64, Height = 64, Values = Sky(64, 64, 100, 5) }.Build();
+ var truncated = Save(cut[..(2880 + 1000)], "cut.fits");
+
+ Assert.Contains("fpack", Assert.Throws<InvalidDataException>(() => Fits.Read(compressed, TestContext.Current.CancellationToken)).Message);
+ Assert.Contains("not a FITS", Assert.Throws<InvalidDataException>(() => Fits.Read(notFits, TestContext.Current.CancellationToken)).Message);
+ Assert.Throws<EndOfStreamException>(() => Fits.Read(truncated, TestContext.Current.CancellationToken));
+
+ var job = await fx.ConvertAsync([compressed], new Preset { TargetFormat = "png" });
+ Assert.Equal(JobState.Failed, job.State);
+ }
+
+ [Fact]
+ public void The_stretch_takes_the_median_to_the_target_background()
+ {
+ var values = Sky(100, 100, 0.1, 0.01).Select(v => (float)v).ToArray();
+
+ var (shadows, midtones) = FitsRendering.StretchParameters(values);
+
+ var median = values.Order().ElementAt(values.Length / 2);
+ Assert.Equal(FitsRendering.TargetBackground, FitsRendering.Midtones(midtones, (median - shadows) / (1 - shadows)), 2);
+ Assert.Equal(0.5, FitsRendering.Midtones(0.3, 0.3), 6);
+ Assert.Equal((0.0, 1.0), (FitsRendering.Midtones(0.3, 0), FitsRendering.Midtones(0.3, 1)));
+ }
+
+ [Fact]
+ public async Task Fits_reaches_pdf_and_jpg_through_the_stretched_picture()
+ {
+ var source = Save(new FitsBuilder { Bitpix = 16, Width = 64, Height = 48, Values = Sky(64, 48, 3000, 100), Bzero = 32768 }.Build(), "m42.fts");
+
+ var pdf = await ConvertAsync(source, "pdf");
+ var planner = fx.Catalog.CreatePlanner();
+
+ Assert.Equal(".pdf", Path.GetExtension(pdf));
+ Assert.DoesNotContain(planner.Plan("fits", "pdf")!.Steps, s => s.To == "tiff");
+ Assert.Single(planner.Plan("fits", "tiff")!.Steps);
+ }
+}
+
+/// <summary>Writes FITS files: a primary HDU (or an empty one and an IMAGE extension), big-endian data, 2880-byte blocks.</summary>
+internal sealed class FitsBuilder
+{
+ public int Bitpix { get; init; } = 16;
+ public int Width { get; init; } = 1;
+ public int Height { get; init; } = 1;
+ public int Planes { get; init; } = 1;
+
+ /// <summary>Physical values, plane after plane, row after row; stored as (value − BZERO) / BSCALE.</summary>
+ public double[] Values { get; init; } = [0];
+
+ public double Bzero { get; init; }
+ public bool InExtension { get; init; }
+
+ /// <summary>A primary HDU without data and a tile-compressed image (a BINTABLE with ZIMAGE = T), as fpack writes.</summary>
+ public bool CompressedTable { get; init; }
+
+ /// <summary>Extra cards (keyword, value as written after "= ").</summary>
+ public List<(string Keyword, string Value)> Cards { get; } = [];
+
+ public byte[] Build(bool writeScale = true)
+ {
+ var file = new MemoryStream();
+ if (CompressedTable)
+ {
+ WriteHeader(file, [("SIMPLE", "T"), ("BITPIX", "8"), ("NAXIS", "0")]);
+ WriteHeader(file, [("XTENSION", "'BINTABLE'"), ("BITPIX", "8"), ("NAXIS", "2"), ("NAXIS1", "8"), ("NAXIS2", "1"),
+ ("PCOUNT", "0"), ("GCOUNT", "1"), ("TFIELDS", "1"), ("ZIMAGE", "T")]);
+ file.Write(new byte[8]);
+ Pad(file, 8, 0);
+ return file.ToArray();
+ }
+
+ var image = new List<(string, string)>();
+ var axes = new List<(string, string)>
+ {
+ ("BITPIX", Bitpix.ToString(CultureInfo.InvariantCulture)),
+ ("NAXIS", Planes > 1 ? "3" : "2"),
+ ("NAXIS1", Width.ToString(CultureInfo.InvariantCulture)),
+ ("NAXIS2", Height.ToString(CultureInfo.InvariantCulture)),
+ };
+ if (Planes > 1)
+ axes.Add(("NAXIS3", Planes.ToString(CultureInfo.InvariantCulture)));
+ if (InExtension)
+ {
+ WriteHeader(file, [("SIMPLE", "T"), ("BITPIX", "16"), ("NAXIS", "0"), ("EXTEND", "T")]);
+ image.Add(("XTENSION", "'IMAGE '"));
+ image.AddRange(axes);
+ image.Add(("PCOUNT", "0"));
+ image.Add(("GCOUNT", "1"));
+ }
+ else
+ {
+ image.Add(("SIMPLE", "T"));
+ image.AddRange(axes);
+ }
+ if (writeScale && Bzero != 0)
+ {
+ image.Add(("BZERO", Bzero.ToString(CultureInfo.InvariantCulture)));
+ image.Add(("BSCALE", "1"));
+ }
+ image.AddRange(Cards);
+ WriteHeader(file, image);
+
+ var size = Math.Abs(Bitpix) / 8;
+ var bytes = new byte[size];
+ foreach (var value in Values)
+ {
+ var stored = value - Bzero;
+ switch (Bitpix)
+ {
+ case 8: bytes[0] = (byte)stored; break;
+ case 16: BinaryPrimitives.WriteInt16BigEndian(bytes, checked((short)Math.Round(stored))); break;
+ case 32: BinaryPrimitives.WriteInt32BigEndian(bytes, checked((int)Math.Round(stored))); break;
+ case 64: BinaryPrimitives.WriteInt64BigEndian(bytes, (long)Math.Round(stored)); break;
+ case -32: BinaryPrimitives.WriteSingleBigEndian(bytes, (float)stored); break;
+ default: BinaryPrimitives.WriteDoubleBigEndian(bytes, stored); break;
+ }
+ file.Write(bytes);
+ }
+ Pad(file, Values.Length * size, 0);
+ return file.ToArray();
+ }
+
+ private static void WriteHeader(Stream file, IEnumerable<(string Keyword, string Value)> cards)
+ {
+ var text = new StringBuilder();
+ foreach (var (keyword, value) in cards)
+ text.Append($"{keyword,-8}= {value,20}".PadRight(80));
+ text.Append("END".PadRight(80));
+ var bytes = Encoding.ASCII.GetBytes(text.ToString());
+ file.Write(bytes);
+ Pad(file, bytes.Length, (byte)' ');
+ }
+
+ private static void Pad(Stream file, long length, byte fill)
+ {
+ for (var i = length % 2880; i is > 0 and < 2880; i++)
+ file.WriteByte(fill);
+ }
+}
+
+/// <summary>Reads what the tests check of a TIFF: the first IFD's layout and, uncompressed, its samples.</summary>
+internal sealed record TiffProbe(int Width, int Height, int Bits, int SampleFormat, int Samples, double[] Values)
+{
+ public static TiffProbe Read(string path)
+ {
+ var file = File.ReadAllBytes(path);
+ Assert.Equal("II*\0", Encoding.ASCII.GetString(file, 0, 4));
+ var ifd = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4));
+ var count = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(ifd));
+ var tags = new Dictionary<int, uint[]>();
+ for (var e = 0; e < count; e++)
+ {
+ var entry = file.AsSpan(ifd + 2 + e * 12, 12);
+ var (tag, type, n) = (BinaryPrimitives.ReadUInt16LittleEndian(entry), BinaryPrimitives.ReadUInt16LittleEndian(entry[2..]),
+ (int)BinaryPrimitives.ReadUInt32LittleEndian(entry[4..]));
+ var size = type == 3 ? 2 : 4;
+ var at = n * size <= 4 && type != 5 ? entry[8..] : file.AsSpan((int)BinaryPrimitives.ReadUInt32LittleEndian(entry[8..]));
+ var numbers = new uint[type == 5 ? 1 : n];
+ for (var i = 0; i < numbers.Length; i++)
+ numbers[i] = size == 2 ? BinaryPrimitives.ReadUInt16LittleEndian(at[(i * 2)..]) : BinaryPrimitives.ReadUInt32LittleEndian(at[(i * 4)..]);
+ tags[tag] = numbers;
+ }
+ var (width, height, bits, samples) = ((int)tags[256][0], (int)tags[257][0], (int)tags[258][0], (int)tags[277][0]);
+ var format = tags.TryGetValue(339, out var f) ? (int)f[0] : 1;
+ var values = new List<double>();
+ if (tags[259][0] == 1)
+ {
+ for (var s = 0; s < tags[273].Length; s++)
+ {
+ var strip = file.AsSpan((int)tags[273][s], (int)tags[279][s]);
+ for (var i = 0; i < strip.Length; i += bits / 8)
+ {
+ values.Add(bits switch
+ {
+ 8 => strip[i],
+ 16 => BinaryPrimitives.ReadUInt16LittleEndian(strip[i..]),
+ _ => BinaryPrimitives.ReadSingleLittleEndian(strip[i..]),
+ });
+ }
+ }
+ }
+ return new TiffProbe(width, height, bits, format, samples, [.. values]);
+ }
+}