SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies escono da Directory.Packages.props e da ogni progetto, per la regola «niente componenti esterni». Tutto ciò che leggeva, ridimensionava o disegnava immagini con Skia ora usa codice scritto in casa sulla BCL: - ImageResampler: Lanczos3 separabile o media per area, alfa premoltiplicata, luce lineare facoltativa; ImageGray per l'impronta. - Il lettore JPEG decodifica ridotto a 1/2, 1/4, 1/8; le miniature chiedono almeno il doppio del lato lungo, così l'ultimo passo resta a Lanczos e la miniatura resta uguale alla lettura intera. - ImageOrientation applica l'EXIF in un punto solo (miniature, impronte, anteprime, dimensioni mostrate). - ImageConverter cambia formato fra JPEG, PNG e WebP portando EXIF, ICC, XMP e testi, con l'etichetta d'orientamento e i pixel non ruotati; PngEncoder scrive anche i testi (tEXt o iTXt). - Febe.Core.Drawing: rasterizzatore con antialiasing (tracciati, riempimenti, tratti, gradienti) per icona, immagini dimostrative, riquadro neutro dei video, foto del sito di prova e prove. Febe.ico rigenerata. - ThumbnailStore legge anche i BMP a 24 bit, come quelli del decoder video del ramo funzione/decoder-h264. Le impronte salvate restano confrontabili (390 su 393 campioni identiche, le altre a distanza 2, soglia 6): nessun ricalcolo. Un PNG o JPEG troncato ora non ha miniatura né impronta. Documenti, elenco dei componenti della pagina «Informazioni» e decisioni aggiornati; nuove prove per ridimensionamento, orientamento, lettura ridotta, conversione con metadati, testi PNG e rasterizzatore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
271 lines
11 KiB
C#
271 lines
11 KiB
C#
using System.Buffers.Binary;
|
||
using System.Numerics;
|
||
using Febe.Core.Abstractions;
|
||
using Febe.Core.Codecs.Images;
|
||
using Febe.Core.Domain;
|
||
using Febe.Core.Drawing;
|
||
using Febe.Data;
|
||
|
||
namespace Febe.Tests.Support;
|
||
|
||
/// <summary>A temporary folder removed at the end of a test.</summary>
|
||
internal sealed class TempFolder : IDisposable
|
||
{
|
||
public TempFolder(string prefix = "febe")
|
||
{
|
||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove", prefix + "-" + Guid.NewGuid().ToString("N")[..10]);
|
||
Directory.CreateDirectory(Path);
|
||
}
|
||
|
||
public string Path { get; }
|
||
|
||
public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);
|
||
|
||
public void Dispose()
|
||
{
|
||
try
|
||
{
|
||
Directory.Delete(Path, recursive: true);
|
||
}
|
||
catch (IOException)
|
||
{
|
||
}
|
||
catch (UnauthorizedAccessException)
|
||
{
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>A clock moved by hand, in Alberto's zone.</summary>
|
||
internal sealed class ManualClock(DateTimeOffset start, TimeZoneInfo? zone = null) : IClock
|
||
{
|
||
public DateTimeOffset Now { get; set; } = start;
|
||
|
||
public TimeZoneInfo LocalZone { get; } = zone ?? TestZones.Rome;
|
||
|
||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||
{
|
||
Now += time;
|
||
return Task.CompletedTask;
|
||
}
|
||
}
|
||
|
||
internal static class TestZones
|
||
{
|
||
/// <summary>Europe/Rome, or an equivalent custom zone when the system has no time zone data.</summary>
|
||
public static TimeZoneInfo Rome { get; } = LoadRome();
|
||
|
||
private static TimeZoneInfo LoadRome()
|
||
{
|
||
foreach (var id in new[] { "Europe/Rome", "W. Europe Standard Time" })
|
||
{
|
||
try
|
||
{
|
||
return TimeZoneInfo.FindSystemTimeZoneById(id);
|
||
}
|
||
catch (TimeZoneNotFoundException)
|
||
{
|
||
}
|
||
catch (InvalidTimeZoneException)
|
||
{
|
||
}
|
||
}
|
||
|
||
var start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 5, DayOfWeek.Sunday);
|
||
var end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 10, 5, DayOfWeek.Sunday);
|
||
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, TimeSpan.FromHours(1), start, end);
|
||
return TimeZoneInfo.CreateCustomTimeZone("Europe/Rome", TimeSpan.FromHours(1), "Europe/Rome", "CET", "CEST", [rule]);
|
||
}
|
||
}
|
||
|
||
/// <summary>Builders of domain records for tests.</summary>
|
||
internal static class Make
|
||
{
|
||
public static readonly DateTimeOffset T0 = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero);
|
||
|
||
public static Account Account(string username, string? instagramId = null, bool mine = false) =>
|
||
Core.Domain.Account.Create(username, StartingPoint.EverythingAndKeepUpdated, T0, TestZones.Rome, isMine: mine) with
|
||
{
|
||
InstagramId = instagramId ?? ((uint)username.GetHashCode(StringComparison.Ordinal)).ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||
};
|
||
|
||
public static Entry Entry(long accountId, string instagramId, DateTimeOffset publishedAt, EntryKind kind = EntryKind.Post, string? caption = null) => new()
|
||
{
|
||
AccountId = accountId,
|
||
Kind = kind,
|
||
InstagramId = instagramId,
|
||
Code = "C" + instagramId,
|
||
PublishedAt = publishedAt,
|
||
Caption = caption,
|
||
DiscoveredAt = T0,
|
||
};
|
||
|
||
public static Media Photo(int position = 1, MediaState state = MediaState.ToDownload) =>
|
||
new() { Position = position, Kind = MediaKind.Photo, State = state, Width = 1080, Height = 1350 };
|
||
|
||
public static Media Video(int position = 1, MediaState state = MediaState.ToDownload) =>
|
||
new() { Position = position, Kind = MediaKind.Video, State = state, Width = 1080, Height = 1920, Duration = TimeSpan.FromSeconds(15) };
|
||
|
||
public static Media Stored(Media media, string sha, string path) =>
|
||
media with { State = MediaState.Downloaded, Sha256 = sha, RelativePath = path, Bytes = 1000 };
|
||
|
||
public static string Sha(int n) => n.ToString("x64", System.Globalization.CultureInfo.InvariantCulture);
|
||
}
|
||
|
||
/// <summary>Opens test databases.</summary>
|
||
internal static class TestDatabase
|
||
{
|
||
public static Task<FebeDatabase> OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed, drawn and encoded
|
||
/// with Febe's own code (Drawing, Codecs/Images).
|
||
/// </summary>
|
||
internal static class TestImages
|
||
{
|
||
public static RgbaImage Scene(int seed, int width = 1200, int height = 900)
|
||
{
|
||
var random = new Random(seed);
|
||
var image = new RgbaImage(width, height);
|
||
using var canvas = new Canvas(image);
|
||
Color RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256));
|
||
|
||
var angle = random.NextDouble() * Math.PI * 2;
|
||
var dx = (float)Math.Cos(angle) * width / 2;
|
||
var dy = (float)Math.Sin(angle) * height / 2;
|
||
var background = new LinearGradientBrush(
|
||
new Vector2((width / 2f) - dx, (height / 2f) - dy),
|
||
new Vector2((width / 2f) + dx, (height / 2f) + dy),
|
||
[RandomColor(), RandomColor(), RandomColor()]);
|
||
canvas.FillRect(0, 0, width, height, background);
|
||
|
||
var shapes = 10 + random.Next(10);
|
||
for (var i = 0; i < shapes; i++)
|
||
{
|
||
var color = RandomColor().WithAlpha((byte)(160 + random.Next(96)));
|
||
var stroke = random.Next(4) == 0;
|
||
float strokeWidth = 4 + random.Next(30);
|
||
var x = (float)(random.NextDouble() * width);
|
||
var y = (float)(random.NextDouble() * height);
|
||
var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width);
|
||
var h = (float)((0.05 + (random.NextDouble() * 0.4)) * height);
|
||
switch (random.Next(4))
|
||
{
|
||
case 0:
|
||
if (stroke)
|
||
{
|
||
canvas.StrokeRect(x - (w / 2), y - (h / 2), w, h, strokeWidth, color);
|
||
}
|
||
else
|
||
{
|
||
canvas.FillRect(x - (w / 2), y - (h / 2), w, h, color);
|
||
}
|
||
|
||
break;
|
||
case 1:
|
||
if (stroke)
|
||
{
|
||
canvas.StrokeCircle(x, y, Math.Min(w, h) / 2, strokeWidth, color);
|
||
}
|
||
else
|
||
{
|
||
canvas.FillCircle(x, y, Math.Min(w, h) / 2, color);
|
||
}
|
||
|
||
break;
|
||
case 2:
|
||
if (stroke)
|
||
{
|
||
canvas.StrokeEllipse(x, y, w / 2, h / 2, strokeWidth, color);
|
||
}
|
||
else
|
||
{
|
||
canvas.FillEllipse(x, y, w / 2, h / 2, color);
|
||
}
|
||
|
||
break;
|
||
default:
|
||
strokeWidth = 6 + random.Next(20);
|
||
canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), strokeWidth, color);
|
||
break;
|
||
}
|
||
}
|
||
|
||
// Fine grain, as in a photo.
|
||
for (var i = 0; i < width * height / 60; i++)
|
||
{
|
||
var v = (byte)random.Next(256);
|
||
canvas.BlendPixel(random.Next(width), random.Next(height), new Color(v, v, v, 28));
|
||
}
|
||
|
||
return image;
|
||
}
|
||
|
||
public static byte[] Jpeg(RgbaImage image, int quality = 90) => JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality });
|
||
|
||
public static byte[] Png(RgbaImage image) => PngEncoder.Encode(image);
|
||
|
||
public static RgbaImage Resize(RgbaImage source, int width, int height) => ImageResampler.Resize(source, width, height);
|
||
|
||
/// <summary>The pixels of <paramref name="width"/> × <paramref name="height"/> from (<paramref name="left"/>, <paramref name="top"/>).</summary>
|
||
public static RgbaImage Crop(RgbaImage source, int left, int top, int width, int height)
|
||
{
|
||
var result = new RgbaImage(width, height);
|
||
for (var y = 0; y < height; y++)
|
||
{
|
||
source.GetRow(top + y).Slice(left * 4, width * 4).CopyTo(result.GetRow(y));
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>Decodes a JPEG/PNG back to pixels (as stored: the orientation is not applied).</summary>
|
||
public static RgbaImage Decode(byte[] encoded) => ImageDecoder.Decode(encoded);
|
||
|
||
/// <summary>Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6).</summary>
|
||
public static RgbaImage RotateCounterClockwise(RgbaImage source)
|
||
{
|
||
var result = new RgbaImage(source.Height, source.Width);
|
||
for (var y = 0; y < result.Height; y++)
|
||
{
|
||
var row = result.GetRow(y);
|
||
for (var x = 0; x < result.Width; x++)
|
||
{
|
||
// Target (x, y) shows source (w − 1 − y, x).
|
||
var (r, g, b, a) = source.GetPixel(source.Width - 1 - y, x);
|
||
row[x * 4] = r;
|
||
row[(x * 4) + 1] = g;
|
||
row[(x * 4) + 2] = b;
|
||
row[(x * 4) + 3] = a;
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>Inserts an EXIF APP1 segment with the given orientation right after the SOI marker of a JPEG.</summary>
|
||
public static byte[] WithExifOrientation(byte[] jpeg, ushort orientation)
|
||
{
|
||
if (jpeg.Length < 2 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
|
||
{
|
||
throw new ArgumentException("Not a JPEG.", nameof(jpeg));
|
||
}
|
||
|
||
var app1 = new byte[36];
|
||
app1[0] = 0xFF;
|
||
app1[1] = 0xE1;
|
||
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), 34); // length, including these two bytes
|
||
"Exif\0\0"u8.CopyTo(app1.AsSpan(4));
|
||
"MM\0*"u8.CopyTo(app1.AsSpan(10)); // TIFF header, big endian
|
||
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(14), 8); // offset of IFD0
|
||
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(18), 1); // one entry
|
||
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(20), 0x0112); // Orientation
|
||
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(22), 3); // SHORT
|
||
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(24), 1); // count
|
||
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(28), orientation);
|
||
BinaryPrimitives.WriteUInt32BigEndian(app1.AsSpan(32), 0); // no next IFD
|
||
return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)];
|
||
}
|
||
}
|