Preload logo

This commit is contained in:
Marco 2025-07-25 10:34:54 +02:00
commit ce347a7095
2 changed files with 184 additions and 167 deletions

View file

@ -2,6 +2,7 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -57,12 +58,23 @@ namespace MaddoShared
{ {
List<FileData> dataToProcess = GetFilesToProcess(options); List<FileData> dataToProcess = GetFilesToProcess(options);
int threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; // int threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads;
int threads = options.MaxThreads;
Bitmap logoBmp = null;
// Load Logo
if (PicSettings.LogoAggiungi & File.Exists(PicSettings.LogoNomeFile))
{
logoBmp = new Bitmap(PicSettings.LogoNomeFile);
}
Func<FileData, Task> processFile = async fileData => Func<FileData, Task> processFile = async fileData =>
{ {
using var logoCopy = logoBmp.Clone(new Rectangle(0, 0, logoBmp.Width, logoBmp.Height),
logoBmp.PixelFormat);
using var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory); using var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
await imgCreator.CreaImmagineThread(fileData.File.Name); await imgCreator.CreaImmagineThread(fileData.File.Name, logoCopy);
results.Add(fileData.File.Name); results.Add(fileData.File.Name);
@ -104,6 +116,16 @@ namespace MaddoShared
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: false, compacting: false); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: false, compacting: false);
} }
} }
try
{
logoBmp?.Dispose();
}
catch (Exception e)
{
logger.LogError(e, "Error in disposing the logo");
}
} }
private List<FileData> GetFilesToProcess(Options options) private List<FileData> GetFilesToProcess(Options options)
@ -150,156 +172,156 @@ namespace MaddoShared
}).ToList(); }).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))
{ // {
var dataToProcess = new List<FileData>(); // var dataToProcess = new List<FileData>();
if (options.AggiornaSottodirectory && options.CreaSottocartelle) // if (options.AggiornaSottodirectory && options.CreaSottocartelle)
{ // {
var helper = new FileHelperSharp(); // var helper = new FileHelperSharp();
dataToProcess = helper.GetFilesRecursive(new DirectoryInfo(options.SourcePath), // dataToProcess = helper.GetFilesRecursive(new DirectoryInfo(options.SourcePath),
new DirectoryInfo(options.DestinationPath), // new DirectoryInfo(options.DestinationPath),
"*.jpg", new FileHelperOptions() // "*.jpg", new FileHelperOptions()
{ // {
FilesPerFolder = options.FilePerCartella, // FilesPerFolder = options.FilePerCartella,
Suffix = options.SuffissoCartelle, // Suffix = options.SuffissoCartelle,
CounterSize = options.CifreContatore, // CounterSize = options.CifreContatore,
NumerationType = options.NumerazioneType // NumerationType = options.NumerazioneType
}); // });
} // }
else if (!options.CreaSottocartelle) // else if (!options.CreaSottocartelle)
{ // {
var files = Directory.EnumerateFiles(options.SourcePath, "*.jpg", // var files = Directory.EnumerateFiles(options.SourcePath, "*.jpg",
options.AggiornaSottodirectory // options.AggiornaSottodirectory
? SearchOption.AllDirectories // ? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly); // : SearchOption.TopDirectoryOnly);
//
dataToProcess = files.Select(x => // dataToProcess = files.Select(x =>
{ // {
var fInfo = new FileInfo(x); // var fInfo = new FileInfo(x);
var filePath = fInfo.DirectoryName; // var filePath = fInfo.DirectoryName;
var trimmedSourcePath = options.SourcePath.TrimEnd('\\'); // var trimmedSourcePath = options.SourcePath.TrimEnd('\\');
var newFilePath = fInfo.FullName.Replace(trimmedSourcePath, "").TrimStart('\\'); // var newFilePath = fInfo.FullName.Replace(trimmedSourcePath, "").TrimStart('\\');
newFilePath = Path.Combine(options.DestinationPath, newFilePath); // newFilePath = Path.Combine(options.DestinationPath, newFilePath);
//
var destFolderPath = new FileInfo(newFilePath).DirectoryName; // var destFolderPath = new FileInfo(newFilePath).DirectoryName;
var destFolderInfo = new DirectoryInfo(destFolderPath); // var destFolderInfo = new DirectoryInfo(destFolderPath);
destFolderInfo.EnsureDirectoryExists(); // destFolderInfo.EnsureDirectoryExists();
//
return new FileData(fInfo, new DirectoryInfo(new FileInfo(newFilePath).DirectoryName)); // return new FileData(fInfo, new DirectoryInfo(new FileInfo(newFilePath).DirectoryName));
}).ToList(); // }).ToList();
//
//// TODO // //// TODO
//dataToProcess = // //dataToProcess =
// (from f in Directory.EnumerateFiles(options.SourcePath, "*.jpg", // // (from f in Directory.EnumerateFiles(options.SourcePath, "*.jpg",
// options.AggiornaSottodirectory // // options.AggiornaSottodirectory
// ? SearchOption.AllDirectories // // ? SearchOption.AllDirectories
// : SearchOption.TopDirectoryOnly) // // : SearchOption.TopDirectoryOnly)
// select new FileData(new FileInfo(f), // // select new FileData(new FileInfo(f),
// new DirectoryInfo(options.DestinationPath.PathCombine( // // new DirectoryInfo(options.DestinationPath.PathCombine(
// new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "") // // new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "")
// ) // // )
// ) // // )
// ) // // )
// ) // // )
// .ToList(); // // .ToList();
} // }
//
var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; // var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads;
var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads) // var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads)
.ConcurrentScheduler; // .ConcurrentScheduler;
//
//var allTasks = new List<Task>(); // //var allTasks = new List<Task>();
var test = from d in dataToProcess // var test = from d in dataToProcess
select Task.Factory.StartNew(async () => // select Task.Factory.StartNew(async () =>
{ // {
var imgCreator = new ImageCreatorSharp(d.File, d.Directory); // var imgCreator = new ImageCreatorSharp(d.File, d.Directory);
await imgCreator.CreaImmagineThread(d.File.Name); // await imgCreator.CreaImmagineThread(d.File.Name);
//
//await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name); // //await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name);
//
imgCreator = null; // imgCreator = null;
//
//var imgC = new ImageCreatorSharp(d.File, d.Directory); // //var imgC = new ImageCreatorSharp(d.File, d.Directory);
//imgC.CreaImmagineThread(d.File.Name); // //imgC.CreaImmagineThread(d.File.Name);
//imgC = null; // //imgC = null;
}, CancellationToken.None, TaskCreationOptions.None, scheduler); // }, CancellationToken.None, TaskCreationOptions.None, scheduler);
//
//int count = 0; // //int count = 0;
//
if (options.LinearExecution) // if (options.LinearExecution)
{ // {
foreach (var task in test) // foreach (var task in test)
{ // {
await task; // await task;
} // }
} // }
else // else
{ // {
if (options.ChunksSize == 0) // if (options.ChunksSize == 0)
{ // {
//var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler}; // //var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler};
await dataToProcess.ParallelForEachAsync(async fileData => // await dataToProcess.ParallelForEachAsync(async fileData =>
{ // {
var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory); // var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
await imgCreator.CreaImmagineThread(fileData.File.Name); // await imgCreator.CreaImmagineThread(fileData.File.Name);
// await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name); // // await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name);
results.Add(fileData.File.Name); // results.Add(fileData.File.Name);
//count = Interlocked.Increment(ref count); // //count = Interlocked.Increment(ref count);
//
try // try
{ // {
updateEvent?.Invoke(this, new Tuple<string, int>(fileData.File.Name, dataToProcess.Count)); // updateEvent?.Invoke(this, new Tuple<string, int>(fileData.File.Name, dataToProcess.Count));
} // }
catch (Exception e) // catch (Exception e)
{ // {
logger.LogError(e, "Error in reporting update"); // logger.LogError(e, "Error in reporting update");
//Console.WriteLine(e); // //Console.WriteLine(e);
throw; // throw;
} // }
finally // finally
{ // {
// Disposing of the creator // // Disposing of the creator
imgCreator = null; // imgCreator = null;
} // }
}, maxDegreeOfParallelism: threads, false, cancellationToken); // }, maxDegreeOfParallelism: threads, false, cancellationToken);
} // }
else // else
{ // {
var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList(); // var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList();
//
//
foreach (var sdaf in asdf) // foreach (var sdaf in asdf)
{ // {
await sdaf.ParallelForEachAsync(async fileData => // await sdaf.ParallelForEachAsync(async fileData =>
{ // {
var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory); // var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
await imgCreator.CreaImmagineThread(fileData.File.Name); // await imgCreator.CreaImmagineThread(fileData.File.Name);
// await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread( // // await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(
// fileData.File.Name); // // fileData.File.Name);
results.Add(fileData.File.Name); // results.Add(fileData.File.Name);
//count = Interlocked.Increment(ref count); // //count = Interlocked.Increment(ref count);
try // try
{ // {
updateEvent?.Invoke(this, // updateEvent?.Invoke(this,
new Tuple<string, int>(fileData.File.Name, dataToProcess.Count)); // new Tuple<string, int>(fileData.File.Name, dataToProcess.Count));
} // }
catch (Exception e) // catch (Exception e)
{ // {
logger.LogError("Error in reporting update"); // logger.LogError("Error in reporting update");
//Console.WriteLine(e); // //Console.WriteLine(e);
throw; // throw;
} // }
finally // finally
{ // {
imgCreator = null; // imgCreator = null;
} // }
}, maxDegreeOfParallelism: threads, false, cancellationToken); // }, maxDegreeOfParallelism: threads, false, cancellationToken);
} // }
} // }
} // }
} // }
public static IEnumerable<List<T>> SplitList<T>(List<T> bigList, int nSize = 3) public static IEnumerable<List<T>> SplitList<T>(List<T> bigList, int nSize = 3)
{ {

View file

@ -85,7 +85,7 @@ public class ImageCreatorSharp : IDisposable
this.DestDir = destination; this.DestDir = destination;
} }
public async Task CreaImmagineThread(string Info) public async Task CreaImmagineThread(string Info, Image logo)
{ {
try try
{ {
@ -120,7 +120,7 @@ public class ImageCreatorSharp : IDisposable
AggiungiTesto(g, imgOutputBig); AggiungiTesto(g, imgOutputBig);
aggiungiLogo(imgOutputBig); aggiungiLogo(imgOutputBig, logo);
SalvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat); SalvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat);
}); });
@ -676,19 +676,14 @@ public class ImageCreatorSharp : IDisposable
private void aggiungiLogo(Bitmap imgOutputBig) private void aggiungiLogo(Bitmap imgOutputBig, Image logo)
{ {
// imgOutputBig // imgOutputBig
if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile)) if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile))
{ {
using var ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile); // using var ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile);
Color LogoColoreTrasparente = Color.White; Color LogoColoreTrasparente = Color.White;
// Dim bmWatermark As Bitmap
// * Create a Bitmap based on the previously modified photograph Bitmap
// bmWatermark = New Bitmap(imgOutputBig)
// 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);
@ -711,13 +706,13 @@ public class ImageCreatorSharp : IDisposable
int FotoLogoH = PicSettings.LogoAltezza; int FotoLogoH = PicSettings.LogoAltezza;
int FotoLogoW = PicSettings.LogoLarghezza; int FotoLogoW = PicSettings.LogoLarghezza;
double FattoreAlt = ImmagineLogo.Height / (double)FotoLogoH; double FattoreAlt = logo.Height / (double)FotoLogoH;
double FattoreLarg = ImmagineLogo.Width / (double)FotoLogoW; double FattoreLarg = logo.Width / (double)FotoLogoW;
Size NuovaSize; Size NuovaSize;
if (FattoreLarg > FattoreAlt) if (FattoreLarg > FattoreAlt)
NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoW, "Larghezza"); NuovaSize = NewthumbSize(logo.Width, logo.Height, FotoLogoW, "Larghezza");
else else
NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoH, "Altezza"); NuovaSize = NewthumbSize(logo.Width, logo.Height, FotoLogoH, "Altezza");
int MargineUsato; int MargineUsato;
int MargineL; int MargineL;
@ -777,7 +772,7 @@ public class ImageCreatorSharp : IDisposable
} }
} }
grWatermark.DrawImage(ImmagineLogo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, ImmagineLogo.Width, ImmagineLogo.Height, GraphicsUnit.Pixel, imageAttributes); grWatermark.DrawImage(logo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, logo.Width, logo.Height, GraphicsUnit.Pixel, imageAttributes);
//grWatermark.Dispose(); //grWatermark.Dispose();
} }
} }