Dispose images

This commit is contained in:
Marco 2025-07-24 14:33:48 +02:00
commit 55713c340b
3 changed files with 394 additions and 322 deletions

View file

@ -40,7 +40,7 @@ namespace MaddoShared
stopwatch.Start();
// todo immagini counter
//todo set label
await CreaImmaginiParallel(options, results, updateEvent, cancellationToken);
await ProcessImagesParallel(options, results, updateEvent, cancellationToken);
// todo set finito label
stopwatch.Stop();
@ -49,6 +49,107 @@ namespace MaddoShared
$"{stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m ${stopwatch.Elapsed.Seconds}s ({stopwatch.Elapsed.TotalSeconds}s)";
}
public async Task ProcessImagesParallel(
Options options,
ConcurrentBag<string> results,
EventHandler<Tuple<string, int>> updateEvent,
CancellationToken cancellationToken = default)
{
List<FileData> dataToProcess = GetFilesToProcess(options);
int threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads;
Func<FileData, Task> processFile = async fileData =>
{
using var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
await imgCreator.CreaImmagineThread(fileData.File.Name);
results.Add(fileData.File.Name);
try
{
updateEvent?.Invoke(this, new Tuple<string, int>(fileData.File.Name, dataToProcess.Count));
}
catch (Exception e)
{
logger.LogError(e, "Error in reporting update");
throw;
}
// finally
// {
// imgCreator = null;
// }
};
if (options.LinearExecution)
{
foreach (var fileData in dataToProcess)
await processFile(fileData);
}
else
{
var chunks = options.ChunksSize > 0
? SplitList(dataToProcess, options.ChunksSize)
: new List<List<FileData>> { dataToProcess };
foreach (var chunk in chunks)
{
await chunk.ParallelForEachAsync(
processFile,
maxDegreeOfParallelism: threads,
false,
cancellationToken);
chunk.Clear();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: false, compacting: false);
}
}
}
private List<FileData> GetFilesToProcess(Options options)
{
if (options.AggiornaSottodirectory && options.CreaSottocartelle)
{
var helper = new FileHelperSharp();
return helper.GetFilesRecursive(
new DirectoryInfo(options.SourcePath),
new DirectoryInfo(options.DestinationPath),
"*.jpg",
new FileHelperOptions
{
FilesPerFolder = options.FilePerCartella,
Suffix = options.SuffissoCartelle,
CounterSize = options.CifreContatore,
NumerationType = options.NumerazioneType
});
}
var files = Directory.EnumerateFiles(
options.SourcePath,
"*.jpg",
options.AggiornaSottodirectory ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
return files.Select(x =>
{
var fInfo = new FileInfo(x);
var filePath = fInfo.DirectoryName;
var trimmedSourcePath = options.SourcePath.TrimEnd('\\');
var newFilePath = fInfo.FullName.Replace(trimmedSourcePath, "").TrimStart('\\');
newFilePath = Path.Combine(options.DestinationPath, newFilePath);
var destFolderPath = new FileInfo(newFilePath).DirectoryName;
var destFolderInfo = new DirectoryInfo(destFolderPath);
destFolderInfo.EnsureDirectoryExists();
return new FileData(fInfo, new DirectoryInfo(new FileInfo(newFilePath).DirectoryName));
// var destDir = new FileInfo(newFilePath).Directory!;
// destDir.Create(); // Ensure exists
//
// return new FileData(fInfo, destDir);
}).ToList();
}
public async Task CreaImmaginiParallel(Options options, ConcurrentBag<string> results,
EventHandler<Tuple<string, int>> updateEvent,
CancellationToken cancellationToken = default(CancellationToken))

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
@ -19,7 +20,8 @@ using SixLabors.ImageSharp.Metadata.Profiles.Exif;
// Imports System.Threading
public class ImageCreatorSharp
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")]
public class ImageCreatorSharp : IDisposable
{
private bool FotoRuotaADestra = false;
private bool FotoRuotaASinistra = false;
@ -93,9 +95,7 @@ public class ImageCreatorSharp
preparaVariabili();
ExtractExif();
// Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(Path.Combine(SourceDir.FullName, NomeFileChild))
using (Image g = Image.FromFile(WorkFile.FullName))
{
using Image g = Image.FromFile(WorkFile.FullName);
// Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(WorkFile.FullName)
// Imposta testo extra
@ -111,8 +111,7 @@ public class ImageCreatorSharp
prepareThumbnailSize(g);
using (Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height))
{
using Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height);
//Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height);
imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution);
@ -124,10 +123,6 @@ public class ImageCreatorSharp
aggiungiLogo(imgOutputBig);
SalvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat);
}
}
});
// g.Dispose()
@ -497,23 +492,19 @@ public class ImageCreatorSharp
}
else
{
using (Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height))
{
using var imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height);
imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat);
//imgOutputSmall.Dispose();
}
}
}
else
{
using (Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height))
{
using Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height);
imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat);
//imgOutputSmall.Dispose();
}
}
}
}
crFont1?.Dispose();
crFont2?.Dispose();
@ -521,8 +512,7 @@ public class ImageCreatorSharp
private void AggiungiTesto(Image g, Bitmap imgOutputBig)
{
using (var grPhoto = Graphics.FromImage(imgOutputBig))
{
using var grPhoto = Graphics.FromImage(imgOutputBig);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
Font crFont = null/* TODO Change to default(_) if this is not a reference type */;
@ -684,9 +674,6 @@ public class ImageCreatorSharp
}
}
private void aggiungiLogo(Bitmap imgOutputBig)
@ -694,7 +681,7 @@ public class ImageCreatorSharp
// imgOutputBig
if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile))
{
Image ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile);
using var ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile);
Color LogoColoreTrasparente = Color.White;
// Dim bmWatermark As Bitmap
@ -704,8 +691,7 @@ public class ImageCreatorSharp
// bmWatermark.SetResolution(imgOutputBig.HorizontalResolution, imgOutputBig.VerticalResolution)
// * Load this Bitmap into a new Graphic Object
using (Graphics grWatermark = Graphics.FromImage(imgOutputBig))
{
using Graphics grWatermark = Graphics.FromImage(imgOutputBig);
ImageAttributes imageAttributes = new ImageAttributes();
// * The first step replace the background color with one that is transparent (Alpha=0, R=0, G=0, B=0)
@ -795,16 +781,11 @@ public class ImageCreatorSharp
//grWatermark.Dispose();
}
}
}
private void SalvaFoto(Bitmap imgOutputBig, Size thumbSizeBig, string NomeFileBig, string NomeFileSmall, Size thumbSizeSmall, ImageFormat thisFormat)
{
using (var image1Stream = new MemoryStream())
{
using var image1Stream = new MemoryStream();
if (PicSettings.FotoGrandeDimOrigina == false)
{
// attenzione non controlla se è png
@ -820,19 +801,15 @@ public class ImageCreatorSharp
}
//imgOutputBig.Save(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), thisFormat);
image1Stream.Seek(0, SeekOrigin.Begin);
using (var g2 = Image.FromStream(image1Stream))
{
using var g2 = Image.FromStream(image1Stream);
thumbSizeBig = g2.Width > g2.Height ? NewthumbSize(g2.Width, g2.Height, PicSettings.LarghezzaBig, "Larghezza") : NewthumbSize(g2.Width, g2.Height, PicSettings.AltezzaBig, "Altezza");
using (Bitmap imgOutputBig2 = new Bitmap(g2, thumbSizeBig.Width, thumbSizeBig.Height))
{
using Bitmap imgOutputBig2 = new Bitmap(g2, thumbSizeBig.Width, thumbSizeBig.Height);
if (thisFormat.Equals(ImageFormat.Jpeg))
SalvaImmagineCustomQuality(imgOutputBig2, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality);
else
imgOutputBig2.Save(Path.Combine(DestDir.FullName, NomeFileBig), thisFormat);
//imgOutputBig2.Dispose();
}
}
//imgOutputBig.Dispose();
//g2.Dispose();
@ -853,16 +830,14 @@ public class ImageCreatorSharp
{
if (PicSettings.AggiungiScritteMiniature)
{
using (System.Drawing.Image g1 = PicSettings.FotoGrandeDimOrigina ? (Image)imgOutputBig.Clone() : Image.FromStream(image1Stream))
{
using System.Drawing.Image g1 = PicSettings.FotoGrandeDimOrigina ? (Image)imgOutputBig.Clone() : Image.FromStream(image1Stream);
//if (PicSettings.FotoGrandeDimOrigina == false)
// g1 = Image.FromStream(image1Stream);
////g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig));
//else
// g1 = (Image)imgOutputBig.Clone();
//g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, NomeFileBig));
using (Bitmap imgOutputSmall = new Bitmap(g1, thumbSizeSmall.Width, thumbSizeSmall.Height))
{
using Bitmap imgOutputSmall = new Bitmap(g1, thumbSizeSmall.Width, thumbSizeSmall.Height);
if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase))
NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + PicSettings.Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4);
//
@ -872,17 +847,13 @@ public class ImageCreatorSharp
imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat);
//imgOutputSmall.Dispose();
}
//g1.Dispose();
}
}
}
//if (File.Exists(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)))
// File.Delete(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig));
}
}
private void SalvaImmagineCustomQuality(Bitmap imageToSave, string nomeFileFinale, long quality)
@ -926,11 +897,6 @@ public class ImageCreatorSharp
return null/* TODO Change to default(_) if this is not a reference type */;
}
/// <summary>
/// ''' Calculate the Size of the New image
/// ''' </summary>
@ -1014,4 +980,9 @@ public class ImageCreatorSharp
_NomeFileChild = value;
}
}
public void Dispose()
{
}
}

View file

@ -1676,7 +1676,7 @@ namespace ImageCatalog
imageCreationOptions.NumerazioneType = GetNumerazioneEnum();
imageCreationOptions.SourcePath = Model.SourcePath;
imageCreationOptions.DestinationPath = Model.DestinationPath;
await imgStf.CreaImmaginiParallel(imageCreationOptions, _results, UiUpdateEvent);
await imgStf.ProcessImagesParallel(imageCreationOptions, _results, UiUpdateEvent);
// Await CreaImmaginiParallel(txtSorgente.Text, txtDestinazione.Text)