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.

Long images: trim page margins, split when too tall, width resize; images fit the format, version 1.10.1

KnifeLemon9ccf6e19df60
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4f7e03c..ab737544 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,25 @@ version it publishes under "What's Changed" in the GitHub release notes, above t
Add a `## <version>` section before tagging a release. Write what someone using Filee notices: what's new, where to
find it, what it does and doesn't do.
+## 1.10.1
+
+### New
+
+- **Long images: trim and split** (issue #50). Two options under "Stack the pages into one tall image" in the PDF
+ part of a preset:
+ - **Cut the blank space above and below each page.** The pages follow each other without wide white gaps; about
+ 4 mm stays around the content.
+ - **Split into several images when the stack is too tall for the format.** JPG holds up to 65,500 px and WebP
+ 16,383 px. Instead of shrinking the long image to fit, Filee writes several (name_1, name_2, …), split between
+ pages, at full size.
+- **Resize to a width.** "Set the width" next to "Scale by percent" and "Limit the long edge" makes images, and long
+ images, a given number of pixels wide (e.g. 800 or 1200). Smaller images are left as they are.
+
+### Fixed
+
+- Images taller or wider than a format holds (a long PNG → JPG, over 65,500 px) failed with "could not write the
+ file". They are now scaled down to fit (issue #50).
+
## 1.10.0
### New
diff --git a/Directory.Build.props b/Directory.Build.props
index 56123de2..6774ed52 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -14,7 +14,7 @@
parameters of a member is fine (CS1573). -->
<NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>
- <Version>1.10.0</Version>
+ <Version>1.10.1</Version>
<Product>Filee</Product>
<Authors>Filee contributors</Authors>
<Copyright>Copyright (c) Filee contributors</Copyright>
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index b43af1aa..0508e507 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -280,8 +280,10 @@
"presets.resize.None": "Original size",
"presets.resize.Percent": "Scale by percent",
"presets.resize.LongEdge": "Limit the long edge",
+ "presets.resize.Width": "Set the width",
"presets.percent": "Percent",
"presets.long_edge": "Long edge (px)",
+ "presets.width": "Width (px)",
"presets.dpi": "DPI",
"presets.dpi_keep": "Keep",
"presets.keep_metadata": "Keep metadata (EXIF)",
@@ -307,6 +309,9 @@
"presets.split": "One file per page",
"presets.combine_pages_hint": "All pages one under another in a single image, e.g. to post a document in one piece. Very long results are scaled down to what the format stores (JPG 65,500 px, WebP 16,383 px tall).",
"presets.combine_pages": "Stack the pages into one tall image (when a PDF is converted)",
+ "presets.trim_page_margins": "Cut the blank space above and below each page",
+ "presets.split_tall_image": "Too tall for the format: split into several images",
+ "presets.split_tall_image_hint": "JPG holds up to 65,500 px, WebP 16,383 px. Without this the long image is scaled down to fit; with it the pages are split between several files (name_1, name_2, …) at full size.",
"presets.group.document": "Documents",
"presets.pdfa": "PDF/A (archival)",
"presets.target_folder": "Folder (extract archives)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index b1978127..9fb135f1 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -280,8 +280,10 @@
"presets.resize.None": "원본 크기",
"presets.resize.Percent": "비율로 조정",
"presets.resize.LongEdge": "긴 변 제한",
+ "presets.resize.Width": "너비 맞추기",
"presets.percent": "비율 (%)",
"presets.long_edge": "긴 변 (px)",
+ "presets.width": "너비(px)",
"presets.dpi": "DPI",
"presets.dpi_keep": "유지",
"presets.keep_metadata": "메타데이터(EXIF) 유지",
@@ -307,6 +309,9 @@
"presets.split": "페이지마다 파일 하나",
"presets.combine_pages_hint": "여러 페이지를 위아래로 붙여 이미지 한 장으로 만들어요. 문서를 한 번에 올릴 때 좋아요. 너무 길면 형식이 저장할 수 있는 높이에 맞춰 줄여요(JPG 65,500px, WebP 16,383px).",
"presets.combine_pages": "모든 페이지를 세로로 이어 한 장으로 (PDF를 변환할 때)",
+ "presets.trim_page_margins": "페이지마다 위아래 빈 여백 잘라내기",
+ "presets.split_tall_image": "형식이 담을 수 있는 높이를 넘으면 여러 장으로 나누기",
+ "presets.split_tall_image_hint": "JPG는 65,500px, WebP는 16,383px까지 담을 수 있어요. 끄면 긴 이미지를 높이에 맞게 줄이고, 켜면 줄이지 않고 페이지 사이에서 나눠 여러 파일(이름_1, 이름_2, …)로 저장해요.",
"presets.group.document": "문서",
"presets.pdfa": "PDF/A (장기 보존용)",
"presets.target_folder": "폴더 (압축 풀기)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 35b5cabc..f10a1c16 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -280,8 +280,10 @@
"presets.resize.None": "原始大小",
"presets.resize.Percent": "按百分比缩放",
"presets.resize.LongEdge": "限制长边",
+ "presets.resize.Width": "设置宽度",
"presets.percent": "百分比",
"presets.long_edge": "长边 (px)",
+ "presets.width": "宽度(像素)",
"presets.dpi": "DPI",
"presets.dpi_keep": "保持",
"presets.keep_metadata": "保留元数据 (EXIF)",
@@ -307,6 +309,9 @@
"presets.split": "每页一个文件",
"presets.combine_pages_hint": "所有页面上下相接,生成一张图片,适合一次性发布整份文档。过长时会缩小到该格式能保存的高度(JPG 65,500 像素,WebP 16,383 像素)。",
"presets.combine_pages": "把所有页面上下拼成一张长图(转换 PDF 时)",
+ "presets.trim_page_margins": "裁掉每页上下的空白",
+ "presets.split_tall_image": "超过格式能保存的高度时,分成多张图片",
+ "presets.split_tall_image_hint": "JPG 最高 65,500 像素,WebP 最高 16,383 像素。不勾选时长图会缩小到能保存的高度,勾选后保持原尺寸,在页面之间分开,保存成多个文件(名称_1、名称_2……)。",
"presets.group.document": "文档",
"presets.pdfa": "PDF/A(长期存档)",
"presets.target_folder": "文件夹(解压缩)",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index d5789e18..1e61ab63 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -92,6 +92,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_quality = _edit.Image.Quality;
_resizePercent = _edit.Image.ResizePercent;
_longEdge = _edit.Image.LongEdge;
+ _width = _edit.Image.Width;
_setDpi = _edit.Image.Dpi.HasValue;
_dpi = _edit.Image.Dpi ?? 300;
_keepMetadata = _edit.Image.KeepMetadata;
@@ -107,6 +108,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_pageRange = _edit.Pdf.PageRange;
_splitPages = _edit.Pdf.SplitPages;
_combinePages = _edit.Pdf.CombinePages;
+ _trimPageMargins = _edit.Pdf.TrimPageMargins;
+ _splitTallImage = _edit.Pdf.SplitTallImage;
_pdfA = _edit.Document.PdfA;
_subfolderName = _edit.Output.SubfolderName;
_customFolder = _edit.Output.CustomFolder;
@@ -141,7 +144,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote))]
private Choice<string> _target;
- [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge))]
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth))]
private Choice<ResizeMode> _resize;
[ObservableProperty, NotifyPropertyChangedFor(nameof(ShowMargin))]
@@ -155,6 +158,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private int _quality;
[ObservableProperty] private int _resizePercent;
[ObservableProperty] private int _longEdge;
+ [ObservableProperty] private int _width;
[ObservableProperty] private bool _setDpi;
[ObservableProperty] private int _dpi;
[ObservableProperty]
@@ -192,6 +196,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
/// <summary>PDF → image: one tall image of all pages.</summary>
[ObservableProperty] private bool _combinePages;
+ [ObservableProperty] private bool _trimPageMargins;
+ [ObservableProperty] private bool _splitTallImage;
[ObservableProperty] private bool _pdfA;
[ObservableProperty] private string _subfolderName;
[ObservableProperty] private string _customFolder;
@@ -243,6 +249,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowExtractNote => TargetId == FormatRegistry.Folder;
public bool ShowPercent => Resize.Value == ResizeMode.Percent;
public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;
+ public bool ShowWidth => Resize.Value == ResizeMode.Width;
public bool ShowMargin => PageSize.Value != PdfPageSize.FitImage;
public bool ShowSubfolder => Location.Value == OutputLocation.Subfolder;
public bool ShowCustomFolder => Location.Value == OutputLocation.CustomFolder;
@@ -266,6 +273,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
image.Resize = Resize.Value;
image.ResizePercent = Math.Clamp(ResizePercent, 1, 1000);
image.LongEdge = Math.Clamp(LongEdge, 16, 20000);
+ image.Width = Math.Clamp(Width, 16, 20000);
image.Dpi = SetDpi ? Math.Clamp(Dpi, 36, 2400) : null;
image.KeepMetadata = KeepMetadata;
image.KeepColorProfile = KeepColorProfile;
@@ -290,6 +298,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
pdf.PageRange = PageRange.Trim();
pdf.SplitPages = SplitPages;
pdf.CombinePages = CombinePages;
+ pdf.TrimPageMargins = TrimPageMargins;
+ pdf.SplitTallImage = SplitTallImage;
_original.Document.PdfA = PdfA;
var media = _original.Media;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index d71e3516..19447e9c 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -61,6 +61,10 @@
<TextBlock Classes="label" Text="{DynamicResource presets.long_edge}" />
<NumericUpDown Value="{Binding LongEdge}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
</StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowWidth}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.width}" />
+ <NumericUpDown Value="{Binding Width}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
+ </StackPanel>
</Grid>
<Grid ColumnDefinitions="Auto,12,*">
<CheckBox Content="{DynamicResource presets.dpi}" IsChecked="{Binding SetDpi}" />
@@ -155,6 +159,11 @@
<StackPanel Spacing="2" IsVisible="{Binding ShowPdfCombine}">
<CheckBox Content="{DynamicResource presets.combine_pages}" IsChecked="{Binding CombinePages}" />
<TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.combine_pages_hint}" />
+ <StackPanel Spacing="2" Margin="28,6,0,0" IsVisible="{Binding CombinePages}">
+ <CheckBox Content="{DynamicResource presets.trim_page_margins}" IsChecked="{Binding TrimPageMargins}" />
+ <CheckBox Content="{DynamicResource presets.split_tall_image}" IsChecked="{Binding SplitTallImage}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.split_tall_image_hint}" />
+ </StackPanel>
</StackPanel>
<Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowPdfBuild}">
<StackPanel>
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index be82bf7a..497ad947 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -69,6 +69,8 @@ public enum ResizeMode
Percent,
/// <summary>Scale so the longer edge equals <see cref="ImageOptions.LongEdge"/> (never upscales).</summary>
LongEdge,
+ /// <summary>Scale to <see cref="ImageOptions.Width"/> pixels wide, height in proportion (never upscales).</summary>
+ Width,
}
/// <summary>TIFF compression schemes.</summary>
@@ -93,6 +95,9 @@ public sealed class ImageOptions
/// <summary>Target long-edge length in pixels when <see cref="Resize"/> is <see cref="ResizeMode.LongEdge"/>.</summary>
public int LongEdge { get; set; } = 1920;
+ /// <summary>Target width in pixels when <see cref="Resize"/> is <see cref="ResizeMode.Width"/>.</summary>
+ public int Width { get; set; } = 1200;
+
/// <summary>Output DPI written into the file. <c>null</c> keeps the source value.</summary>
public int? Dpi { get; set; }
@@ -165,6 +170,18 @@ public sealed class PdfOptions
/// <summary>For PDF → image: stack the pages into one tall image instead of one image per page.</summary>
public bool CombinePages { get; set; }
+ /// <summary>
+ /// With <see cref="CombinePages"/>: cut the blank space above and below each page's content (a small margin stays),
+ /// so the pages follow each other without wide white gaps.
+ /// </summary>
+ public bool TrimPageMargins { get; set; }
+
+ /// <summary>
+ /// With <see cref="CombinePages"/>: when the stack is taller than the format stores (JPG 65,500 px, WebP 16,383 px),
+ /// write several images split between pages instead of scaling the stack down.
+ /// </summary>
+ public bool SplitTallImage { get; set; }
+
public PdfOptions Clone() => (PdfOptions)MemberwiseClone();
}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index 7142341c..ff29b026 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -125,6 +125,41 @@ internal static class ImageEncoder
return frames;
}
+ /// <summary>
+ /// The longest side a format stores: JPEG 65,535 px (65,500 keeps clear of encoder rounding), WebP 16,383 px,
+ /// AVIF 16,384 px. Other formats take more than any image Filee makes.
+ /// </summary>
+ public static double MaxSide(string targetFormat) => targetFormat switch
+ {
+ "jpg" or "jpeg" => 65_500,
+ "webp" => 16_383,
+ "avif" => 16_384,
+ _ => double.PositiveInfinity,
+ };
+
+ /// <summary>
+ /// Scales an image down until both sides fit <see cref="MaxSide"/>. A 1200 × 74,673 px long image used to fail as
+ /// JPG with "could not write the file" (issue #50).
+ /// </summary>
+ private static void FitFormat(IMagickImage<byte> image, string targetFormat)
+ {
+ var scale = Math.Min(1, MaxSide(targetFormat) / Math.Max(image.Width, image.Height));
+ if (scale < 1)
+ image.Resize((uint)Math.Max(1, Math.Floor(image.Width * scale)), (uint)Math.Max(1, Math.Floor(image.Height * scale)));
+ }
+
+ /// <summary>
+ /// How much <see cref="ApplyOptions"/> resizes a <paramref name="width"/> × <paramref name="height"/> image before
+ /// <see cref="FitFormat"/> (1 when it does not).
+ /// </summary>
+ public static double ResizeScale(double width, double height, ImageOptions options) => options.Resize switch
+ {
+ ResizeMode.Percent when options.ResizePercent > 0 => options.ResizePercent / 100.0,
+ ResizeMode.LongEdge when options.LongEdge > 0 => Math.Min(1, options.LongEdge / Math.Max(width, height)),
+ ResizeMode.Width when options.Width > 0 => Math.Min(1, options.Width / width),
+ _ => 1,
+ };
+
/// <summary>Applies resize / colour / metadata options to one frame.</summary>
public static void ApplyOptions(IMagickImage<byte> image, ImageOptions options, string targetFormat)
{
@@ -139,7 +174,11 @@ internal static class ImageEncoder
// Greater = only shrink images that are larger than the box, never upscale.
image.Resize(new MagickGeometry((uint)options.LongEdge, (uint)options.LongEdge) { Greater = true });
break;
+ case ResizeMode.Width when options.Width > 0 && image.Width > options.Width:
+ image.Resize((uint)options.Width, (uint)Math.Max(1, Math.Round(image.Height * (double)options.Width / image.Width)));
+ break;
}
+ FitFormat(image, targetFormat);
if (options.Grayscale)
image.Grayscale();
diff --git a/src/Filee.Engines/Pdf/PdfiumConverter.cs b/src/Filee.Engines/Pdf/PdfiumConverter.cs
index ade83426..bca97069 100644
--- a/src/Filee.Engines/Pdf/PdfiumConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfiumConverter.cs
@@ -2,6 +2,7 @@
// multi-page TIFF or GIF, or (PdfOptions.CombinePages) the pages stacked into one tall image.
using Filee.Core.Conversion;
+using Filee.Core.Presets;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
using ImageMagick;
@@ -58,6 +59,8 @@ public sealed class PdfiumConverter : IConverter
var frame = ToMagick(bitmap, dpi);
if (stack)
{
+ if (step.Preset.Pdf.TrimPageMargins)
+ TrimVertically(frame, dpi);
collected.Add(frame); // stacked after the loop; the image options apply to the tall image
progress?.Report((double)index / pages.Count * 0.8);
continue;
@@ -85,12 +88,16 @@ public sealed class PdfiumConverter : IConverter
if (stack)
{
- using var tall = Stack(collected, step.To);
- ImageEncoder.ApplyOptions(tall, step.Preset.Image, step.To);
- if (step.Output.Allocate(extension, null) is { } path)
+ var parts = step.Preset.Pdf.SplitTallImage ? Split(collected, step.To, step.Preset.Image) : [collected];
+ for (var part = 0; part < parts.Count; part++)
{
- tall.Write(path, format);
- written.Add(path);
+ using var tall = Stack(parts[part]);
+ ImageEncoder.ApplyOptions(tall, step.Preset.Image, step.To); // also scales it to fit the format
+ if (step.Output.Allocate(extension, parts.Count > 1 ? $"_{part + 1}" : null) is { } path)
+ {
+ tall.Write(path, format);
+ written.Add(path);
+ }
}
}
else if (collected.Count > 0)
@@ -107,15 +114,15 @@ public sealed class PdfiumConverter : IConverter
}, cancellationToken);
/// <summary>
- /// The pages one under another, centred on a white strip as wide as the widest page. Scaled down when the result
- /// would be taller than the format stores (JPEG 65,500 px, WebP 16,383 px) or larger than
- /// <see cref="MaxStackedPixels"/>.
+ /// The pages one under another, centred on a white strip as wide as the widest page. Scaled down when larger than
+ /// <see cref="MaxStackedPixels"/>; <see cref="ImageEncoder.ApplyOptions"/> then fits it to what the format stores
+ /// (JPEG 65,500 px, WebP 16,383 px).
/// </summary>
- internal static IMagickImage<byte> Stack(IReadOnlyList<IMagickImage<byte>> pages, string target)
+ internal static IMagickImage<byte> Stack(IReadOnlyList<IMagickImage<byte>> pages)
{
double width = pages.Max(p => p.Width);
double height = pages.Sum(p => (double)p.Height);
- var scale = Math.Min(1, Math.Min(MaxHeight(target) / height, Math.Sqrt(MaxStackedPixels / (width * height))));
+ var scale = Math.Min(1, Math.Sqrt(MaxStackedPixels / (width * height)));
var stripWidth = (uint)Math.Max(1, Math.Floor(width * scale));
using var strip = new MagickImageCollection();
foreach (var page in pages)
@@ -132,14 +139,63 @@ public sealed class PdfiumConverter : IConverter
return tall;
}
- /// <summary>The tallest image a format stores; PNG, TIFF and the rest take more than a stack ever needs.</summary>
- internal static double MaxHeight(string target) => target switch
+ /// <summary>
+ /// Pages in runs short enough for one image of the format after the preset's resize (issue #50: a 44-page
+ /// certificate at 1200 px wide is 74,673 px tall, more than a JPG holds). Runs break between pages; a single page
+ /// taller than the format is a run of its own and is scaled down.
+ /// </summary>
+ internal static List<IReadOnlyList<IMagickImage<byte>>> Split(IReadOnlyList<IMagickImage<byte>> pages, string target, ImageOptions options)
{
- "jpg" or "jpeg" => 65_500,
- "webp" => 16_383,
- "avif" or "heic" => 16_384,
- _ => 1_000_000,
- };
+ double width = pages.Max(p => p.Width);
+ double height = pages.Sum(p => (double)p.Height);
+ var scale = ImageEncoder.ResizeScale(width, height, options) * Math.Min(1, Math.Sqrt(MaxStackedPixels / (width * height)));
+ var limit = ImageEncoder.MaxSide(target) / scale;
+ var parts = new List<IReadOnlyList<IMagickImage<byte>>>();
+ var run = new List<IMagickImage<byte>>();
+ double runHeight = 0;
+ foreach (var page in pages)
+ {
+ if (run.Count > 0 && runHeight + page.Height > limit)
+ {
+ parts.Add(run);
+ run = [];
+ runHeight = 0;
+ }
+ run.Add(page);
+ runHeight += page.Height;
+ }
+ parts.Add(run);
+ return parts;
+ }
+
+ /// <summary>
+ /// Cuts the blank rows above and below a page's content, keeping about 4 mm so text does not touch the next page.
+ /// A blank page shrinks to that margin.
+ /// </summary>
+ internal static void TrimVertically(IMagickImage<byte> page, int dpi)
+ {
+ var margin = Math.Max(4, dpi / 6);
+ uint top, bottom;
+ using (var probe = page.Clone())
+ {
+ probe.ColorFuzz = new Percentage(8); // scanned pages are not pure white
+ var box = probe.BoundingBox;
+ if (box is null || box.Width == 0 || box.Height == 0 || box.Height >= page.Height)
+ {
+ if (box is not null && box.Height >= page.Height)
+ return;
+ top = 0;
+ bottom = (uint)Math.Min(page.Height, margin * 2);
+ }
+ else
+ {
+ top = (uint)Math.Max(0, box.Y - margin);
+ bottom = (uint)Math.Min(page.Height, box.Y + box.Height + margin);
+ }
+ }
+ page.Crop(new MagickGeometry(0, (int)top, page.Width, bottom - top));
+ page.ResetPage();
+ }
private static MagickImage ToMagick(SKBitmap bitmap, int dpi)
{
diff --git a/tests/Filee.Engines.Tests/ImageAndPdfTests.cs b/tests/Filee.Engines.Tests/ImageAndPdfTests.cs
index a68ced16..f1893c6b 100644
--- a/tests/Filee.Engines.Tests/ImageAndPdfTests.cs
+++ b/tests/Filee.Engines.Tests/ImageAndPdfTests.cs
@@ -244,7 +244,8 @@ public class ImageAndPdfTests(EngineFixture fx) : IClassFixture<EngineFixture>
var pages = Enumerable.Range(0, 40).Select(_ => (IMagickImage<byte>)new MagickImage(MagickColors.SkyBlue, 2480, 3508)).ToList();
try
{
- using var tall = Filee.Engines.Pdf.PdfiumConverter.Stack(pages, target);
+ using var tall = Filee.Engines.Pdf.PdfiumConverter.Stack(pages);
+ Filee.Engines.Magick.ImageEncoder.ApplyOptions(tall, new ImageOptions(), target);
Assert.True(tall.Height <= limit, $"{tall.Height} px");
Assert.True((long)tall.Width * tall.Height <= Filee.Engines.Pdf.PdfiumConverter.MaxStackedPixels);
Assert.InRange(tall.Width / (double)tall.Height, 2480 / (3508.0 * 40) * 0.95, 2480 / (3508.0 * 40) * 1.05); // pages keep their shape
@@ -255,6 +256,91 @@ public class ImageAndPdfTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
}
+ [Fact]
+ public async Task An_image_taller_than_a_jpg_holds_is_scaled_down_instead_of_failing()
+ {
+ // Issue #50: a 1200 × 74,673 px long PNG → JPG failed with "could not write the file".
+ var dir = fx.NewFolder();
+ var png = Path.Combine(dir, "long.png");
+ using (var source = new MagickImage(MagickColors.SkyBlue, 12, 70_000))
+ source.Write(png, MagickFormat.Png);
+
+ var job = await fx.ConvertAsync([png], new Preset { TargetFormat = "jpg" });
+
+ AssertDone(job);
+ using var jpg = new MagickImage(job.Outputs.Single());
+ Assert.InRange(jpg.Height, 60_000u, 65_500u);
+ }
+
+ [Fact]
+ public void Width_resize_shrinks_wide_images_and_leaves_narrow_ones()
+ {
+ var options = new ImageOptions { Resize = ResizeMode.Width, Width = 1200 };
+ using var wide = new MagickImage(MagickColors.White, 3000, 1000);
+ using var narrow = new MagickImage(MagickColors.White, 800, 2000);
+
+ Filee.Engines.Magick.ImageEncoder.ApplyOptions(wide, options, "jpg");
+ Filee.Engines.Magick.ImageEncoder.ApplyOptions(narrow, options, "jpg");
+
+ Assert.Equal((1200u, 400u), (wide.Width, wide.Height));
+ Assert.Equal((800u, 2000u), (narrow.Width, narrow.Height));
+ }
+
+ [Fact]
+ public void A_long_image_splits_between_pages_into_parts_the_format_holds()
+ {
+ // Five 6,000 px pages: a WebP holds 16,383 px, so two pages per part; at half width (Width 50 px) all fit.
+ var pages = Enumerable.Range(0, 5).Select(_ => (IMagickImage<byte>)new MagickImage(MagickColors.White, 100, 6000)).ToList();
+ try
+ {
+ var parts = Filee.Engines.Pdf.PdfiumConverter.Split(pages, "webp", new ImageOptions());
+ Assert.Equal([2, 2, 1], parts.Select(p => p.Count));
+
+ var half = Filee.Engines.Pdf.PdfiumConverter.Split(pages, "webp", new ImageOptions { Resize = ResizeMode.Width, Width = 50 });
+ Assert.Equal([5], half.Select(p => p.Count));
+ Assert.Single(Filee.Engines.Pdf.PdfiumConverter.Split(pages, "png", new ImageOptions()));
+ }
+ finally
+ {
+ pages.ForEach(p => p.Dispose());
+ }
+ }
+
+ [Fact]
+ public void Trimming_keeps_the_content_and_a_small_margin()
+ {
+ using var page = new MagickImage(MagickColors.White, 200, 1000);
+ page.Draw(new ImageMagick.Drawing.Drawables().FillColor(MagickColors.Black).Rectangle(20, 400, 180, 499));
+ using var blank = new MagickImage(MagickColors.White, 200, 1000);
+
+ Filee.Engines.Pdf.PdfiumConverter.TrimVertically(page, 72); // margin 12 px at 72 dpi
+ Filee.Engines.Pdf.PdfiumConverter.TrimVertically(blank, 72);
+
+ Assert.Equal((200u, 124u), (page.Width, page.Height));
+ Assert.Equal(24u, blank.Height);
+ }
+
+ [Fact]
+ public async Task Trimmed_long_image_is_shorter_and_a_split_one_names_its_parts()
+ {
+ var dir = fx.NewFolder();
+ var pdf = (await fx.ConvertAsync([EngineFixture.MakeMultiPageTiff(dir, 3)], new Preset { TargetFormat = "pdf" })).Outputs.Single();
+ var full = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 72, CombinePages = true }, Output = { FileNamePattern = "{name}_full" } });
+ var trimmed = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 72, CombinePages = true, TrimPageMargins = true }, Output = { FileNamePattern = "{name}_trim" } });
+
+ AssertDone(full);
+ AssertDone(trimmed);
+ using var a = new MagickImage(full.Outputs.Single());
+ using var b = new MagickImage(trimmed.Outputs.Single());
+ Assert.Equal(a.Width, b.Width);
+ Assert.True(b.Height <= a.Height, $"{b.Height} > {a.Height}");
+
+ // A split that fits in one part writes one file without a number.
+ var split = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "jpg", Pdf = { RenderDpi = 72, CombinePages = true, SplitTallImage = true }, Output = { FileNamePattern = "{name}_long" } });
+ AssertDone(split);
+ Assert.Equal("pages_long.jpg", Path.GetFileName(split.Outputs.Single()));
+ }
+
[Fact]
public async Task Merge_images_into_one_pdf()
{