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
? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly);
dataToProcess = 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));
}).ToList();
//// TODO
//dataToProcess =
// (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), //
// new DirectoryInfo(options.DestinationPath.PathCombine( // dataToProcess = files.Select(x =>
// new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "") // {
// ) // var fInfo = new FileInfo(x);
// ) // var filePath = fInfo.DirectoryName;
// ) // var trimmedSourcePath = options.SourcePath.TrimEnd('\\');
// ) // var newFilePath = fInfo.FullName.Replace(trimmedSourcePath, "").TrimStart('\\');
// .ToList(); // newFilePath = Path.Combine(options.DestinationPath, newFilePath);
} //
// var destFolderPath = new FileInfo(newFilePath).DirectoryName;
var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; // var destFolderInfo = new DirectoryInfo(destFolderPath);
var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads) // destFolderInfo.EnsureDirectoryExists();
.ConcurrentScheduler; //
// return new FileData(fInfo, new DirectoryInfo(new FileInfo(newFilePath).DirectoryName));
//var allTasks = new List<Task>(); // }).ToList();
var test = from d in dataToProcess //
select Task.Factory.StartNew(async () => // //// TODO
{ // //dataToProcess =
var imgCreator = new ImageCreatorSharp(d.File, d.Directory); // // (from f in Directory.EnumerateFiles(options.SourcePath, "*.jpg",
await imgCreator.CreaImmagineThread(d.File.Name); // // options.AggiornaSottodirectory
// // ? SearchOption.AllDirectories
//await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name); // // : SearchOption.TopDirectoryOnly)
// // select new FileData(new FileInfo(f),
imgCreator = null; // // new DirectoryInfo(options.DestinationPath.PathCombine(
// // new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "")
//var imgC = new ImageCreatorSharp(d.File, d.Directory); // // )
//imgC.CreaImmagineThread(d.File.Name); // // )
//imgC = null; // // )
}, CancellationToken.None, TaskCreationOptions.None, scheduler); // // )
// // .ToList();
//int count = 0; // }
//
if (options.LinearExecution) // var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads;
{ // var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads)
foreach (var task in test) // .ConcurrentScheduler;
{ //
await task; // //var allTasks = new List<Task>();
} // var test = from d in dataToProcess
} // select Task.Factory.StartNew(async () =>
else // {
{ // var imgCreator = new ImageCreatorSharp(d.File, d.Directory);
if (options.ChunksSize == 0) // await imgCreator.CreaImmagineThread(d.File.Name);
{ //
//var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler}; // //await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name);
await dataToProcess.ParallelForEachAsync(async fileData => //
{ // imgCreator = null;
var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory); //
await imgCreator.CreaImmagineThread(fileData.File.Name); // //var imgC = new ImageCreatorSharp(d.File, d.Directory);
// await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name); // //imgC.CreaImmagineThread(d.File.Name);
results.Add(fileData.File.Name); // //imgC = null;
//count = Interlocked.Increment(ref count); // }, CancellationToken.None, TaskCreationOptions.None, scheduler);
//
try // //int count = 0;
{ //
updateEvent?.Invoke(this, new Tuple<string, int>(fileData.File.Name, dataToProcess.Count)); // if (options.LinearExecution)
} // {
catch (Exception e) // foreach (var task in test)
{ // {
logger.LogError(e, "Error in reporting update"); // await task;
//Console.WriteLine(e); // }
throw; // }
} // else
finally // {
{ // if (options.ChunksSize == 0)
// Disposing of the creator // {
imgCreator = null; // //var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler};
} // await dataToProcess.ParallelForEachAsync(async fileData =>
}, maxDegreeOfParallelism: threads, false, cancellationToken); // {
} // var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
else // await imgCreator.CreaImmagineThread(fileData.File.Name);
{ // // await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name);
var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList(); // results.Add(fileData.File.Name);
// //count = Interlocked.Increment(ref count);
//
foreach (var sdaf in asdf) // try
{ // {
await sdaf.ParallelForEachAsync(async fileData => // updateEvent?.Invoke(this, new Tuple<string, int>(fileData.File.Name, dataToProcess.Count));
{ // }
var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory); // catch (Exception e)
await imgCreator.CreaImmagineThread(fileData.File.Name); // {
// await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread( // logger.LogError(e, "Error in reporting update");
// fileData.File.Name); // //Console.WriteLine(e);
results.Add(fileData.File.Name); // throw;
//count = Interlocked.Increment(ref count); // }
try // finally
{ // {
updateEvent?.Invoke(this, // // Disposing of the creator
new Tuple<string, int>(fileData.File.Name, dataToProcess.Count)); // imgCreator = null;
} // }
catch (Exception e) // }, maxDegreeOfParallelism: threads, false, cancellationToken);
{ // }
logger.LogError("Error in reporting update"); // else
//Console.WriteLine(e); // {
throw; // var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList();
} //
finally //
{ // foreach (var sdaf in asdf)
imgCreator = null; // {
} // await sdaf.ParallelForEachAsync(async fileData =>
}, maxDegreeOfParallelism: threads, false, cancellationToken); // {
} // var imgCreator = new ImageCreatorSharp(fileData.File, fileData.Directory);
} // await imgCreator.CreaImmagineThread(fileData.File.Name);
} // // await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(
} // // fileData.File.Name);
// results.Add(fileData.File.Name);
// //count = Interlocked.Increment(ref count);
// try
// {
// updateEvent?.Invoke(this,
// new Tuple<string, int>(fileData.File.Name, dataToProcess.Count));
// }
// catch (Exception e)
// {
// logger.LogError("Error in reporting update");
// //Console.WriteLine(e);
// throw;
// }
// finally
// {
// imgCreator = null;
// }
// }, 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();
} }
} }