Codec di casa al posto di SkiaSharp (C1, passo 5)
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>
This commit is contained in:
1 parent
b4383a6110
commit
d6a6a68496
47 files changed
+3391
-562
No files matched your search
@@ -1,10 +1,11 @@
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it,
|
||||
/// decoding directly at a reduced size to save memory and time.
|
||||
/// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP), applying the
|
||||
/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is
|
||||
/// enough, which saves memory and time.
|
||||
/// </summary>
|
||||
internal static class ImageDecoding
|
||||
{
|
||||
@@ -14,118 +15,110 @@ internal static class ImageDecoding
|
||||
/// </summary>
|
||||
public const long MaxDecodedPixels = 100_000_000;
|
||||
|
||||
/// <summary>Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it).</summary>
|
||||
public const long MaxFileBytes = 512L * 1024 * 1024;
|
||||
|
||||
private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels };
|
||||
|
||||
/// <summary>
|
||||
/// Decodes an image upright, as premultiplied RGBA. When <paramref name="minLongSide"/> is given the codec may
|
||||
/// decode at a lower resolution, but never below that long side (unless the image is smaller).
|
||||
/// Returns null when the content is not a decodable image.
|
||||
/// Decodes an image upright, as straight RGBA. When <paramref name="minLongSide"/> is given the codec may decode
|
||||
/// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the
|
||||
/// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large).
|
||||
/// </summary>
|
||||
public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null)
|
||||
public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
using var data = SKData.Create(stream);
|
||||
if (data is null || data.IsEmpty)
|
||||
return ReadAll(stream) is { } data ? DecodeUpright(data, minLongSide) : null;
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="DecodeUpright(Stream, int?)"/>, from bytes already in memory.</summary>
|
||||
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide = null)
|
||||
{
|
||||
if (data.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var codec = SKCodec.Create(data);
|
||||
if (codec is null)
|
||||
RgbaImage? stored = null;
|
||||
try
|
||||
{
|
||||
ImageInfo info;
|
||||
stored = minLongSide is { } min && min > 0
|
||||
? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true)
|
||||
: ImageDecoder.Decode(data, out info, Limits, pooled: true);
|
||||
var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true);
|
||||
if (!ReferenceEquals(upright, stored))
|
||||
{
|
||||
stored.Dispose();
|
||||
}
|
||||
|
||||
stored = null;
|
||||
return upright;
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var size = ChooseDecodeSize(codec, minLongSide);
|
||||
if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0)
|
||||
finally
|
||||
{
|
||||
return null;
|
||||
stored?.Dispose();
|
||||
}
|
||||
|
||||
var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
|
||||
var decoded = new SKBitmap(info);
|
||||
var result = codec.GetPixels(info, decoded.GetPixels());
|
||||
if (result is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
|
||||
{
|
||||
decoded.Dispose();
|
||||
return null;
|
||||
}
|
||||
|
||||
return Orient(decoded, codec.EncodedOrigin);
|
||||
}
|
||||
|
||||
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
|
||||
public static (int Width, int Height)? ReadSize(Stream stream)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stream);
|
||||
using var codec = SKCodec.Create(stream);
|
||||
if (codec is null)
|
||||
return ReadAll(stream) is { } data ? ReadSize(data) : null;
|
||||
}
|
||||
|
||||
/// <summary>Like <see cref="ReadSize(Stream)"/>, from bytes already in memory.</summary>
|
||||
public static (int Width, int Height)? ReadSize(ReadOnlyMemory<byte> data)
|
||||
{
|
||||
if (data.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var (w, h) = (codec.Info.Width, codec.Info.Height);
|
||||
return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
|
||||
try
|
||||
{
|
||||
var info = ImageDecoder.Identify(data, Limits);
|
||||
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
|
||||
private static byte[]? ReadAll(Stream stream)
|
||||
{
|
||||
var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
|
||||
if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min)
|
||||
if (stream.CanSeek)
|
||||
{
|
||||
return full;
|
||||
}
|
||||
|
||||
var best = full;
|
||||
foreach (var scale in new[] { 0.5f, 0.25f, 0.125f })
|
||||
{
|
||||
var scaled = codec.GetScaledDimensions(scale);
|
||||
if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min)
|
||||
var remaining = stream.Length - stream.Position;
|
||||
if (remaining <= 0 || remaining > MaxFileBytes)
|
||||
{
|
||||
break;
|
||||
return null;
|
||||
}
|
||||
|
||||
best = scaled;
|
||||
var bytes = new byte[remaining];
|
||||
stream.ReadExactly(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool SwapsAxes(SKEncodedOrigin origin) =>
|
||||
origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom;
|
||||
|
||||
private static SKBitmap Orient(SKBitmap source, SKEncodedOrigin origin)
|
||||
{
|
||||
if (origin is SKEncodedOrigin.TopLeft or SKEncodedOrigin.Default)
|
||||
using var copy = new MemoryStream();
|
||||
var buffer = new byte[81920];
|
||||
int read;
|
||||
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
return source;
|
||||
if (copy.Length + read > MaxFileBytes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
copy.Write(buffer, 0, read);
|
||||
}
|
||||
|
||||
float w = source.Width, h = source.Height;
|
||||
var swap = SwapsAxes(origin);
|
||||
var outW = swap ? source.Height : source.Width;
|
||||
var outH = swap ? source.Width : source.Height;
|
||||
|
||||
// Each matrix maps a source pixel (x, y) to its upright position.
|
||||
var matrix = origin switch
|
||||
{
|
||||
SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1),
|
||||
SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1),
|
||||
SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1),
|
||||
SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1),
|
||||
SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1),
|
||||
_ => SKMatrix.Identity,
|
||||
};
|
||||
|
||||
var upright = new SKBitmap(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||||
using (var canvas = new SKCanvas(upright))
|
||||
{
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
canvas.SetMatrix(in matrix);
|
||||
canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
|
||||
}
|
||||
|
||||
source.Dispose();
|
||||
return upright;
|
||||
return copy.Length == 0 ? null : copy.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Numerics;
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
@@ -38,6 +38,9 @@ public static class PerceptualHash
|
||||
private const int Size = 32;
|
||||
private const int Low = 8;
|
||||
|
||||
/// <summary>A JPEG is decoded reduced, but never below this long side.</summary>
|
||||
private const int MinDecodedSide = 256;
|
||||
|
||||
private static readonly double[,] Cosines = BuildCosines();
|
||||
|
||||
/// <summary>Hamming distance between two hashes (0–64).</summary>
|
||||
@@ -50,8 +53,8 @@ public static class PerceptualHash
|
||||
public static ulong? Compute(Stream encodedImage)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(encodedImage);
|
||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
|
||||
return bitmap is null ? null : Compute(bitmap);
|
||||
using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide);
|
||||
return image is null ? null : Compute(image);
|
||||
}
|
||||
|
||||
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
|
||||
@@ -61,17 +64,11 @@ public static class PerceptualHash
|
||||
return Compute(stream);
|
||||
}
|
||||
|
||||
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
|
||||
internal static ulong Compute(SKBitmap bitmap)
|
||||
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
|
||||
internal static ulong Compute(RgbaImage image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bitmap);
|
||||
using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul
|
||||
? null
|
||||
: bitmap.Copy(SKColorType.Rgba8888);
|
||||
var source = rgba ?? bitmap;
|
||||
var grey = Luminance(source);
|
||||
var small = AreaResample(grey, source.Width, source.Height, Size, Size);
|
||||
return HashOf(small);
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
return HashOf(AreaResample(image, Size, Size));
|
||||
}
|
||||
|
||||
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
|
||||
@@ -123,50 +120,37 @@ public static class PerceptualHash
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
|
||||
private static double[] Luminance(SKBitmap bitmap)
|
||||
/// <summary>
|
||||
/// The grey levels (0–255, over white: <see cref="ImageGray.LumaOverWhite"/>) of an image reduced to dw × dh by area
|
||||
/// averaging, one source row at a time (memory: one row and dw × source height values).
|
||||
/// </summary>
|
||||
internal static double[] AreaResample(RgbaImage image, int dw, int dh)
|
||||
{
|
||||
var width = bitmap.Width;
|
||||
var height = bitmap.Height;
|
||||
var result = new double[width * height];
|
||||
var pixels = bitmap.GetPixelSpan();
|
||||
var rowBytes = bitmap.RowBytes;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = pixels.Slice(y * rowBytes, width * 4);
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var r = row[x * 4];
|
||||
var g = row[(x * 4) + 1];
|
||||
var b = row[(x * 4) + 2];
|
||||
var a = row[(x * 4) + 3];
|
||||
var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha)
|
||||
result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
|
||||
internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh)
|
||||
{
|
||||
var horizontal = new double[dw * sh];
|
||||
var sw = image.Width;
|
||||
var sh = image.Height;
|
||||
var xs = Weights(sw, dw);
|
||||
var horizontal = new double[dw * sh];
|
||||
var grey = new double[sw];
|
||||
for (var y = 0; y < sh; y++)
|
||||
{
|
||||
ImageGray.LumaOverWhite(image.GetRow(y), grey);
|
||||
for (var dx = 0; dx < dw; dx++)
|
||||
{
|
||||
double sum = 0;
|
||||
foreach (var (index, weight) in xs[dx])
|
||||
{
|
||||
sum += source[(y * sw) + index] * weight;
|
||||
sum += grey[index] * weight;
|
||||
}
|
||||
|
||||
horizontal[(y * dw) + dx] = sum;
|
||||
}
|
||||
}
|
||||
|
||||
return Vertical(horizontal, sh, dw, dh);
|
||||
}
|
||||
|
||||
private static double[] Vertical(double[] horizontal, int sh, int dw, int dh)
|
||||
{
|
||||
var result = new double[dw * dh];
|
||||
var ys = Weights(sh, dh);
|
||||
for (var dy = 0; dy < dh; dy++)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using SkiaSharp;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Drawing;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
@@ -54,13 +55,14 @@ public sealed class ThumbnailStore
|
||||
return true;
|
||||
}
|
||||
|
||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
|
||||
if (bitmap is null)
|
||||
using var image = DecodeFor(encodedImage, LongSide);
|
||||
if (image is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
WriteJpeg(target, Render(bitmap, LongSide));
|
||||
using var thumbnail = Render(image, LongSide);
|
||||
WriteJpeg(target, thumbnail);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -94,26 +96,20 @@ public sealed class ThumbnailStore
|
||||
}
|
||||
|
||||
const int width = 270, height = LongSide; // 9:16, like stories and reels
|
||||
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||||
var canvas = surface.Canvas;
|
||||
canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4));
|
||||
using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill })
|
||||
using var tile = new RgbaImage(width, height);
|
||||
using (var canvas = new Canvas(tile))
|
||||
{
|
||||
canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
|
||||
}
|
||||
var background = new Color(0xE4, 0xE4, 0xE4);
|
||||
canvas.Clear(background);
|
||||
canvas.FillCircle(width / 2f, height / 2f, 34, new Color(0x9A, 0x9A, 0x9A));
|
||||
|
||||
using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill })
|
||||
{
|
||||
// A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp.
|
||||
var cx = width / 2f + 4;
|
||||
// The play sign: a triangle pointing right, a little right of the centre to look centred.
|
||||
var cx = (width / 2f) + 4;
|
||||
var cy = height / 2f;
|
||||
SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
|
||||
canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
|
||||
canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background);
|
||||
}
|
||||
|
||||
using var image = surface.Snapshot();
|
||||
using var bitmap = SKBitmap.FromImage(image);
|
||||
WriteJpeg(path, bitmap.Copy());
|
||||
WriteJpeg(path, tile);
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -125,67 +121,66 @@ public sealed class ThumbnailStore
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
||||
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
|
||||
using var decoded = DecodeFor(source, longSide);
|
||||
if (decoded is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var small = Render(decoded, longSide);
|
||||
using var pixmap = small.PeekPixels();
|
||||
if (pixmap is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
|
||||
return data?.ToArray();
|
||||
return Jpeg(small);
|
||||
}
|
||||
|
||||
private static SKBitmap Render(SKBitmap source, int longSide)
|
||||
/// <summary>
|
||||
/// Decodes an image upright for a picture of <paramref name="longSide"/> pixels. A JPEG may be shrunk while decoding,
|
||||
/// but only down to twice that size: the last step is left to Lanczos, since the codec's 8 × 8 block averages would
|
||||
/// show at almost 1:1. Null when the content cannot be decoded.
|
||||
/// </summary>
|
||||
internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
|
||||
ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
|
||||
|
||||
/// <summary>
|
||||
/// The image reduced to <paramref name="longSide"/> on its long side (Lanczos, never enlarged) and seen over white,
|
||||
/// since JPEG has no alpha. Always a new pooled image, which the caller disposes.
|
||||
/// </summary>
|
||||
internal static RgbaImage Render(RgbaImage source, int longSide)
|
||||
{
|
||||
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
|
||||
var width = Math.Max(1, (int)Math.Round(source.Width * scale));
|
||||
var height = Math.Max(1, (int)Math.Round(source.Height * scale));
|
||||
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
||||
using var canvas = new SKCanvas(result);
|
||||
canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white
|
||||
using var image = SKImage.FromBitmap(source);
|
||||
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
|
||||
var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, longSide);
|
||||
var result = ImageResampler.Resize(source, width, height, pooled: true);
|
||||
ImageBackground.Flatten(result, Color.White);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void WriteJpeg(string target, SKBitmap bitmap)
|
||||
/// <summary>The JPEG of a thumbnail: quality <see cref="JpegQuality"/>, chroma 4:2:0.</summary>
|
||||
internal static byte[] Jpeg(RgbaImage image) =>
|
||||
JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = JpegQuality, Subsampling = JpegSubsampling.Ratio420 });
|
||||
|
||||
private static void WriteJpeg(string target, RgbaImage image)
|
||||
{
|
||||
using (bitmap)
|
||||
var data = Jpeg(image);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
||||
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
||||
{
|
||||
file.Write(data);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel."))
|
||||
using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality))
|
||||
?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita."))
|
||||
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
||||
{
|
||||
data.SaveTo(file);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
File.Move(temp, target, overwrite: false);
|
||||
}
|
||||
catch (IOException) when (File.Exists(target))
|
||||
{
|
||||
// Created meanwhile by another task: same content.
|
||||
}
|
||||
File.Move(temp, target, overwrite: false);
|
||||
}
|
||||
finally
|
||||
catch (IOException) when (File.Exists(target))
|
||||
{
|
||||
if (File.Exists(temp))
|
||||
{
|
||||
File.Delete(temp);
|
||||
}
|
||||
// Created meanwhile by another task: same content.
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temp))
|
||||
{
|
||||
File.Delete(temp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user