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(); stopwatch.Start();
// todo immagini counter // todo immagini counter
//todo set label //todo set label
await CreaImmaginiParallel(options, results, updateEvent, cancellationToken); await ProcessImagesParallel(options, results, updateEvent, cancellationToken);
// todo set finito label // todo set finito label
stopwatch.Stop(); stopwatch.Stop();
@ -49,6 +49,107 @@ namespace MaddoShared
$"{stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m ${stopwatch.Elapsed.Seconds}s ({stopwatch.Elapsed.TotalSeconds}s)"; $"{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, public async Task CreaImmaginiParallel(Options options, ConcurrentBag<string> results,
EventHandler<Tuple<string, int>> updateEvent, EventHandler<Tuple<string, int>> updateEvent,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))

View file

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

View file

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