diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..99a1b50 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "MaddoLibrary"] + path = MaddoLibrary + url = git@gitlab.com:MaddoTools/MaddoLibrary.git diff --git a/.upgrade-assistant b/.upgrade-assistant new file mode 100644 index 0000000..d7035e5 --- /dev/null +++ b/.upgrade-assistant @@ -0,0 +1 @@ +{"Build":"0.2.212405\u002B8e7b4314944e5328780f06f20721a4d6ef9783bb","CurrentProject":"","EntryPoint":"","IsComplete":true} \ No newline at end of file diff --git a/Catalog.sln b/Catalog.sln index fb8ac9a..237b063 100644 --- a/Catalog.sln +++ b/Catalog.sln @@ -1,9 +1,9 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31005.135 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35312.102 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCatalog 2", "imagecatalog\ImageCatalog 2.csproj", "{3F1E23DB-435E-0590-1EF5-735E898DBA3C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageCatalog 2", "imagecatalog\ImageCatalog 2.csproj", "{3F1E23DB-435E-0590-1EF5-735E898DBA3C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCatalog 3", "ImageCatalogCS\ImageCatalog 3.csproj", "{D11ED7B0-93E8-4F38-A142-EED72D7EE8B5}" EndProject @@ -15,10 +15,14 @@ Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "CatalogVbLib", "CatalogVbLi EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{A3D50937-74F6-4DC8-8D89-B534B484C0F9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaddoShared", "MaddoShared\MaddoShared.csproj", "{AEBFE9E3-277C-4A7B-8448-145D1B11998B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaddoShared", "MaddoShared\MaddoShared.csproj", "{AEBFE9E3-277C-4A7B-8448-145D1B11998B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCatalogParallel", "ImageCatalogParallel\ImageCatalogParallel.csproj", "{0F42DA5C-2788-48BD-BACA-01625C3CFFBB}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaddoLibrary.Base.NET46", "MaddoLibrary\MaddoLibrary.Base.NET46\MaddoLibrary.Base.NET46.csproj", "{E93DAAE6-4AA9-4A45-AFB6-58209B3AD3C9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaddoLibrary.WPF.NET46", "MaddoLibrary\MaddoLibrary.WPF.NET46\MaddoLibrary.WPF.NET46.csproj", "{73DA19D7-196D-4B16-B610-93250978A607}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -31,8 +35,8 @@ Global GlobalSection(ProjectConfigurationPlatforms) = postSolution {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.ActiveCfg = Debug|x64 - {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.Build.0 = Debug|x64 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.ActiveCfg = Debug|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.Build.0 = Debug|Any CPU {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x86.ActiveCfg = Debug|x86 {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x86.Build.0 = Debug|x86 {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/CatalogLib/CatalogLib.csproj b/CatalogLib/CatalogLib.csproj index c88f86e..631add3 100644 --- a/CatalogLib/CatalogLib.csproj +++ b/CatalogLib/CatalogLib.csproj @@ -9,7 +9,7 @@ Properties CatalogLib CatalogLib - v4.6 + v4.8 512 SAK SAK @@ -60,28 +60,33 @@ ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll True - - ..\packages\SixLabors.Core.0.1.0-alpha0002\lib\netstandard1.1\SixLabors.Core.dll + + ..\packages\SixLabors.Core.1.0.0-beta0002\lib\netstandard1.1\SixLabors.Core.dll - ..\packages\SixLabors.Fonts.0.1.0-alpha0014\lib\netstandard1.3\SixLabors.Fonts.dll + ..\packages\SixLabors.Fonts.1.0.0-beta0001\lib\netstandard1.3\SixLabors.Fonts.dll + + + ..\packages\SixLabors.ImageSharp.1.0.0-beta0001\lib\netstandard1.3\SixLabors.ImageSharp.dll + + + ..\packages\SixLabors.ImageSharp.Drawing.1.0.0-beta0001\lib\netstandard1.1\SixLabors.ImageSharp.Drawing.dll - ..\packages\SixLabors.Shapes.0.1.0-alpha0018\lib\netstandard1.1\SixLabors.Shapes.dll + ..\packages\SixLabors.Shapes.1.0.0-beta0001\lib\netstandard1.1\SixLabors.Shapes.dll - ..\packages\SixLabors.Shapes.Text.0.1.0-alpha0018\lib\netstandard1.1\SixLabors.Shapes.Text.dll + ..\packages\SixLabors.Shapes.Text.1.0.0-beta0001\lib\netstandard1.1\SixLabors.Shapes.Text.dll ..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - - ..\packages\System.Buffers.4.3.0\lib\netstandard1.1\System.Buffers.dll + + ..\packages\System.Buffers.4.4.0\lib\netstandard1.1\System.Buffers.dll - - ..\packages\System.Collections.Immutable.1.3.1\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll - True + + ..\packages\System.Collections.Immutable.1.4.0\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll @@ -109,7 +114,7 @@ ..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - ..\packages\System.Memory.4.4.0-preview1-25305-02\lib\netstandard1.0\System.Memory.dll + ..\packages\System.Memory.4.4.0-preview2-25405-01\lib\netstandard1.0\System.Memory.dll ..\packages\System.Net.Http.4.3.0\lib\net46\System.Net.Http.dll @@ -118,11 +123,11 @@ ..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - - ..\packages\System.Numerics.Vectors.4.3.0\lib\net46\System.Numerics.Vectors.dll + + ..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll - ..\packages\System.Runtime.CompilerServices.Unsafe.4.4.0-preview1-25305-02\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll + ..\packages\System.Runtime.CompilerServices.Unsafe.4.4.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll @@ -140,7 +145,7 @@ ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net46\System.Security.Cryptography.X509Certificates.dll - ..\packages\System.ValueTuple.4.4.0-preview1-25305-02\lib\netstandard1.0\System.ValueTuple.dll + ..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll @@ -153,11 +158,11 @@ + - @@ -167,10 +172,15 @@ {44465926-240d-473f-90b8-786ba4384406} CatalogVbLib + + {e93daae6-4aa9-4a45-afb6-58209b3ad3c9} + MaddoLibrary.Base.NET46 + + diff --git a/CatalogLib/Enums.cs b/CatalogLib/Enums.cs new file mode 100644 index 0000000..831a7c4 --- /dev/null +++ b/CatalogLib/Enums.cs @@ -0,0 +1,41 @@ +namespace CatalogLib +{ + public enum Positions + { + Alto, + Centro, + Basso + } + + public enum Alignments + { + Sinistra, + Centro, + Destra + } + + public enum ResizeModes + { + Bicubic, + Box, + CatmullRom, + Hermite, + Lanczos2, + Lanczos3, + Lanczos5, + Lanczos8, + MitchellNetravali, + NearestNeighbor, + Robidoux, + Spline, + Triangle, + Welch + + } + + public enum ResizeDimensions + { + LatoLungo, + LatoCorto + } +} \ No newline at end of file diff --git a/CatalogLib/ImageCreator.cs b/CatalogLib/ImageCreator.cs index d338c95..869544b 100644 --- a/CatalogLib/ImageCreator.cs +++ b/CatalogLib/ImageCreator.cs @@ -394,7 +394,7 @@ namespace CatalogLib } - switch (_picSettings.Posizione.ToUpper()) + switch (_picSettings.TextPosition.ToString().ToUpper()) { case "ALTO": yPosFromBottom1 = _picSettings.Margine; diff --git a/CatalogLib/ImgSharpCreator.cs b/CatalogLib/ImgSharpCreator.cs index 1f5ac0d..aa053a6 100644 --- a/CatalogLib/ImgSharpCreator.cs +++ b/CatalogLib/ImgSharpCreator.cs @@ -1,41 +1,76 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; using System.Linq; using System.Numerics; -using System.Text; using System.Threading.Tasks; -using ImageSharp; -using ImageSharp.Drawing; -using ImageSharp.PixelFormats; -using ImageSharp.Processing; +using MaddoLibrary.Base.Log; using SixLabors.Fonts; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.MetaData.Profiles.Exif; +using SixLabors.ImageSharp.Processing; +using SixLabors.Primitives; using Font = SixLabors.Fonts.Font; using FontFamily = SixLabors.Fonts.FontFamily; using FontStyle = SixLabors.Fonts.FontStyle; -using Image = ImageSharp.Image; - +using Rgba32 = SixLabors.ImageSharp.Rgba32; +using Image = SixLabors.ImageSharp.Image; namespace CatalogLib { public class ImgSharpCreator : IImageProcessor { + private Image _logo; + public ImgSharpCreator() + { + if (!PicSettings.Instance.EnableLogo) return; + if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return; + if (!File.Exists(PicSettings.Instance.LogoPath)) return; + + _logo = Image.Load(PicSettings.Instance.LogoPath); + + } private FileInfo _currentFile; public void Start(FileInfo workFile) { + + Stopwatch s = new Stopwatch(); + s.Start(); + _currentFile = workFile; using (Image image = Image.Load(workFile.FullName)/* new Image(workFile.FullName)*/) { + MaddoLogger.Log("Loaded Image: {0}", workFile.FullName); //image.Rotate(-90); + bool isRotated; + + var orientation = image.MetaData.ExifProfile.GetValue(ExifTag.Orientation); + if ((ushort)orientation.Value != 1) + { + isRotated = true; + } + else + { + isRotated = false; + } + + if (PicSettings.Instance.FotoRidimensiona) + { + Resize(image); + } + if (PicSettings.Instance.GeneraleRotazioneAutomatica) { - image.AutoOrient(); + image.Mutate(img => img.AutoOrient()); + MaddoLogger.Log("Rotated Image: {0}", workFile.FullName); + //image.AutoOrient(); //var exif = image.MetaData.ExifProfile; //if (exif != null) @@ -98,25 +133,134 @@ namespace CatalogLib if (PicSettings.Instance.EnableText) { - SetExtraText(image); + //SetTextTest(image); + SetExtraText(image, isRotated); + + + MaddoLogger.Log("Drawn text on Image: {0}", workFile.FullName); } //JpegDecoder j = new JpegDecoder(); var va = Vector.IsHardwareAccelerated; + MaddoLogger.Log("Hardware Accelerated: {0}", va); //image.Resize(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza); //image.Resize(2240, 2240); //var fff = FontCollection.SystemFonts.Find(PicSettings.Instance.NomeFont); //var font = new Font(fff, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular); //image.DrawText("sssssssssssssssssssssssssssssssssssssssssssssss", font, Color.Black, new Vector2(200, 200)); - image.Save(Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name)); + image.Save(Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name), new JpegEncoder() { Quality = PicSettings.Instance.CompressioneJpeg }); //image.Resize(200, 200).Save(""); + + MaddoLogger.Log("Saved Image: {0} to: {1}", workFile.FullName, Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name)); + } + s.Stop(); + MaddoLogger.Log("Time Taken for {0}: {1}", workFile.FullName, s.Elapsed); + } + + private void Resize(Image image) + { + IResampler resampler; + switch (PicSettings.Instance.ResizeMode) + { + case ResizeModes.Bicubic: + resampler = new BicubicResampler(); + break; + case ResizeModes.Box: + resampler = new BoxResampler(); + break; + case ResizeModes.CatmullRom: + resampler = new CatmullRomResampler(); + break; + case ResizeModes.Hermite: + resampler = new HermiteResampler(); + break; + case ResizeModes.Lanczos2: + resampler = new Lanczos2Resampler(); + break; + case ResizeModes.Lanczos3: + resampler = new Lanczos3Resampler(); + break; + case ResizeModes.Lanczos5: + resampler = new Lanczos5Resampler(); + break; + case ResizeModes.Lanczos8: + resampler = new Lanczos8Resampler(); + break; + case ResizeModes.MitchellNetravali: + resampler = new MitchellNetravaliResampler(); + break; + case ResizeModes.NearestNeighbor: + resampler = new NearestNeighborResampler(); + break; + case ResizeModes.Robidoux: + resampler = new RobidouxResampler(); + break; + case ResizeModes.Spline: + resampler = new SplineResampler(); + break; + case ResizeModes.Triangle: + resampler = new TriangleResampler(); + break; + case ResizeModes.Welch: + resampler = new WelchResampler(); + break; + default: + throw new ArgumentOutOfRangeException(); + } + // todo calcolare ridimensionamento + var size = new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza); + if (PicSettings.Instance.FotoMantieniDimensioni) + { + size = ResizeImage(image, size, PicSettings.Instance.ResizeDimension); + image.Mutate(x => x.Resize((size.Width), (size.Height), resampler)); + + //Width Formula: + //original height / original width * new width = new height + //Height Formula: + //orignal width / orignal height * new height = new width + } + else + { + + image.Mutate(x => x.Resize(PicSettings.Instance.FotoAltezza, PicSettings.Instance.FotoLarghezza, resampler)); } } - private void SetExtraText(Image image) + private Size ResizeImage(Image image, Size size, ResizeDimensions side) + { + switch (side) + { + case ResizeDimensions.LatoLungo: + size = GetResizeDimensions(new Size(image.Width, image.Height), size, image.Width > image.Height); + break; + case ResizeDimensions.LatoCorto: + size = GetResizeDimensions(new Size(image.Width, image.Height), size, image.Width <= image.Height); + break; + default: + throw new ArgumentOutOfRangeException(); + } + return size; + } + + private Size GetResizeDimensions(Size originalSize, Size newSize, bool adjustHeight) + { + return adjustHeight ? new Size(newSize.Width, originalSize.Height / originalSize.Width * newSize.Height) : new Size(originalSize.Width / originalSize.Height * newSize.Height, newSize.Height); + } + + private void SetTextTest(Image image) + { + string text = "test test test test test testtest test test test test test test"; + Font font = new Font(SystemFonts.Find("verdana"), 300, FontStyle.Regular); + image.Mutate(x => x.DrawText(text, font, Rgba32.Yellow, new PointF(2760, 3295.54932f), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + } + + private void SetExtraText(Image image, bool isRotated) { if (string.IsNullOrWhiteSpace(PicSettings.Instance.TestoApplicareOrizzontale)) { @@ -124,6 +268,24 @@ namespace CatalogLib return; } + string text; + if (isRotated) + { + if (PicSettings.Instance.TestoApplicareOrizzontale.Contains("$_")) + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", "\r\n"); + } + else + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", ""); + } + + } + else + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", ""); + } + var fo = SixLabors.Fonts.SystemFonts.Find(PicSettings.Instance.NomeFont); @@ -131,12 +293,27 @@ namespace CatalogLib //var fff = FontCollection.SystemFonts.Find(PicSettings.Instance.NomeFont); //var fff = FontCollection.SystemFonts.Find("Segoe Print"); - var font = new Font(fo, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular); + Font font; + + if (!PicSettings.Instance.Grassetto) + { + font = new Font(fo, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular); + } + else + { + font = new Font(fo, (float)PicSettings.Instance.DimensioneFont, FontStyle.Bold); + } + // todo corsivo + + + //var font = new Font(fff, 8f, FontStyle.Regular); //Color c = Color.FromHex(FlipRgbString(PicSettings.Instance.ColoreTestoRGB)); Rgba32 g = Rgba32.FromHex(FlipRgbString(PicSettings.Instance.ColoreTestoRGB)); + + Rgba32 gBack = Rgba32.Black; // todo alpha //TextMeasurer measurer = new TextMeasurer(); //var size = measurer.MeasureText(PicSettings.Instance.TestoApplicareOrizzontale, font, 72); @@ -147,13 +324,197 @@ namespace CatalogLib Vector2 center = new Vector2(image.Width / 2, image.Height / 2); //center horizontally, 10px down - var size = TextMeasurer.Measure(PicSettings.Instance.TestoApplicareOrizzontale, new RendererOptions(font)); + var size = TextMeasurer.Measure(text, new RendererOptions(font)); + + var larghezzaStandard = size.Width; + var dimensioneStandard = (int)Math.Round(PicSettings.Instance.DimensioneFont); + if (size.Width > image.Width) + { + var c = dimensioneStandard; + do + { + if (c > 20) + { + c -= 5; + } + else + { + c -= 1; + } + + if (PicSettings.Instance.Grassetto) + { + font = new Font(fo, c, FontStyle.Bold); + } + else + { + font = new Font(fo, c, FontStyle.Regular); + } + size = TextMeasurer.Measure(text, + new RendererOptions(font)); + if (size.Width < image.Width) + { + larghezzaStandard = (int)Math.Round(size.Width); + break; + } + if (c <= 5) + { + break; + } + } while (dimensioneStandard == c); + } + + float yPosFromBottom = 0; + + switch (PicSettings.Instance.TextPosition) + { + case Positions.Alto: + yPosFromBottom = PicSettings.Instance.Margine; + break; + case Positions.Basso: + yPosFromBottom = image.Height - size.Height - (image.Height * PicSettings.Instance.Margine / 100); + break; + } + + float xCenterofImg = 0; + + // stringformat + + switch (PicSettings.Instance.TextAlignment) + { + case Alignments.Sinistra: + xCenterofImg = PicSettings.Instance.Margine + (larghezzaStandard / 2); + if ((larghezzaStandard / 2) > (image.Width / 2) - PicSettings.Instance.Margine) + { + xCenterofImg = image.Width / 2; + } + break; + case Alignments.Centro: + xCenterofImg = image.Width / 2; + break; + case Alignments.Destra: + xCenterofImg = image.Width - PicSettings.Instance.Margine - larghezzaStandard / 2; + + if (larghezzaStandard / 2 > image.Width / 2 - PicSettings.Instance.Margine) + { + xCenterofImg = image.Width / 2; + } + + break; + } + // stringformat alignment center + + if (PicSettings.Instance.Grassetto) + { + font = new Font(fo, dimensioneStandard, FontStyle.Bold); + } + else + { + font = new Font(fo, dimensioneStandard, FontStyle.Regular); + } + + image.Mutate(x => x.DrawText(text, font, gBack, new PointF((float)Math.Round(xCenterofImg + 1), (float)Math.Round(yPosFromBottom + 1)), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + + image.Mutate(x => x.DrawText(text, font, g, new PointF((float)Math.Round(xCenterofImg), (float)Math.Round(yPosFromBottom)), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + + return; + + float scalingFactor = Math.Min(image.Width / size.Width, image.Height / size.Height); Font scaledFont = new Font(font, scalingFactor * font.Size); + image.Mutate(x => + x.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, center, + new TextGraphicsOptions(true) + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Bottom + })); + //image.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); - image.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); + } + + private void AddLogo(Image image) + { + //if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return; + //if (!File.Exists(PicSettings.Instance.LogoPath)) return; + //using (Image logo = Image.Load(PicSettings.Instance.LogoPath)) + //{ + // Size size = new Size(); + // Point location = new Point(); + // image.Mutate(x => x.DrawImage(logo, size, location, new GraphicsOptions() + // { + + // })); + + //} + + Size size = new Size(); + Point location = new Point(); + + if (_logo != null) + { + var width = PicSettings.Instance.LogoWidth; + var height = PicSettings.Instance.LogoHeight; + var heightFactor = _logo.Height / height; + var widthFactor = _logo.Width / width; + var newLogoSize = new Size(); + + newLogoSize = GetResizeDimensions(new Size(_logo.Width, _logo.Height), new Size(width, height), PicSettings.Instance.LogoResizeSide.Equals(ResizeDimensions.LatoCorto)); + //todo riguardare perché non torna cosa ho fatto + + int margineUsato = 0; + int margineL; + bool inPercentualeL; + + inPercentualeL = PicSettings.Instance.LogoMargin.EndsWith("%"); + if (inPercentualeL) + { + margineL = int.Parse(PicSettings.Instance.LogoMargin.Replace("%", "")); + } + else + { + margineL = int.Parse(PicSettings.Instance.LogoMargin); + } + + switch (PicSettings.Instance.LogoPosition) + { + case Positions.Alto: + break; + case Positions.Centro: + break; + case Positions.Basso: + break; + default: + throw new ArgumentOutOfRangeException(); + } + + switch (PicSettings.Instance.LogoAlignment) + { + case Alignments.Sinistra: + location.X = margineUsato; + break; + case Alignments.Centro: + //location.X = image.Width - + break; + case Alignments.Destra: + break; + default: + throw new ArgumentOutOfRangeException(); + } + image.Mutate(x => x.DrawImage(_logo, size, location, new GraphicsOptions())); + + + + + } } @@ -166,7 +527,7 @@ namespace CatalogLib var size = TextMeasurer.Measure("Test test test test test", new RendererOptions(font)); float scalingFactor = Math.Min(image.Width / size.Width, image.Height / size.Height); Font scaledFont = new Font(font, scalingFactor * font.Size); - image.DrawText("Test test test test test", scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); + image.Mutate(x => x.DrawText("Test test test test test", scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom })); } private string FlipRgbString(string originalString) diff --git a/CatalogLib/MaddoLogger.cs b/CatalogLib/MaddoLogger.cs deleted file mode 100644 index 3eba4b7..0000000 --- a/CatalogLib/MaddoLogger.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace CatalogLib -{ - public class MaddoLogger - { - public void AddToLog(string data) - { - string dest = Path.Combine(PicSettings.Instance.DirectoryDestinazione, "log.txt"); - - } - } -} diff --git a/CatalogLib/PicSettings.cs b/CatalogLib/PicSettings.cs index 9453628..795b004 100644 --- a/CatalogLib/PicSettings.cs +++ b/CatalogLib/PicSettings.cs @@ -6,7 +6,7 @@ using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; - +using MaddoLibrary.Base.Log; using Newtonsoft.Json; namespace CatalogLib @@ -71,6 +71,11 @@ namespace CatalogLib SetBase(key, value); } + public void SetFloat(string key, float value) + { + SetBase(key, value); + } + public void Set(string key, T value) { SetBase(key, value); @@ -134,6 +139,23 @@ namespace CatalogLib return (double)_settingsDict[key]; } + public float GetFloat(string key, float defaultValue = 0) + { + if (!_settingsDict.ContainsKey(key)) + { + SetFloat(key, defaultValue); + } + + if (_settingsDict[key] is float f) return f; + MaddoLogger.LogError("Error while parsing {0}", key); + + float fl = 0; + SetFloat(key, float.TryParse(_settingsDict[key].ToString(), out f) ? fl : defaultValue); + return (float)_settingsDict[key]; + } + + + public T Get(string key, T defaultValue) { if (!_settingsDict.ContainsKey(key)) @@ -146,6 +168,8 @@ namespace CatalogLib } + + public string GetString(string key, string defaultValue = "") { if (!_settingsDict.ContainsKey(key)) @@ -184,7 +208,10 @@ namespace CatalogLib //return _settingsDict.ContainsKey(key) ? _settingsDict[key] : defaultValue; } - + public T GetEnum(string name, T defaultValue) + { + return (T)Enum.Parse(typeof(T), GetString(name, defaultValue.ToString())); + } public void SetDefaults() { @@ -193,8 +220,8 @@ namespace CatalogLib public bool DirAggiornaSottoDirectory { - get { return this.GetBool("DirAggiornaSottoDirectory", true); } - set { this.SetBool("DirAggiornaSottoDirectory", value); } + get => this.GetBool("DirAggiornaSottoDirectory", true); + set => this.SetBool("DirAggiornaSottoDirectory", value); } public bool Grassetto @@ -262,12 +289,8 @@ namespace CatalogLib get { return 0; } } - public string Posizione - { - get { return string.Empty; } - } - + public DateTime DataPartenza { get; set; } public string TestoOrario { get; internal set; } public int DimStandard { get; internal set; } @@ -290,7 +313,11 @@ namespace CatalogLib set { SetString("DirDestinazione", value); } } - public float Margine { get; set; } + public int Margine + { + get => GetInt("Margin", 1); + set => SetInt("Margin", value); + } public float MargVert { get; set; } public string Allineamento { get; set; } @@ -432,8 +459,90 @@ namespace CatalogLib } } + public bool FotoRidimensiona + { + get => GetBool("FotoRidimensiona", false); + set => Set("FotoRidimensiona", value); + } + + public Positions TextPosition + { + get => GetEnum("TextPosition", Positions.Alto); //(Positions)Enum.Parse(typeof(Positions), GetString("TextPosition", Positions.Alto.ToString())); + set => SetString("TextPosition", value.ToString()); + } + + public Alignments TextAlignment + { + get => GetEnum("TextAlignment", Alignments.Centro); + set => SetString("TextAlignment", value.ToString()); + } + + public bool Threading + { + get => GetBool("Threading", true); + set => SetBool("Threading", value); + } + + public ResizeModes ResizeMode + { + get => GetEnum("ResizeMode", ResizeModes.Bicubic); + set => SetString("ResizeMode", value.ToString()); + } + + public ResizeDimensions ResizeDimension + { + get => GetEnum("ResizeDimension", CatalogLib.ResizeDimensions.LatoCorto); + set => SetString("ResizeDimension", value.ToString()); + } + + public string LogoPath + { + get => GetString("LogoPath"); + set => SetString("LogoPath", value); + } + + public int LogoWidth + { + get => GetInt("LogoWidth"); + set => SetInt("LogoWidth", value); + } + + public int LogoHeight + { + get => GetInt("LogoHeight"); + set => SetInt("LogoHeight", value); + } + + public string LogoMargin + { + get => GetString("LogoMargin"); + set => SetString("LogoMargin", value); + } + + public Positions LogoPosition + { + get => GetEnum("LogoPositions", Positions.Alto); + set => SetString("LogoPositions", value.ToString()); + } + + public Alignments LogoAlignment + { + get => GetEnum("LogoAlignments", Alignments.Centro); + set => SetString("LogoAlignments", value.ToString()); + } + + public ResizeDimensions LogoResizeSide + { + get => GetEnum("LogoResizeMode", ResizeDimensions.LatoCorto); + set => SetString("LogoResizeMode", value.ToString()); + } + #endregion + #region Enums + + + #endregion } } \ No newline at end of file diff --git a/CatalogLib/app.config b/CatalogLib/app.config index b5d559f..f007515 100644 --- a/CatalogLib/app.config +++ b/CatalogLib/app.config @@ -1,35 +1,35 @@ - + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - \ No newline at end of file + diff --git a/CatalogLib/packages.config b/CatalogLib/packages.config index 8beea34..86dfa50 100644 --- a/CatalogLib/packages.config +++ b/CatalogLib/packages.config @@ -10,7 +10,7 @@ - + @@ -19,45 +19,45 @@ - + - + - - - + + + - + - - - + + + - + - + - + - + - + \ No newline at end of file diff --git a/CatalogLib/stylecop.json b/CatalogLib/stylecop.json new file mode 100644 index 0000000..c67c0db --- /dev/null +++ b/CatalogLib/stylecop.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": + { + "orderingRules": + { + "usingDirectivesPlacement": "outsideNamespace" + }, + "documentationRules": + { + "xmlHeader": false, + "copyrightText": "Copyright (c) Six Labors and contributors.\nLicensed under the Apache License, Version 2.0." + } + } +} \ No newline at end of file diff --git a/CatalogVbLib/CatalogVbLib.vbproj b/CatalogVbLib/CatalogVbLib.vbproj index c6e2591..e042d2f 100644 --- a/CatalogVbLib/CatalogVbLib.vbproj +++ b/CatalogVbLib/CatalogVbLib.vbproj @@ -1,156 +1,44 @@ - - - + - Debug - AnyCPU - {44465926-240D-473F-90B8-786BA4384406} + net9.0-windows Library - CatalogVbLib - CatalogVbLib - 512 - Windows - v4.5 - SAK - SAK - SAK - SAK - - - true - full - true - true - bin\Debug\ - CatalogVbLib.xml - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - - - pdbonly - false - true - true - bin\Release\ - CatalogVbLib.xml - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - - - On - - - Binary - - - Off - - - On - - - true - true - true - bin\x64\Debug\ - CatalogVbLib.xml - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - full - x64 - MinimumRecommendedRules.ruleset - - - true - bin\x64\Release\ - CatalogVbLib.xml - true - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - pdbonly - x64 - MinimumRecommendedRules.ruleset + false + true + + embedded + + + embedded + - - ..\packages\Ben.Demystifier.0.3.0\lib\net45\Ben.Demystifier.dll - - - - ..\packages\System.Collections.Immutable.5.0.0\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll - - - - - ..\packages\System.Reflection.Metadata.5.0.0\lib\portable-net45+win8\System.Reflection.Metadata.dll - - - ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll - - - ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll - - - - - - - - - - - - - - - - - - - - - - - - - + True Application.myapp + True - + True True Resources.resx - + True Settings.settings True - - - VbMyResourcesResXFileCodeGenerator - Resources.Designer.vb - My.Resources - Designer - - - - + MyApplicationCodeGenerator Application.Designer.vb - - SettingsSingleFileGenerator - My - Settings.Designer.vb - - - - + + + + + + + \ No newline at end of file diff --git a/CatalogVbLib/My Project/Application.Designer.vb b/CatalogVbLib/My Project/Application.Designer.vb index 96b7331..88dd01c 100644 --- a/CatalogVbLib/My Project/Application.Designer.vb +++ b/CatalogVbLib/My Project/Application.Designer.vb @@ -1,7 +1,7 @@ '------------------------------------------------------------------------------ ' ' This code was generated by a tool. -' Runtime Version:4.0.30319.34011 +' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. diff --git a/CatalogVbLib/My Project/AssemblyInfo.vb b/CatalogVbLib/My Project/AssemblyInfo.vb index be5e3ed..4d58ddf 100644 --- a/CatalogVbLib/My Project/AssemblyInfo.vb +++ b/CatalogVbLib/My Project/AssemblyInfo.vb @@ -1,35 +1,9 @@ Imports System Imports System.Reflection Imports System.Runtime.InteropServices - -' Le informazioni generali relative a un assembly sono controllate dal seguente -' insieme di attributi. Per modificare le informazioni associate a un assembly -' è necessario modificare i valori di questi attributi. - -' Controllare i valori degli attributi dell'assembly - - - - - - 'Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi - -' Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: -' -' Numero di versione principale -' Numero di versione secondario -' Numero build -' Revisione -' -' È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build -' utilizzando l'asterisco (*) come descritto di seguito: -' - - - diff --git a/CatalogVbLib/My Project/Resources.Designer.vb b/CatalogVbLib/My Project/Resources.Designer.vb index 4c63fee..176c107 100644 --- a/CatalogVbLib/My Project/Resources.Designer.vb +++ b/CatalogVbLib/My Project/Resources.Designer.vb @@ -1,7 +1,7 @@ '------------------------------------------------------------------------------ ' ' This code was generated by a tool. -' Runtime Version:4.0.30319.34011 +' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. @@ -11,6 +11,7 @@ Option Strict On Option Explicit On +Imports System Namespace My.Resources @@ -21,20 +22,20 @@ Namespace My.Resources ''' ''' A strongly-typed resource class, for looking up localized strings, etc. ''' - _ + _ Friend Module Resources - + Private resourceMan As Global.System.Resources.ResourceManager - + Private resourceCulture As Global.System.Globalization.CultureInfo - + ''' ''' Returns the cached ResourceManager instance used by this class. ''' - _ + _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then @@ -44,17 +45,17 @@ Namespace My.Resources Return resourceMan End Get End Property - + ''' ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. ''' - _ + _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get - Set(ByVal value As Global.System.Globalization.CultureInfo) + Set resourceCulture = value End Set End Property diff --git a/CatalogVbLib/My Project/Settings.Designer.vb b/CatalogVbLib/My Project/Settings.Designer.vb index 30ce19b..9abf647 100644 --- a/CatalogVbLib/My Project/Settings.Designer.vb +++ b/CatalogVbLib/My Project/Settings.Designer.vb @@ -1,7 +1,7 @@ '------------------------------------------------------------------------------ ' ' This code was generated by a tool. -' Runtime Version:4.0.30319.34011 +' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. @@ -13,42 +13,42 @@ Option Explicit On Namespace My - - _ + + _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase - - Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) - + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) + #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then - Private Shared addedHandler As Boolean + Private Shared addedHandler As Boolean - Private Shared addedHandlerLockObject As New Object + Private Shared addedHandlerLockObject As New Object - _ - Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) - If My.Application.SaveMySettingsOnExit Then - My.Settings.Save() - End If - End Sub + _ + Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub #End If #End Region - + Public Shared ReadOnly Property [Default]() As MySettings Get - + #If _MyType = "WindowsForms" Then - If Not addedHandler Then - SyncLock addedHandlerLockObject - If Not addedHandler Then - AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings - addedHandler = True - End If - End SyncLock - End If + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If #End If Return defaultInstance End Get diff --git a/CatalogVbLib/packages.config b/CatalogVbLib/packages.config deleted file mode 100644 index b0d74df..0000000 --- a/CatalogVbLib/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/ImageCatalogCS/App.config b/ImageCatalogCS/App.config index 8e15646..4bfa005 100644 --- a/ImageCatalogCS/App.config +++ b/ImageCatalogCS/App.config @@ -1,6 +1,6 @@ - + - + - \ No newline at end of file + diff --git a/ImageCatalogCS/ImageCatalog 3.csproj b/ImageCatalogCS/ImageCatalog 3.csproj index 993bc20..ef71c58 100644 --- a/ImageCatalogCS/ImageCatalog 3.csproj +++ b/ImageCatalogCS/ImageCatalog 3.csproj @@ -1,5 +1,5 @@  - + Debug @@ -9,12 +9,13 @@ Properties ImageCatalogCS ImageCatalogCS - v4.5 + v4.8 512 SAK SAK SAK SAK + AnyCPU @@ -105,6 +106,7 @@ True Resources.resx + True SettingsSingleFileGenerator diff --git a/ImageCatalogCS/Properties/Resources.Designer.cs b/ImageCatalogCS/Properties/Resources.Designer.cs index 9c3a10e..6af1fd8 100644 --- a/ImageCatalogCS/Properties/Resources.Designer.cs +++ b/ImageCatalogCS/Properties/Resources.Designer.cs @@ -1,17 +1,17 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18010 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ -namespace ImageCatalogCS.Properties -{ - - +namespace ImageCatalogCS.Properties { + using System; + + /// /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -19,51 +19,43 @@ namespace ImageCatalogCS.Properties // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - + internal class Resources { + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { + internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageCatalogCS.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { + internal static global::System.Globalization.CultureInfo Culture { + get { return resourceCulture; } - set - { + set { resourceCulture = value; } } diff --git a/ImageCatalogCS/Properties/Settings.Designer.cs b/ImageCatalogCS/Properties/Settings.Designer.cs index 684a319..0e29f59 100644 --- a/ImageCatalogCS/Properties/Settings.Designer.cs +++ b/ImageCatalogCS/Properties/Settings.Designer.cs @@ -1,28 +1,24 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.18010 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ -namespace ImageCatalogCS.Properties -{ - - +namespace ImageCatalogCS.Properties { + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.11.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { + + public static Settings Default { + get { return defaultInstance; } } diff --git a/MaddoLibrary b/MaddoLibrary new file mode 160000 index 0000000..5987cc2 --- /dev/null +++ b/MaddoLibrary @@ -0,0 +1 @@ +Subproject commit 5987cc26521d839bf81bdaab19d101488294da19 diff --git a/MaddoShared.backup/FileData.cs b/MaddoShared.backup/FileData.cs new file mode 100644 index 0000000..37bd735 --- /dev/null +++ b/MaddoShared.backup/FileData.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public class FileData + { + /// + /// Il file originale + /// + public FileInfo File { get; set; } + /// + /// La cartella di destinazione + /// + public DirectoryInfo Directory { get; set; } + + public FileData(FileInfo newFile, DirectoryInfo newDirectory) + { + this.File = newFile; + this.Directory = newDirectory; + } + } +} diff --git a/MaddoShared.backup/FileHelperSharp.cs b/MaddoShared.backup/FileHelperSharp.cs new file mode 100644 index 0000000..905999e --- /dev/null +++ b/MaddoShared.backup/FileHelperSharp.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public class FileHelperOptions + { + public bool SeparateFiles { get; set; } + public NumerazioneType NumerationType { get; set; } + public int CounterSize { get; set; } + public string Suffix { get; set; } + public int FilesPerFolder { get; set; } + } + public enum NumerazioneType + { + Progressiva, + Files + } + public class FileHelperSharp + { + + public List GetFilesRecursive(DirectoryInfo root, DirectoryInfo destRoot, string filter, FileHelperOptions options) + { + ConcurrentDictionary dirSourceDest = new ConcurrentDictionary(); + List result = new List(); + + // Dim stack As New Stack(Of DirectoryInfo) + Stack> stack = new Stack>(); + + + + KeyValuePair pair = new KeyValuePair(); + + + // stack.Push(root) + stack.Push(new KeyValuePair(root, destRoot)); + + while ((stack.Count > 0)) + { + KeyValuePair curDirKV = stack.Pop(); + // curDirKP = stack.Pop() + DirectoryInfo dir = curDirKV.Key; + DirectoryInfo dDir = curDirKV.Value; + try + { + // result.AddRange(dir.GetFiles(filter, SearchOption.TopDirectoryOnly)) + // dividere file qui + if (options.FilesPerFolder > 0 & options.SeparateFiles) + AppendDictionaryConcurrent(dirSourceDest, DividiFilesInDirConcurrent(dir, dDir, options, filter)); + else + AppendDictionaryConcurrent(dirSourceDest, DividiFilesInDirConcurrent(dir, dDir, options, filter)); + + foreach (DirectoryInfo subDirectory in dir.GetDirectories()) + stack.Push(new KeyValuePair(subDirectory, new DirectoryInfo(Path.Combine(dDir.FullName, subDirectory.Name)))); + } + catch (Exception ex) + { + // TODO ERROR + } + } + + List resultData = new List(); + resultData.AddRange(from p in dirSourceDest + select new FileData(p.Key, p.Value)); + return resultData; + } + + public ConcurrentDictionary AppendDictionaryConcurrent(ConcurrentDictionary dictA, ConcurrentDictionary dictB) + { + foreach (KeyValuePair pair in dictB) + dictA.TryAdd(pair.Key, pair.Value); + return dictA; + } + + + private ConcurrentDictionary DividiFilesInDirConcurrent(DirectoryInfo dir, DirectoryInfo dirDest, FileHelperOptions options, string filter) + { + //int filesCount = dir.GetFiles(Filter).Length; + int contaFilePerDir = 0; + int contaDirPerDir = 0; + string tempText;// = string.Empty; + ConcurrentDictionary foldersDict = new ConcurrentDictionary(); + + DirectoryInfo destDir; + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName)); + foreach (FileInfo file in dir.GetFiles(filter)) + { + contaFilePerDir += 1; + + if (contaFilePerDir == (contaDirPerDir * options.FilesPerFolder) + 1) + { + contaDirPerDir += 1; + + tempText = options.NumerationType == NumerazioneType.Progressiva ? contaDirPerDir.ToString() : (contaDirPerDir * options.FilesPerFolder).ToString(); + int i; + for (i = 1; i <= (options.CounterSize - tempText.Length); i++) + tempText = "0" + tempText; + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName, options.Suffix + tempText)); + } + + if (!destDir.Exists) + destDir.Create(); + + foldersDict.TryAdd(file, destDir); + } + + return foldersDict; + } + + } +} diff --git a/MaddoShared.backup/ImageCreationStuff.cs b/MaddoShared.backup/ImageCreationStuff.cs new file mode 100644 index 0000000..439f3dc --- /dev/null +++ b/MaddoShared.backup/ImageCreationStuff.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CatalogVbLib; +using Dasync.Collections; + +namespace MaddoShared +{ + public class ImageCreationStuff + { + public class Options + { + public bool AggiornaSottodirectory { get; set; } + public bool CreaSottocartelle { get; set; } + + public int FilePerCartella { get; set; } + public string SuffissoCartelle { get; set; } + public int CifreContatore { get; set; } + public NumerazioneType NumerazioneType { get; set; } + public string SourcePath { get; set; } + public string DestinationPath { get; set; } + + public int MaxThreads { get; set; } + public int ChunksSize { get; set; } + public bool LinearExecution { get; set; } + } + + public async Task CreaCatalogoParallel(Options options, ConcurrentBag results, EventHandler> updateEvent, CancellationToken cancellationToken = default(CancellationToken)) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + // todo immagini counter + //todo set label + await CreaImmaginiParallel(options, results, updateEvent, cancellationToken); + + // todo set finito label + stopwatch.Stop(); + + return $"{stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m ${stopwatch.Elapsed.Seconds}s ({stopwatch.Elapsed.TotalSeconds}s)"; + + + } + + public async Task CreaImmaginiParallel(Options options, ConcurrentBag results, EventHandler> updateEvent, CancellationToken cancellationToken = default(CancellationToken)) + { + var dataToProcess = new List(); + if (options.AggiornaSottodirectory && options.CreaSottocartelle) + { + var helper = new FileHelperSharp(); + dataToProcess = 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 + }); + } + else if (!options.CreaSottocartelle) + { + 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 + // ? SearchOption.AllDirectories + // : SearchOption.TopDirectoryOnly) + // select new FileData(new FileInfo(f), + // new DirectoryInfo(options.DestinationPath.PathCombine( + // new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "") + // ) + // ) + // ) + // ) + // .ToList(); + } + + var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; + var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads) + .ConcurrentScheduler; + + //var allTasks = new List(); + var test = from d in dataToProcess + select Task.Factory.StartNew(async () => + { + await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name); + + //var imgC = new ImageCreatorSharp(d.File, d.Directory); + //imgC.CreaImmagineThread(d.File.Name); + //imgC = null; + }, CancellationToken.None, TaskCreationOptions.None, scheduler); + + //int count = 0; + + if (options.LinearExecution) + { + foreach (var task in test) + { + await task; + } + } + else + { + if (options.ChunksSize == 0) + { + + + //var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler}; + await dataToProcess.ParallelForEachAsync(async fileData => + { + 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(fileData.File.Name, dataToProcess.Count) ); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + + }, maxDegreeOfParallelism: threads, false, cancellationToken); + + + } + else + { + + var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList(); + + + foreach (var sdaf in asdf) + { + await sdaf.ParallelForEachAsync(async fileData => + { + 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(fileData.File.Name, dataToProcess.Count)); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + }, maxDegreeOfParallelism: threads, false, cancellationToken); + } + + + + } + } + + + } + + public static IEnumerable> SplitList(List bigList, int nSize = 3) + { + for (int i = 0; i < bigList.Count; i += nSize) + { + yield return bigList.GetRange(i, Math.Min(nSize, bigList.Count - i)); + } + } + } +} diff --git a/MaddoShared.backup/ImageCreatorSharp.cs b/MaddoShared.backup/ImageCreatorSharp.cs new file mode 100644 index 0000000..13f0d8e --- /dev/null +++ b/MaddoShared.backup/ImageCreatorSharp.cs @@ -0,0 +1,1021 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualBasic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Windows.Forms; +using CatalogVbLib; +using SixLabors.ImageSharp.Metadata.Profiles.Exif; + +// Imports System.Threading + +public class ImageCreatorSharp +{ + private bool FotoRuotaADestra = false; + private bool FotoRuotaASinistra = false; + + private string TempMinText = ""; + // Private crFont1 As Font + private string _NomeFileChild; + + private DirectoryInfo _SourceDir; + private DirectoryInfo _DestDirStart; + private DirectoryInfo _DestDir; + + private FileInfo _workFile; + + private string testoFirma; + private string testoFirmaV; + private int alphaScelta; + private int DimensioneStandard; + private int DimensioneStandardMiniatura; + private DateTime dataFoto; + private DateTime dataPartenzaI; + private string testoOrario; + private string testoFirmaPiccola; + private Size thumbSizeSmall; + private Size thumbSizeBig; + private string nomeFileSmall; + private string nomeFileBig; + private string nomeFileBig2; + + private float yPosFromBottom; + private float yPosFromBottom1; + private float yPosFromBottom2; + private float yPosFromBottom3; + private float yPosFromBottom4; + + private ExifReader.Orientations _orientation; + private DateTime? _creationDate; + + public ImageCreatorSharp() + { + } + + public ImageCreatorSharp(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir, DirectoryInfo destDirStart) + { + this.NomeFileChild = nomeFileChild; + this.SourceDir = sourceDir; + this.DestDir = destDir; + this.DestDirStart = destDirStart; + this.WorkFile = new FileInfo(nomeFileChild); + } + + public ImageCreatorSharp(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir) + { + this.NomeFileChild = nomeFileChild; + this.DestDir = destDir; + } + + public ImageCreatorSharp(FileInfo file, DirectoryInfo destination) + { + this.WorkFile = file; + this.DestDir = destination; + } + + public async Task CreaImmagineThread(string Info) + { + try + { + await Task.Run(() => + { + Console.WriteLine($"File: {WorkFile} Dest: {DestDir}"); + preparaVariabili(); + ExtractExif(); + // Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(Path.Combine(SourceDir.FullName, NomeFileChild)) + using (Image g = Image.FromFile(WorkFile.FullName)) + { + + // Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(WorkFile.FullName) + + // Imposta testo extra + impostaTestoExtra(g); + + // Ruota l'immagine in base ai dati EXIF + Rotation(g); + + // Forza jpeg se è selezionata l'opzione + System.Drawing.Imaging.ImageFormat thisFormat = g.RawFormat; + if (PicSettings.UsaForzaJpg == true) + thisFormat = System.Drawing.Imaging.ImageFormat.Jpeg; + + prepareThumbnailSize(g); + + 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); + + // Crea le miniature + creaMiniature(g, imgOutputBig, thisFormat); + + AggiungiTesto(g, imgOutputBig); + + aggiungiLogo(imgOutputBig); + + SalvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat); + } + + + } + }); + + // g.Dispose() + + //GC.Collect(); + } + + // PicSettings.mainForm.stepProgressBar() + + catch (Exception ex) + { + var e = ex.Demystify(); + Console.WriteLine(e); + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); + } + } + + private void ExtractExif() + { + using (var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName)) + { + ExifReader.Orientations finalOrientation; + var rotation = img.Metadata?.ExifProfile?.GetValue(ExifTag.Orientation); + if (rotation == null) + { + finalOrientation = ExifReader.Orientations.TopLeft; + } + else + { + finalOrientation = (ExifReader.Orientations)rotation.Value; + } + + _orientation = finalOrientation; + + var creation = img.Metadata?.ExifProfile?.GetValue(ExifTag.DateTime); + if (creation != null) + { + var succ = DateTime.TryParse(creation.Value, out var crDate); + if (succ) + { + _creationDate = crDate; + } + else + { + _creationDate = null; + } + } + else + { + _creationDate = null; + } + + + } + } + + private void Rotation(System.Drawing.Image g) + { + FotoRuotaADestra = false; + FotoRuotaASinistra = false; + + if (PicSettings.UsaRotazioneAutomatica == true) + { + if (g.PropertyIdList.Length > 0) + { + + + //ExifReader DatiExif = new ExifReader((Bitmap)g); + + switch (_orientation /*DatiExif.Orientation*/) + { + case ExifReader.Orientations.BottomLeft: + case ExifReader.Orientations.BottomRight: + case ExifReader.Orientations.LeftTop: + case ExifReader.Orientations.LftBottom: + FotoRuotaASinistra = true; + break; + case ExifReader.Orientations.RightBottom: + case ExifReader.Orientations.RightTop: + case ExifReader.Orientations.TopLeft: + case ExifReader.Orientations.TopRight: + break; + + } + } + } + + if (FotoRuotaASinistra == true) + g.RotateFlip(RotateFlipType.Rotate270FlipNone); + if (FotoRuotaADestra == true) + g.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + /// + /// ''' Aggiunge Orario, tempo gara e altri + /// ''' + /// ''' Image + /// ''' + private void impostaTestoExtra(Image g) + { + if (PicSettings.UsaOrarioTestoApplicare | PicSettings.UsaTempoGaraTestoApplicare | PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + if (g.PropertyIdList.Length > 0) + { + //ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = _creationDate ?? DateTime.Now; //DatiExif.DateTimeOriginal; + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + + if (dataFoto.Year != 1) + { + testoFirmaPiccola = dataFoto.ToShortTimeString(); + if (PicSettings.UsaOrarioTestoApplicare == true) + { + testoFirma += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + testoFirmaV += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + } + if (PicSettings.UsaTempoGaraTestoApplicare == true) + { + + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + + TimeSpan Orario = new TimeSpan(0, 0, 0, (int)diffA); + testoFirma += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + testoFirmaV += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + } + } + } + } + else + { + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + } + } + + /// + /// ''' Prepara diverse variabili azzerandole, elaborandole e prendendole dalle impostazioni + /// ''' + /// ''' + private void preparaVariabili() + { + alphaScelta = System.Convert.ToInt32((255 * (100 - PicSettings.Trasparenza) / (double)100)); + testoFirma = ""; + testoFirmaV = ""; + dataPartenzaI = PicSettings.DataPartenza; + testoOrario = PicSettings.TestoOrario; + if (testoOrario.Length > 0) + testoOrario += " "; + testoFirmaPiccola = ""; + thumbSizeSmall = new Size(); + thumbSizeBig = new Size(); + nomeFileSmall = ""; + nomeFileBig2 = ""; + nomeFileBig = ""; + DimensioneStandard = PicSettings.DimStandard; + DimensioneStandardMiniatura = PicSettings.DimStandardMiniatura; + // nomeFileSmall = Suffisso & NomeFileChild + // nomeFileBig = NomeFileChild + nomeFileSmall = PicSettings.Suffisso + WorkFile.Name; + nomeFileBig = WorkFile.Name; + } + + private void prepareThumbnailSize(Image g) + { + if (g.Width > g.Height) + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.LarghezzaSmall, "Larghezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + else + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.AltezzaSmall, "Altezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + } + + private void creaMiniature(Image g, Bitmap imgOutputBig, ImageFormat thisFormat) + { + if (PicSettings.TestoMin) + testoFirmaPiccola = nomeFileBig; + else if (PicSettings.AggNumTempMin) + testoFirmaPiccola = nomeFileBig + " "; + // Dim yPosFromBottom4 As Single + + Font crFont1 = null/* TODO Change to default(_) if this is not a reference type */; + Font crFont2 = null/* TODO Change to default(_) if this is not a reference type */; + SizeF crSize1 = new SizeF(); + SizeF crSize2 = new SizeF(); + + if (PicSettings.CreaMiniature == true) + { + if (PicSettings.AggiungiScritteMiniature == false) + { + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + nomeFileSmall = nomeFileSmall.Substring(0, nomeFileSmall.Length - 4) + PicSettings.Codice + nomeFileSmall.Substring(nomeFileSmall.Length - 4); + if (PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + if (testoFirmaPiccola.Length > 0) + { + using (var imgOutputSmall = (Bitmap)imgOutputBig.Clone()) + { + Graphics grPhoto1; + grPhoto1 = Graphics.FromImage(imgOutputSmall); + grPhoto1.SmoothingMode = SmoothingMode.AntiAlias; + + int LarghezzaStandard1; + // quick fix + DimensioneStandardMiniatura = 50; + if (PicSettings.Grassetto == true) + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + } + else + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard); + } + + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + crSize2 = grPhoto1.MeasureString(testoFirma, crFont1); + LarghezzaStandard1 = System.Convert.ToInt32(crSize1.Width); + + if (crSize1.Width > System.Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandardMiniatura; + do + { + if (Conta > 20) + Conta -= 5; + else + Conta -= 1; + if (PicSettings.Grassetto == true) + crFont1 = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + else + crFont1 = new Font(PicSettings.IlFont, Conta); + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + if (crSize1.Width < System.Convert.ToSingle(g.Width)) + { + LarghezzaStandard1 = System.Convert.ToInt32(crSize1.Width); + break; + } + + if (Conta <= 5) + break; + } + while (true); + DimensioneStandardMiniatura = Conta; + } + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + { + yPosFromBottom1 = (PicSettings.Margine); + yPosFromBottom4 = (PicSettings.MargVert); + break; + } + + case "BASSO": + { + yPosFromBottom1 = System.Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.Margine / (double)100))); + yPosFromBottom4 = System.Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.MargVert / (double)100))); + break; + } + } + + float xCenterOfImg1 = 0; + + StringFormat StrFormat1 = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + { + xCenterOfImg1 = System.Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard1 / (double)2))); + + if ((LarghezzaStandard1 / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "CENTRO": + { + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "DESTRA": + { + xCenterOfImg1 = System.Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard1 / (double)2))); + + if ((LarghezzaStandard1 / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + } + StrFormat1.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush21 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + SolidBrush semiTransBrush1 = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + // quick fix + DimensioneStandardMiniatura = PicSettings.DimMin; + + if (PicSettings.Grassetto == true) + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + else + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + // asdgadfhdfhjgfsjgfjygfdhsdafa + if (PicSettings.TestoMin) + { + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else if (PicSettings.AggTempoGaraMin & PicSettings.UsaTempoGaraTestoApplicare) + { + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + + TimeSpan Orario = new TimeSpan(0, 0, (int)diffA);/* new TimeSpan(DateTime.DateDiff(DateInterval.Second, dataPartenzaI, dataFoto) * 10000000);*/ + string tempstr = ""; + + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else if (PicSettings.AggNumTempMin) + { + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + TimeSpan Orario = new TimeSpan(0, 0, (int)diffA); + string tempstr = ""; + tempstr += nomeFileBig; + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else + { + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + + // Salva la miniatura + //using (var g22 = Image.FromHbitmap(imgOutputSmall)) + + + using (var imgOutputSmall2 = new Bitmap(imgOutputSmall, thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + imgOutputSmall2.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + + //imgOutputSmall2.Dispose(); + } + + //imgOutputSmall.Dispose(); + } + + + //File.Delete(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall)); + //FileSystem.Kill(); + } + else + { + using (Bitmap 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)) + { + imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + //imgOutputSmall.Dispose(); + } + } + } + } + + crFont1?.Dispose(); + crFont2?.Dispose(); + } + + private void AggiungiTesto(Image g, Bitmap 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 */; + SizeF crSize = new SizeF(); + int LarghezzaStandard; + + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + crSize = grPhoto.MeasureString(testoFirma, crFont); + LarghezzaStandard = System.Convert.ToInt32(crSize.Width); + + if (crSize.Width > System.Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandard; + do + { + if (Conta > 20) + Conta -= 5; + else + Conta -= 1; + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, Conta); + crSize = grPhoto.MeasureString(testoFirma, crFont); + if (crSize.Width < System.Convert.ToSingle(g.Width)) + { + LarghezzaStandard = System.Convert.ToInt32(crSize.Width); + break; + } + + if (Conta <= 5) + break; + } + while (true); + DimensioneStandard = Conta; + } + + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + { + yPosFromBottom = (PicSettings.Margine); + yPosFromBottom3 = (PicSettings.MargVert); + break; + } + + case "BASSO": + { + yPosFromBottom = System.Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.Margine / (double)100))); + yPosFromBottom3 = System.Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.MargVert / (double)100))); + break; + } + } + + float xCenterOfImg = 0; + float xCenterOfImg3 = 0; + StringFormat StrFormat = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + { + xCenterOfImg = System.Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard / (double)2))); + xCenterOfImg3 = System.Convert.ToSingle((PicSettings.MargVert + (LarghezzaStandard / (double)2))); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.MargVert) + xCenterOfImg3 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "CENTRO": + { + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "DESTRA": + { + xCenterOfImg = System.Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard / (double)2))); + xCenterOfImg3 = System.Convert.ToSingle((g.Width - PicSettings.MargVert - (LarghezzaStandard / (double)2))); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.MargVert) + xCenterOfImg3 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + } + StrFormat.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + // Dim semiTransBrush As SolidBrush = New SolidBrush(Color.FromArgb(AlphaScelta, _FontColoreR, _FontColoreG, _FontColoreB)) + SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + if (FotoRuotaADestra | FotoRuotaASinistra) + { + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, PicSettings.DimVert, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, PicSettings.DimVert); + } + else if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + + + // qui scrive il testo (nomefilebig) + if (PicSettings.TestoNome) + { + if (PicSettings.NomeData & g.PropertyIdList.Length > 0) + { + //ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = _creationDate ?? DateTime.Now; //DatiExif.DateTimeOriginal; + + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + else + { + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + } + + if (PicSettings.TestoNome == false) + { + if (FotoRuotaADestra | FotoRuotaASinistra) + { + if (PicSettings.TestoMin == false) + { + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom3 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom3), StrFormat); + } + if (PicSettings.TestoMin == true) + { + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom4 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom4), StrFormat); + } + } + else + { + grPhoto.DrawString(testoFirma, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(testoFirma, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + } + + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + { + nomeFileBig2 = nomeFileBig; + nomeFileBig = nomeFileBig.Substring(0, nomeFileBig.Length - 4) + PicSettings.Codice + nomeFileBig.Substring(nomeFileBig.Length - 4); + } + //grPhoto.Dispose(); + + crFont?.Dispose(); + } + + + } + + + + + private void aggiungiLogo(Bitmap imgOutputBig) + { + // imgOutputBig + if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile)) + { + Image ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile); + + 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 + 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) + ColorMap colorMap = new ColorMap(); + + // * background this will be the color we search for and replace with transparency + colorMap.OldColor = LogoColoreTrasparente; + colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); + + ColorMap[] remapTable = new[] { colorMap }; + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); + + // * The second color manipulation is used to change the opacity by setting the 3rd row and 3rd column to 0.3f + float[][] colorMatrixElements = new[] { new float[] { 1.0F, 0.0F, 0.0F, 0.0F, 0.0F }, new float[] { 0.0F, 1.0F, 0.0F, 0.0F, 0.0F }, new float[] { 0.0F, 0.0F, 1.0F, 0.0F, 0.0F }, new float[] { 0.0F, 0.0F, 0.0F, System.Convert.ToSingle(PicSettings.LogoTrasparenza) / 100F, 0.0F }, new float[] { 0.0F, 0.0F, 0.0F, 0.0F, 1.0F } }; + ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); + imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); + + int FotoLogoH = PicSettings.LogoAltezza; + int FotoLogoW = PicSettings.LogoLarghezza; + double FattoreAlt = ImmagineLogo.Height / (double)FotoLogoH; + double FattoreLarg = ImmagineLogo.Width / (double)FotoLogoW; + Size NuovaSize; + if (FattoreLarg > FattoreAlt) + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoW, "Larghezza"); + else + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoH, "Altezza"); + + int MargineUsato; + int MargineL; + bool InPercentualeL; + if (PicSettings.LogoMargine.EndsWith("%") == true) + InPercentualeL = true; + else + InPercentualeL = false; + MargineL = System.Convert.ToInt32(PicSettings.LogoMargine); + if (InPercentualeL == true) + MargineUsato = System.Convert.ToInt32(imgOutputBig.Height * MargineL / (double)100); + else + MargineUsato = MargineL; + + int xPosOfWm = 0; + int yPosOfWm = 0; + switch (PicSettings.LogoPosizioneH.ToUpper()) + { + case "SINISTRA": + case "NESSUNA": + { + xPosOfWm = MargineUsato; + break; + } + + case "CENTRO": + { + xPosOfWm = System.Convert.ToInt32((imgOutputBig.Width - NuovaSize.Width) / (double)2); + break; + } + + case "DESTRA": + { + xPosOfWm = ((imgOutputBig.Width - NuovaSize.Width) - MargineUsato); + break; + } + } + switch (PicSettings.LogoPosizioneV.ToUpper()) + { + case "ALTO": + case "NESSUNA": + { + yPosOfWm = MargineUsato; + break; + } + + case "CENTRO": + { + yPosOfWm = System.Convert.ToInt32((imgOutputBig.Height - NuovaSize.Height) / (double)2); + break; + } + + case "BASSO": + { + yPosOfWm = ((imgOutputBig.Height - NuovaSize.Height) - MargineUsato); + break; + } + } + + grWatermark.DrawImage(ImmagineLogo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, ImmagineLogo.Width, ImmagineLogo.Height, GraphicsUnit.Pixel, imageAttributes); + //grWatermark.Dispose(); + } + } + } + + + private void SalvaFoto(Bitmap imgOutputBig, Size thumbSizeBig, string NomeFileBig, string NomeFileSmall, Size thumbSizeSmall, ImageFormat thisFormat) + { + using (var image1Stream = new MemoryStream()) + { + + + + if (PicSettings.FotoGrandeDimOrigina == false) + { + // attenzione non controlla se è png + // imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" & NomeFileBig), thisFormat) + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + MakeImageCustomQuality(imgOutputBig, image1Stream); + } + //SalvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), PicSettings.jpegQuality); + else + { + imgOutputBig.Save(image1Stream, thisFormat); + } + //imgOutputBig.Save(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), thisFormat); + image1Stream.Seek(0, SeekOrigin.Begin); + 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)) + { + 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(); + } + else + { + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + SalvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality); + else + imgOutputBig.Save(Path.Combine(DestDir.FullName, NomeFileBig), thisFormat); + + //imgOutputBig.Dispose(); + } + image1Stream.Seek(0, SeekOrigin.Begin); + + if (PicSettings.CreaMiniature) + { + if (PicSettings.AggiungiScritteMiniature) + { + 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)) + { + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + PicSettings.Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4); + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + SalvaImmagineCustomQuality(imgOutputSmall, Path.Combine(DestDir.FullName, NomeFileSmall), PicSettings.jpegQualityMin); + else + 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) + { + ImageCodecInfo JgpEncoder = GetEncoder(ImageFormat.Jpeg); + System.Drawing.Imaging.Encoder MyEncoder = System.Drawing.Imaging.Encoder.Quality; + + EncoderParameters MyEncoderParameters = new EncoderParameters(1); + + EncoderParameter MyEncoderParameter = new EncoderParameter(MyEncoder, PicSettings.jpegQuality); + MyEncoderParameters.Param[0] = MyEncoderParameter; + imageToSave.Save(nomeFileFinale, JgpEncoder, MyEncoderParameters); + //imageToSave.Dispose(); + } + + private void MakeImageCustomQuality(Bitmap imageToSave, Stream destinationStream) + { + ImageCodecInfo JgpEncoder = GetEncoder(ImageFormat.Jpeg); + System.Drawing.Imaging.Encoder MyEncoder = System.Drawing.Imaging.Encoder.Quality; + + EncoderParameters MyEncoderParameters = new EncoderParameters(1); + + EncoderParameter MyEncoderParameter = new EncoderParameter(MyEncoder, PicSettings.jpegQuality); + MyEncoderParameters.Param[0] = MyEncoderParameter; + destinationStream.Seek(0, SeekOrigin.Begin); + imageToSave.Save(destinationStream, JgpEncoder, MyEncoderParameters); + //imageToSave.Dispose(); + } + + + private ImageCodecInfo GetEncoder(ImageFormat format) + { + ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); + + + foreach (var codec in codecs) + { + if (codec.FormatID == format.Guid) + return codec; + } + return null/* TODO Change to default(_) if this is not a reference type */; + } + + + + + + + /// + /// ''' Calculate the Size of the New image + /// ''' + /// ''' Larghezza + /// ''' Altezza + /// ''' + /// ''' + /// ''' + /// ''' + private Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize) + { + // e + // *** Larghezza, Altezza, Auto + + double tempMultiplier; + + if (TipoSize.ToUpper() == "Larghezza".ToUpper()) + tempMultiplier = MaxPixel / (double)currentwidth; + else if (TipoSize.ToUpper() == "Altezza".ToUpper()) + tempMultiplier = MaxPixel / (double)currentheight; + else if (currentheight > currentwidth) + tempMultiplier = MaxPixel / (double)currentheight; + else + tempMultiplier = MaxPixel / (double)currentwidth; + + Size NewSize = new Size(System.Convert.ToInt32(currentwidth * tempMultiplier), System.Convert.ToInt32(currentheight * tempMultiplier)); + + return NewSize; + } + + public FileInfo WorkFile + { + get + { + return _workFile; + } + set + { + _workFile = value; + } + } + + public DirectoryInfo DestDir + { + get => _DestDir; + set => _DestDir = value; + } + + public DirectoryInfo SourceDir + { + get + { + return _SourceDir; + } + set + { + _SourceDir = value; + } + } + + public DirectoryInfo DestDirStart + { + get + { + return _DestDirStart; + } + set + { + _DestDirStart = value; + } + } + + public string NomeFileChild + { + get + { + return _NomeFileChild; + } + set + { + _NomeFileChild = value; + } + } +} diff --git a/MaddoShared.backup/MaddoShared.csproj b/MaddoShared.backup/MaddoShared.csproj new file mode 100644 index 0000000..03c762e --- /dev/null +++ b/MaddoShared.backup/MaddoShared.csproj @@ -0,0 +1,101 @@ + + + + + Debug + AnyCPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B} + Library + Properties + MaddoShared + MaddoShared + v4.7.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\AsyncEnumerator.4.0.2\lib\net461\AsyncEnumerable.dll + + + ..\packages\Ben.Demystifier.0.3.0\lib\net45\Ben.Demystifier.dll + + + ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\packages\SixLabors.ImageSharp.1.0.3\lib\net472\SixLabors.ImageSharp.dll + + + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.5.0.0\lib\net461\System.Collections.Immutable.dll + + + + + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Reflection.Metadata.5.0.0\lib\net461\System.Reflection.Metadata.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + + + + ..\packages\Z.ExtensionMethods.2.1.1\lib\net45\Z.ExtensionMethods.dll + + + + + + + + + + + + + {44465926-240d-473f-90b8-786ba4384406} + CatalogVbLib + + + + + + + + \ No newline at end of file diff --git a/MaddoShared.backup/Properties/AssemblyInfo.cs b/MaddoShared.backup/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..52a601e --- /dev/null +++ b/MaddoShared.backup/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MaddoShared")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MaddoShared")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("aebfe9e3-277c-4a7b-8448-145d1b11998b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MaddoShared.backup/ThreadingHelper.cs b/MaddoShared.backup/ThreadingHelper.cs new file mode 100644 index 0000000..f0ce4db --- /dev/null +++ b/MaddoShared.backup/ThreadingHelper.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public static class ThreadingHelper + { + /// + /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. + /// NOTE: If one of the given tasks has already been started, an exception will be thrown. + /// + /// The tasks to run. + /// The maximum number of tasks to run in parallel. + /// The cancellation token. + public static void StartAndWaitAllThrottled(IEnumerable tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken()) + { + StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken); + } + + /// + /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. + /// NOTE: If one of the given tasks has already been started, an exception will be thrown. + /// + /// The tasks to run. + /// The maximum number of tasks to run in parallel. + /// The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely. + /// The cancellation token. + public static void StartAndWaitAllThrottled(IEnumerable tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken()) + { + // Convert to a list of tasks so that we don't enumerate over it multiple times needlessly. + var tasks = tasksToRun.ToList(); + + using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel)) + { + var postTaskTasks = new List(); + + // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running. + tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release()))); + + // Start running each task. + foreach (var task in tasks) + { + // Increment the number of tasks currently running and wait if too many are running. + throttler.Wait(timeoutInMilliseconds, cancellationToken); + + cancellationToken.ThrowIfCancellationRequested(); + task.Start(); + } + + // Wait for all of the provided tasks to complete. + // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler's using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object. + Task.WaitAll(postTaskTasks.ToArray(), cancellationToken); + } + } + } +} diff --git a/MaddoShared.backup/app.config b/MaddoShared.backup/app.config new file mode 100644 index 0000000..8d59e6b --- /dev/null +++ b/MaddoShared.backup/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MaddoShared/packages.config b/MaddoShared.backup/packages.config similarity index 100% rename from MaddoShared/packages.config rename to MaddoShared.backup/packages.config diff --git a/MaddoShared.backup/upgrade.backup b/MaddoShared.backup/upgrade.backup new file mode 100644 index 0000000..3d26f1f --- /dev/null +++ b/MaddoShared.backup/upgrade.backup @@ -0,0 +1 @@ +Backup created at 1615021651 (06/03/2021 09:07:31 +00:00) \ No newline at end of file diff --git a/MaddoShared/ImageCreationStuff.cs b/MaddoShared/ImageCreationStuff.cs index 277994f..439f3dc 100644 --- a/MaddoShared/ImageCreationStuff.cs +++ b/MaddoShared/ImageCreationStuff.cs @@ -149,32 +149,12 @@ namespace MaddoShared }, maxDegreeOfParallelism: threads, false, cancellationToken); - //var throttler = new SemaphoreSlim(initialCount: threads); - //foreach (var fileData in dataToProcess) - //{ - // await throttler.WaitAsync(); - // allTasks.Add(Task.Factory.StartNew(() => { - // try - // { - // new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread( - // fileData.File.Name); - // } - // finally - // { - // throttler.Release(); - // } - // }, CancellationToken.None, TaskCreationOptions.None, scheduler)); - //} - - //await Task.WhenAll(test); } else { - var asdf = SplitList(dataToProcess.ToList(), dataToProcess.Count()).ToList(); - //var sadf = asdf[0]; - - //var sadf1 = asdf[1]; + var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList(); + foreach (var sdaf in asdf) { @@ -197,22 +177,9 @@ namespace MaddoShared - //foreach (var chunk in asdf) - //{ - // await Task.WhenAll(chunk); - // GC.Collect(); - // //GC.WaitForPendingFinalizers(); - // //GC.Collect(); - //} - } } - //foreach (var task in test) - //{ - // await task; - //} - } diff --git a/MaddoShared/ImageCreatorSharp.cs b/MaddoShared/ImageCreatorSharp.cs index 13f0d8e..84a4c21 100644 --- a/MaddoShared/ImageCreatorSharp.cs +++ b/MaddoShared/ImageCreatorSharp.cs @@ -150,23 +150,22 @@ public class ImageCreatorSharp { using (var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName)) { - ExifReader.Orientations finalOrientation; - var rotation = img.Metadata?.ExifProfile?.GetValue(ExifTag.Orientation); - if (rotation == null) + _orientation = ExifReader.Orientations.TopLeft; + + IExifValue rotation = null; + + var found = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.Orientation, out rotation) ?? false; + + if (found) { - finalOrientation = ExifReader.Orientations.TopLeft; - } - else - { - finalOrientation = (ExifReader.Orientations)rotation.Value; + _orientation = (ExifReader.Orientations)rotation.ToInt32(); } - _orientation = finalOrientation; - - var creation = img.Metadata?.ExifProfile?.GetValue(ExifTag.DateTime); - if (creation != null) + IExifValue date = null; + var creationFound = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.DateTime, out date) ?? false; + if (creationFound) { - var succ = DateTime.TryParse(creation.Value, out var crDate); + var succ = DateTime.TryParse(date.ToString(), out var crDate); if (succ) { _creationDate = crDate; diff --git a/MaddoShared/MaddoShared.csproj b/MaddoShared/MaddoShared.csproj index 03c762e..4063086 100644 --- a/MaddoShared/MaddoShared.csproj +++ b/MaddoShared/MaddoShared.csproj @@ -1,101 +1,30 @@ - - - + - Debug - AnyCPU - {AEBFE9E3-277C-4A7B-8448-145D1B11998B} + net9.0-windows Library - Properties - MaddoShared - MaddoShared - v4.7.2 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 + false + true + true + x64 - - ..\packages\AsyncEnumerator.4.0.2\lib\net461\AsyncEnumerable.dll - - - ..\packages\Ben.Demystifier.0.3.0\lib\net45\Ben.Demystifier.dll - - - ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll - - - ..\packages\SixLabors.ImageSharp.1.0.3\lib\net472\SixLabors.ImageSharp.dll - - - - ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll - - - ..\packages\System.Collections.Immutable.5.0.0\lib\net461\System.Collections.Immutable.dll - - - - - ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll - - - - ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll - - - ..\packages\System.Reflection.Metadata.5.0.0\lib\net461\System.Reflection.Metadata.dll - - - ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll - - - ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll - - - - - - - - - - ..\packages\Z.ExtensionMethods.2.1.1\lib\net45\Z.ExtensionMethods.dll - + + + + + + + + + + + + + all + + - - - - - - + - - - {44465926-240d-473f-90b8-786ba4384406} - CatalogVbLib - - - - - - - \ No newline at end of file diff --git a/WPFCatalog/App.config b/WPFCatalog/App.config index ff1c544..ca0daff 100644 --- a/WPFCatalog/App.config +++ b/WPFCatalog/App.config @@ -20,11 +20,11 @@ - + - + @@ -38,6 +38,14 @@ + + + + + + + + diff --git a/WPFCatalog/Controls/GeneralSettingsControl.xaml b/WPFCatalog/Controls/GeneralSettingsControl.xaml index 9f511c8..bfa637d 100644 --- a/WPFCatalog/Controls/GeneralSettingsControl.xaml +++ b/WPFCatalog/Controls/GeneralSettingsControl.xaml @@ -7,10 +7,24 @@ xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks" + xmlns:System="clr-namespace:System;assembly=mscorlib" + xmlns:catalogLib="clr-namespace:CatalogLib;assembly=CatalogLib" mc:Ignorable="d" d:DesignHeight="900" d:DesignWidth="500" d:DataContext="{d:DesignInstance wpfCatalog:MainWindowViewModel}" > + + + + + + + + + + + + @@ -65,6 +79,7 @@ + @@ -80,6 +95,7 @@ + @@ -112,6 +128,8 @@ + + @@ -125,16 +143,19 @@ - diff --git a/WPFCatalog/Controls/TextSettingsControl.xaml b/WPFCatalog/Controls/TextSettingsControl.xaml index 27566c6..7d7ac19 100644 --- a/WPFCatalog/Controls/TextSettingsControl.xaml +++ b/WPFCatalog/Controls/TextSettingsControl.xaml @@ -6,12 +6,24 @@ xmlns:wpfCatalog="clr-namespace:WPFCatalog" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" - mc:Ignorable="d" + xmlns:System="clr-namespace:System;assembly=mscorlib" + xmlns:catalogLib="clr-namespace:CatalogLib;assembly=CatalogLib" + mc:Ignorable="d" d:DesignHeight="900" d:DesignWidth="500" d:DataContext="{d:DesignInstance wpfCatalog:MainWindowViewModel}" > + + + + + + + + + + @@ -42,8 +54,8 @@ Text="{Binding FontName}" > - - + + @@ -81,28 +93,8 @@ - - - - - - - - - - - - - - - - - - + + @@ -117,9 +109,19 @@ @@ -135,28 +137,28 @@ - + diff --git a/WPFCatalog/MainWindow.xaml b/WPFCatalog/MainWindow.xaml index e9fb26c..c7cd8fe 100644 --- a/WPFCatalog/MainWindow.xaml +++ b/WPFCatalog/MainWindow.xaml @@ -24,7 +24,7 @@ - + @@ -67,7 +67,7 @@ - + @@ -182,12 +182,15 @@ - - + + - +