public Size MagicScalerResize()
        {
            // stride is width * bytes per pixel (3 for BGR), rounded up to the nearest multiple of 4
            const uint stride  = ResizedWidth * 3u + 3u & ~3u;
            const uint bufflen = ResizedHeight * stride;

            var settings = new ProcessImageSettings
            {
                Width   = ResizedWidth,
                Height  = ResizedHeight,
                Sharpen = false
            };

            using (var pixels = new TestPatternPixelSource(Width, Height, PixelFormats.Bgr24bpp))
                using (var pipeline = MagicImageProcessor.BuildPipeline(pixels, settings))
                {
                    var rect   = new Rectangle(0, 0, ResizedWidth, ResizedHeight);
                    var buffer = ArrayPool <byte> .Shared.Rent((int)bufflen);

                    pipeline.PixelSource.CopyPixels(rect, (int)stride, new Span <byte>(buffer, 0, (int)bufflen));
                    ArrayPool <byte> .Shared.Return(buffer);

                    return(rect.Size);
                }
        }
Example #2
0
        private Stream MagicScaleResize(Stream stream)
        {
            var outStream = new MemoryStream(1024);

            const int quality = 75;

            var settings = new ProcessImageSettings()
            {
                Width = this._width,

                Height = this._height,

                ResizeMode = CropScaleMode.Crop,

                SaveFormat = fileFormat,

                JpegQuality = quality,

                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            MagicImageProcessor.ProcessImage(stream, outStream, settings);

            return(outStream);
        }
Example #3
0
        public FileInfo ResizeTo(FileInfo toResize, int width, int quality, string imageTypeString, bool addSizeString,
                                 IProgress <string> progress)
        {
            if (!toResize.Exists)
            {
                return(null);
            }

            var newFile = Path.Combine(toResize.Directory?.FullName ?? string.Empty, $"{Guid.NewGuid()}.jpg");

            var newFileInfo = new FileInfo(newFile);

            if (newFileInfo.Exists)
            {
                newFileInfo.Delete();
            }

            var settings = new ProcessImageSettings {
                Width = width, JpegQuality = quality
            };

            using var outStream = new FileStream(newFileInfo.FullName, FileMode.Create);
            var results = MagicImageProcessor.ProcessImage(toResize.FullNameWithLongFilePrefix(), outStream, settings);

            outStream.Dispose();

            var finalFileName = Path.Combine(toResize.Directory?.FullName ?? string.Empty,
                                             $"{Path.GetFileNameWithoutExtension(toResize.Name)}--{imageTypeString}{(addSizeString ? $"--{width}w--{results.Settings.Height}h" : string.Empty)}.jpg");

            FileManagement.MoveFileAndLog(newFileInfo.FullName, finalFileName);

            newFileInfo = new FileInfo(finalFileName);

            return(newFileInfo);
        }
Example #4
0
 private void ConvertPendulumArtwork(DirectoryInfo destinationPath, string orgName, FileInfo imageFile,
                                     ProcessImageSettings settings, string zibFilename)
 {
     settings.Width             = 347;
     settings.Height            = 444;
     settings.JpegSubsampleMode = ChromaSubsampleMode.Default;
     _imageRepo.ConvertImage(destinationPath, imageFile, orgName, settings, zibFilename);
 }
Example #5
0
 private void ConvertNormalArtwork(DirectoryInfo destinationPath, string orgName, FileInfo imageFile,
                                   ProcessImageSettings settings, string zibFilename)
 {
     settings.Width             = 304;
     settings.Height            = 304;
     settings.JpegSubsampleMode = ChromaSubsampleMode.Subsample420;
     _imageRepo.ConvertImage(destinationPath, imageFile, orgName, settings, zibFilename);
 }
Example #6
0
    private void MinifyImage(string source, string destination)
    {
        var settings = new ProcessImageSettings {
            Width = Consts.ImageWidth
        };

        using var outStream = new FileStream(destination, FileMode.CreateNew);
        MagicImageProcessor.ProcessImage(source, outStream, settings);
    }
Example #7
0
        public static void Resize(Stream inputStream, Stream outputStream, int oldWidth, int oldHeight, int size = DefaultThumbnailSize)
        {
            var scaled = ScaledSize(oldWidth, oldHeight, size);

            var settings = new ProcessImageSettings()
            {
                Width             = scaled.width,
                Height            = scaled.height,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = Quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            MagicImageProcessor.ProcessImage(inputStream, outputStream, settings);
        }
        public void SaveImage(int ID, IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                // Empty file
                string defaultFileName = "default.png";
                string sourcePath      = Path.Combine(_hostingEnv.WebRootPath + @"\img\temp", defaultFileName);

                var ext      = Path.GetExtension(Path.Combine(sourcePath, defaultFileName));
                var fileName = ID + ext;

                string targetPath = Path.Combine(_hostingEnv.WebRootPath + @"\img\products", fileName);

                File.Copy(sourcePath, targetPath);
            }
            else
            {
                var fileName = ID + Path.GetExtension(file.FileName);
                fileName = _hostingEnv.WebRootPath + $@"\img\temp\{fileName}";

                using (FileStream fs = File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }

                const int size = 160;

                var path            = fileName;
                var outputDirectory = string.Empty;
                outputDirectory = _hostingEnv.WebRootPath + $@"\img\products";

                var settings = new ProcessImageSettings()
                {
                    Width      = size,
                    Height     = size,
                    ResizeMode = CropScaleMode.Max,
                    SaveFormat = FileFormat.Png
                };

                using (var output = new FileStream(OutputPath(path, outputDirectory), FileMode.Create))
                {
                    MagicImageProcessor.ProcessImage(path, output, settings);
                    File.Delete(path);
                }
            }
        }
Example #9
0
        public void MagicScalerResize(string input)
        {
            var settings = new ProcessImageSettings()
            {
                Width             = ThumbnailSize,
                Height            = ThumbnailSize,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = Quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            using (var output = new FileStream(OutputPath(input, MagicScaler), FileMode.Create))
            {
                MagicImageProcessor.ProcessImage(input, output, settings);
            }
        }
        internal static void MagicScalerResize(string path, int size, string outputDirectory)
        {
            var settings = new ProcessImageSettings()
            {
                Width             = size,
                Height            = size,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = Quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            using (var output = new FileStream(OutputPath(path, outputDirectory, MagicScaler), FileMode.Create))
            {
                MagicImageProcessor.ProcessImage(path, output, settings);
            }
        }
Example #11
0
        public void Test()
        {
            using (FileStream inputStream = File.OpenRead(@"Content\landscape-4665051.small.jpg"))
                using (var originalImage = new Bitmap(inputStream))
                    using (var outputStream = File.Create(@"Content\landscape-4665051.resized.jpg"))
                    {
                        int width  = 1140;
                        var ratio  = (float)width / originalImage.Width;
                        int height = Convert.ToInt32(originalImage.Height * ratio);

                        var settings = new ProcessImageSettings
                        {
                            Width = 1140
                        };

                        inputStream.Seek(0, SeekOrigin.Begin);
                        var result = MagicImageProcessor.ProcessImage(inputStream, outputStream, settings);
                    }
        }
        public (bool Saved, string FileName) SaveImage(string id, IFormFile picture)
        {
            try
            {
                var settings = new ProcessImageSettings()
                {
                    Height      = 75,
                    Width       = 75,
                    ResizeMode  = CropScaleMode.Crop,
                    SaveFormat  = FileFormat.Jpeg,
                    JpegQuality = 100
                };

                var savePath = Path.Combine(_env.ContentRootPath, _userImages, id);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                var fileName  = $"img_{CreateFileName()}.jpg";
                var finalPath = Path.Combine(savePath, fileName);

                var currentImage = Directory.GetFiles(savePath).FirstOrDefault();

                using (var output = new FileStream(finalPath, FileMode.Create))
                {
                    MagicImageProcessor.ProcessImage(picture.OpenReadStream(), output, settings);
                }

                if (!IsNullOrEmpty(currentImage))
                {
                    File.Delete(currentImage);
                }

                return(true, fileName);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);

                return(false, $"Error: {e.Message}");
            }
        }
Example #13
0
        public static string ResizeImageFromByte(byte[] buffer, int size)
        {
            const int quality  = 100;
            var       settings = new ProcessImageSettings()
            {
                Width             = size,
                Height            = size,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            using var imgStream = new MemoryStream(buffer);
            using var output    = new MemoryStream();
            MagicImageProcessor.ProcessImage(imgStream, output, settings);
            var t = ReadToEnd(output);

            return(ImageToSrc(t));
        }
Example #14
0
        public static async Task ResizeImageToFile(string path, IFormFile file)
        {
            const int size     = Constants.ImageSize;
            const int quality  = 100;
            var       settings = new ProcessImageSettings()
            {
                Width             = size,
                Height            = size,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };

            await using var imgStream = new MemoryStream();
            await using var output    = new FileStream(path, FileMode.Create);
            await file.CopyToAsync(imgStream);

            imgStream.Position = 0;
            MagicImageProcessor.ProcessImage(imgStream, output, settings);
        }
Example #15
0
        public void MagicScalerResize()
        {
            // stride is width * bytes per pixel (3 for BGR), rounded up to the nearest multiple of 4
            const uint stride  = ResizedWidth * 3u + 3u & ~3u;
            const uint bufflen = ResizedHeight * stride;

            var pixels   = new TestPatternPixelSource(Width, Height, PixelFormats.Bgr24bpp);
            var settings = new ProcessImageSettings
            {
                Width  = ResizedWidth,
                Height = ResizedHeight
            };

            using (var pipeline = MagicImageProcessor.BuildPipeline(pixels, settings))
            {
                var rect   = new System.Drawing.Rectangle(0, 0, ResizedWidth, ResizedHeight);
                var buffer = Marshal.AllocHGlobal((int)bufflen);
                pipeline.PixelSource.CopyPixels(rect, stride, bufflen, buffer);
                Marshal.FreeHGlobal(buffer);
            }
        }
        /// <summary>Updates a cache file path by appending the settings hash and optionally output size to the original file name.</summary>
        /// <param name="newPath">The undecorated cache file path.</param>
        /// <param name="settings">The processing settings.</param>
        /// <param name="includeResolution">True to include the output width and height in the file name, false to omit.</param>
        /// <returns>The updated cache file path.</returns>
        protected string WrapFileName(string newPath, ProcessImageSettings settings, bool includeResolution = true)
        {
            string file = VirtualPathUtility.GetFileName(newPath);
            var    sb   = new StringBuilder(128);

            sb.Append(VirtualPathUtility.GetDirectory(newPath).Substring(1));
            sb.Append('/');
            sb.Append(settings.GetCacheHash());
            sb.Append('.');
            sb.Append(Path.GetFileNameWithoutExtension(file));

            if (includeResolution)
            {
                sb.AppendFormat(".{0}x{1}", settings.Width, settings.Height);
            }

            sb.Append('.');
            sb.Append(settings.SaveFormat.GetFileExtension(Path.GetExtension(file)));

            return(VirtualPathUtility.Combine(cacheRoot, sb.ToString()));
        }
Example #17
0
        public Task <string> CreateThumbnailAsync(byte[] content, string fileName)
        {
            var frameInfo = ImageFileInfo.Load(content).Frames.First();

            var settings = new ProcessImageSettings
            {
                Width      = frameInfo.Width >= frameInfo.Height ? THUMBNAIL_SIZE : 0,
                Height     = frameInfo.Height > frameInfo.Width ? THUMBNAIL_SIZE : 0,
                HybridMode = HybridScaleMode.Off,
                ResizeMode = CropScaleMode.Contain
            };

            var newFileName = GetUniqueFileName(GetThumbnailFileName(fileName));

            using (var stream = GetFileStream(newFileName, FileMode.Create))
            {
                MagicImageProcessor.ProcessImage(content, stream, settings);
            }

            return(Task.FromResult(newFileName));
        }
Example #18
0
        public static bool ResizeImageToFileSrc(string src, string path)
        {
            const int size     = Constants.ImageSize;
            const int quality  = 100;
            var       settings = new ProcessImageSettings()
            {
                Width             = size,
                Height            = size,
                ResizeMode        = CropScaleMode.Max,
                SaveFormat        = FileFormat.Jpeg,
                JpegQuality       = quality,
                JpegSubsampleMode = ChromaSubsampleMode.Subsample420
            };
            var buffer = FullSizeToByte(src);

            using var imgStream = new MemoryStream(buffer);
            using var output    = new MemoryStream();
            MagicImageProcessor.ProcessImage(imgStream, output, settings);
            var t = ReadToEnd(output);

            return(ByteArrayToFile(path, t));
        }
Example #19
0
        public void ConvertImage(DirectoryInfo destinationPath, FileInfo imageFile, string orgName,
                                 ProcessImageSettings settings, string zibFilename)
        {
            var outputFolder = new DirectoryInfo(Path.Combine(Constants.ResourceOutputFolderName, zibFilename));
            var filePath     = Path.Combine(outputFolder.FullName, orgName);

            var imageLocation = imageFile.FullName;

            try
            {
                CreatePathIfNotExists(outputFolder);

                using (var outStream = new FileStream(filePath, FileMode.Create))
                {
                    MagicImageProcessor.ProcessImage(imageLocation, outStream, settings);
                }
            }
            catch (Exception e)
            {
                _logger.LogException(e);
            }
        }
        public static async Task <BitmapSource> InMemoryThumbnailFromFile(FileInfo file, int width, int quality)
        {
            await using var fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
            await using var outStream  = new MemoryStream();

            var settings = new ProcessImageSettings {
                Width = width, JpegQuality = quality
            };

            MagicImageProcessor.ProcessImage(fileStream, outStream, settings);

            outStream.Position = 0;

            var uiImage = new BitmapImage();

            uiImage.BeginInit();
            uiImage.CacheOption  = BitmapCacheOption.OnLoad;
            uiImage.StreamSource = outStream;
            uiImage.EndInit();
            uiImage.Freeze();

            return(uiImage);
        }
Example #21
0
        public void ConvertAll(IEnumerable <Artwork> artworks)
        {
            var  artworkList     = artworks.ToList();
            var  destinationPath = _resourceRepo.GetOutputPath();
            long progress        = 0;
            var  numberOfArtwork = artworkList.ToList().Count();

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            _logger.LogInformation(Localization.InformationConvertingImages);

            var settings = new ProcessImageSettings
            {
                SaveFormat  = FileFormat.Jpeg,
                JpegQuality = 92,
            };

            foreach (var artwork in artworkList)
            {
                var imageFile = artwork.ReplacementImageFile;
                if (artwork.IsPendulum)
                {
                    ConvertPendulumArtwork(destinationPath, artwork.GameImageFileName, imageFile, settings, artwork.ZibFilename);
                }
                else
                {
                    ConvertNormalArtwork(destinationPath, artwork.GameImageFileName, imageFile, settings, artwork.ZibFilename);
                }
                _logger.LogInformation(Localization.InformationProcessingProgress(progress, numberOfArtwork, artwork.GameImageCardName));
                progress++;
            }

            stopwatch.Stop();
            _logger.LogInformation(Localization.InformationProcessingDone(numberOfArtwork, MiliToSec(stopwatch.ElapsedMilliseconds)));
        }
Example #22
0
        private static async Task process(TaskCompletionSource <ArraySegment <byte> > tcs, string reqPath, string cachePath, ProcessImageSettings s)
        {
            try
            {
                if (reqPath == WebRSizeModule.NotFoundPath)
                {
                    using (await enterWorkQueueAsync())
                        using (var oimg = new MemoryStream(8192))
                        {
                            GdiImageProcessor.CreateBrokenImage(oimg, s);
                            oimg.Position = 0;
                            saveResult(tcs, oimg, cachePath, DateTime.MinValue);
                            return;
                        }
                }

                var vpp      = HostingEnvironment.VirtualPathProvider;
                var vppAsync = vpp as CachingAsyncVirtualPathProvider;

                var file = vppAsync != null ? await vppAsync.GetFileAsync(reqPath) : vpp.GetFile(reqPath);

                var afile = file as AsyncVirtualFile;

                var lastWrite = afile?.LastModified ?? DateTime.MinValue;
                if (lastWrite == DateTime.MinValue && mpbvfType.Value.IsAssignableFrom(file.GetType()))
                {
                    lastWrite = File.GetLastWriteTimeUtc(HostingEnvironment.MapPath(reqPath));
                }

                using (var iimg = afile != null ? await afile.OpenAsync() : file.Open())
                    using (await enterWorkQueueAsync())
                        using (var oimg = new MemoryStream(16384))
                        {
                            MagicImageProcessor.ProcessImage(iimg, oimg, s);

                            saveResult(tcs, oimg, cachePath, lastWrite);
                        }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);

                tdic.TryRemove(cachePath, out _);
            }
        }
Example #23
0
        private async Task mapRequest(object sender, EventArgs e)
        {
            var ctx = ((HttpApplication)sender).Context;
            var vpp = HostingEnvironment.VirtualPathProvider;

            string path   = ctx.Request.Path;
            bool   exists = vpp is CachingAsyncVirtualPathProvider vppAsync ? await vppAsync.FileExistsAsync(path) : vpp.FileExists(path);

            var folderConfig = imageFolders.FirstOrDefault(f => ctx.Request.Path.StartsWith(f.Path, StringComparison.OrdinalIgnoreCase));

            if (folderConfig is null)
            {
                return;
            }

            var dic = ctx.Request.QueryString.ToDictionary();

            if (folderConfig.DefaultSettings.Count > 0)
            {
                dic = folderConfig.DefaultSettings.ToDictionary().Coalesce(dic);
            }

            var s = ProcessImageSettings.FromDictionary(dic);

            int rw = s.Width, rh = s.Height;

            if (double.TryParse(dic.GetValueOrDefault("devicepixelratio") ?? dic.GetValueOrDefault("dpr"), out double dpr))
            {
                dpr      = dpr.Clamp(1d, 5d);
                s.Width  = (int)Math.Floor(s.Width * dpr);
                s.Height = (int)Math.Floor(s.Height * dpr);
            }

            if (exists && s.IsEmpty && !folderConfig.ForceProcessing)
            {
                return;
            }

            var ifi = default(ImageFileInfo);

            if (!exists)
            {
                ctx.Response.TrySkipIisCustomErrors = true;
                ctx.Response.StatusCode             = 404;
                path = NotFoundPath;

                if (s.Width <= 0 && s.Height <= 0)
                {
                    s.Width = s.Height = 100;
                }

                ifi          = new ImageFileInfo(s.Width > 0 ? s.Width : s.Height, s.Height > 0 ? s.Height : s.Width);
                s.SaveFormat = FileFormat.Png;
            }

            ifi = ifi ?? await CacheHelper.GetImageInfoAsync(path);

            s.NormalizeFrom(ifi);

            if (!folderConfig.AllowEnlarge)
            {
                var frame = ifi.Frames[s.FrameIndex];
                if (s.Width > frame.Width)
                {
                    s.Width  = frame.Width;
                    s.Height = 0;
                    s.Fixup(frame.Width, frame.Height);
                }
                if (s.Height > frame.Height)
                {
                    s.Width  = 0;
                    s.Height = frame.Height;
                    s.Fixup(frame.Width, frame.Height);
                }
            }

            if (s.Width * s.Height > folderConfig.MaxPixels)
            {
                ctx.Response.StatusCode = 400;
                ctx.ApplicationInstance.CompleteRequest();
                return;
            }

            if (dpr > 0d && !dic.ContainsKey("quality") && !dic.ContainsKey("q"))
            {
                dpr            = Math.Max(Math.Max((double)s.Width / (rw > 0 ? rw : s.Width), (double)s.Height / (rh > 0 ? rh : s.Height)), 1d);
                s.JpegQuality -= (int)Math.Round((dpr - 1d) * 10);
            }

            string cacheVPath = namingStrategy.Value.GetCacheFilePath(path, s);
            string cachePath  = HostingEnvironment.MapPath(cacheVPath);

            if (File.Exists(cachePath))
            {
                ctx.RewritePath(cacheVPath, null, string.Empty, false);
                return;
            }

            if (path == NotFoundPath)
            {
                ctx.RewritePath(NotFoundPath);
            }

            ctx.Items[ProcessImageSettingsKey] = s;
            ctx.Items[CachePathKey]            = cachePath;
            ctx.RemapHandler(handler);
        }
    private void RunTests(string inFile)
    {
        bool breakup    = false;
        var  inFileInfo = new FileInfo(inFile);

        var settings = new ProcessImageSettings {
            Width       = 400,
            Height      = 0,
            Sharpen     = false,
            JpegQuality = 90,
            ResizeMode  = CropScaleMode.Crop,
            SaveFormat  = FileFormat.Jpeg,
            //BlendingMode = GammaMode.sRGB,
            //HybridMode = HybridScaleMode.Turbo,
            //Interpolation = InterpolationSettings.Cubic,
            //MatteColor = Color.Pink,
            //Anchor = CropAnchor.Bottom | CropAnchor.Right,
        };

        var inImage = File.ReadAllBytes(inFileInfo.FullName);

        new ImageResizer.Plugins.FastScaling.FastScalingPlugin().Install(ImageResizer.Configuration.Config.Current);
        //new ImageResizer.Plugins.PrettyGifs.PrettyGifs().Install(ImageResizer.Configuration.Config.Current);

        int speed = settings.HybridMode == HybridScaleMode.Off ? -2 : settings.HybridMode == HybridScaleMode.FavorQuality ? 0 : settings.HybridMode == HybridScaleMode.FavorSpeed ? 2 : 4;
        //string filter = settings.Interpolation.Equals(InterpolationSettings.Cubic) ? "cubic" : settings.Interpolation.Equals(InterpolationSettings.Linear) ? "linear" : "";
        string anchor1 = (settings.Anchor & CropAnchor.Top) == CropAnchor.Top ? "top" : (settings.Anchor & CropAnchor.Bottom) == CropAnchor.Bottom ? "bottom" : "middle";
        string anchor2 = (settings.Anchor & CropAnchor.Left) == CropAnchor.Left ? "left" : (settings.Anchor & CropAnchor.Right) == CropAnchor.Right ? "right" : "center";
        string bgcolor = settings.MatteColor == Color.Empty ? null : $"&bgcolor={settings.MatteColor.ToKnownColor()}";
        string quality = settings.JpegQuality == 0 ? null : $"&quality={settings.JpegQuality}";
        string format  = settings.SaveFormat == FileFormat.Png8 ? "gif" : settings.SaveFormat.ToString();
        var    irs     = new ResizeSettings($"width={settings.Width}&height={settings.Height}&mode={settings.ResizeMode}&anchor={anchor1}{anchor2}&autorotate=true{bgcolor}&scale=both&format={format}&quality={settings.JpegQuality}&fastscale=true&down.speed={speed}");

        Func <Stream> gdi = () => { using (var msi = new MemoryStream(inImage)) { var mso = new MemoryStream(16384); GdiImageProcessor.ProcessImage(msi, mso, settings); return(mso); } };
        Func <Stream> mag = () => { using (var msi = new MemoryStream(inImage)) { var mso = new MemoryStream(16384); MagicImageProcessor.ProcessImage(msi, mso, settings); return(mso); } };
        Func <Stream> wic = () => { using (var msi = new MemoryStream(inImage)) { var mso = new MemoryStream(16384); WicImageProcessor.ProcessImage(msi, mso, settings); return(mso); } };
        Func <Stream> irf = () => { using (var msi = new MemoryStream(inImage)) { var mso = new MemoryStream(16384); ImageBuilder.Current.Build(msi, mso, irs); return(mso); } };

        try
        {
            var irfimg = Task.Run(irf).Result;
            var gdiimg = Task.Run(gdi).Result;
            var wicimg = Task.Run(wic).Result;
            var magimg = Task.Run(mag).Result;

            File.WriteAllBytes($"imgirf.{settings.SaveFormat.ToString().ToLower()}", ((MemoryStream)irfimg).ToArray());
            File.WriteAllBytes($"imggdi.{settings.SaveFormat.ToString().ToLower()}", ((MemoryStream)gdiimg).ToArray());
            File.WriteAllBytes($"imgmag.{settings.SaveFormat.ToString().ToLower()}", ((MemoryStream)magimg).ToArray());
            File.WriteAllBytes($"imgwic.{settings.SaveFormat.ToString().ToLower()}", ((MemoryStream)wicimg).ToArray());

            irfimg.Position = gdiimg.Position = wicimg.Position = magimg.Position = 0;

            img1.Source = BitmapFrame.Create(irfimg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            img2.Source = BitmapFrame.Create(gdiimg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            img3.Source = BitmapFrame.Create(wicimg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            img4.Source = BitmapFrame.Create(magimg, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

            if (breakup)
            {
                GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                GC.Collect(2, GCCollectionMode.Forced, true);
                Thread.Sleep(1000);
            }

            runTest(irf, $"FastScaling Auto {(speed == -2 ? null : "(speed=" + speed + ")")}", lbl1, breakup);
            runTest(gdi, $"GDI+ HighQualityBicubic {(settings.HybridMode == HybridScaleMode.Off ? null : " Hybrid (" + settings.HybridMode + ")")}", lbl2, breakup);
            runTest(wic, $"WIC Fant", lbl3, breakup);
            runTest(mag, $"MagicScaler {(settings.HybridMode == HybridScaleMode.Off ? null : " Hybrid (" + settings.HybridMode + ")")}", lbl4, breakup);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
        static void Main(string[] args)
        {
            const int thumbnailWidth  = 156;
            const int thumbnailHeight = 156;
            const int imageWidth      = 712;
            const int imageHeight     = 650;

            const string path      = @"C:\DerinSIS\DerinBilgiGorseller\";
            var          thumbPath = Path.Combine(path, "Thumbs");
            var          imagePath = Path.Combine(path, "Images");

            // G{0} -> Model klasörü
            // V{0} -> Model klasörü içindeki ürünler
            //U -> Ürün klasörü

            var pictures  = new List <PictureInfoModel>();
            var directory = new DirectoryInfo(path);

            // foreach (var item in directory.GetFiles().Where(x => x.LastWriteTime >= DateTime.Now.AddDays(-2)))
            foreach (var folder in directory.GetFileSystemInfos())
            {
                if (folder.Name.StartsWith("G"))
                {
                    //Model klasörü içinden ürünleri ayrıştır
                    if (int.TryParse(folder.Name.Replace("G", ""), out var modelId))
                    {
                        var subDirectory = new DirectoryInfo(Path.Combine(path, folder.FullName));
                        var counter      = 0;
                        foreach (var productInModel in subDirectory.GetFiles())
                        {
                            var productName = productInModel.Name.Split('_')[0].ToString().Replace("V", "");
                            if (int.TryParse(productName, out var productId))
                            {
                                pictures.Add(new PictureInfoModel
                                {
                                    FileName      = productInModel.FullName,
                                    LastWriteTime = productInModel.LastWriteTime,
                                    ModelId       = modelId,
                                    ProductId     = productId,
                                    PathName      = Path.Combine(@"\", folder.Name, productInModel.Name),
                                    Sequence      = counter
                                });
                                counter++;
                            }
                        }
                    }
                }

                if (folder.Name.StartsWith("U"))
                {
                    if (int.TryParse(folder.Name.Replace("U", ""), out var productId))
                    {
                        var subDirectory = new DirectoryInfo(Path.Combine(path, folder.FullName));
                        var counter      = 0;
                        foreach (var productInModel in subDirectory.GetFiles())
                        {
                            pictures.Add(new PictureInfoModel
                            {
                                FileName      = productInModel.FullName,
                                LastWriteTime = productInModel.LastWriteTime,
                                ModelId       = 0,
                                ProductId     = productId,
                                PathName      = Path.Combine(@"\", folder.Name, productInModel.Name),
                                Sequence      = counter
                            });
                            counter++;
                        }
                    }
                }
            }

            pictures = pictures.GroupBy(x => x.ProductId)
                       .SelectMany(x => x.Select((y, i) => new { y, i }))
                       .Select(x => new PictureInfoModel
            {
                ProductId     = x.y.ProductId,
                FileName      = x.y.FileName,
                LastWriteTime = x.y.LastWriteTime,
                ModelId       = x.y.ModelId,
                PathName      = x.y.PathName,
                Sequence      = x.i + 1
            }).ToList();


            // foreach (var item in pictures.OrderBy(x => x.ProductId))
            // {
            //     System.Console.WriteLine(item);
            // }

            if (pictures.Any())
            {
                //Thumbnails
                if (!Directory.Exists(thumbPath))
                {
                    Directory.CreateDirectory(thumbPath);
                }

                var imageSettings = new ProcessImageSettings
                {
                    Width             = thumbnailWidth,
                    Height            = thumbnailHeight,
                    ResizeMode        = CropScaleMode.Max,
                    SaveFormat        = FileFormat.Jpeg,
                    JpegQuality       = 100,
                    JpegSubsampleMode = ChromaSubsampleMode.Subsample420
                };

                foreach (var item in pictures)
                {
                    using var outStream = new FileStream(Path.Combine(thumbPath, item.OutputName), FileMode.Create);
                    MagicImageProcessor.ProcessImage(item.FileName, outStream, imageSettings);
                }

                //Standart Images
                if (!Directory.Exists(imagePath))
                {
                    Directory.CreateDirectory(imagePath);
                }

                imageSettings.Width  = imageWidth;
                imageSettings.Height = imageHeight;

                foreach (var item in pictures)
                {
                    using var outStream = new FileStream(Path.Combine(imagePath, item.OutputName), FileMode.Create);
                    MagicImageProcessor.ProcessImage(item.FileName, outStream, imageSettings);
                }

                //Write last run time to drn2Table -> value 9999;
                //Save image info to Database
                //check existing row
                var dbModel = new
                {
                    ProductId        = 1,
                    ModelId          = 1,
                    ThumbnailName    = Path.Combine(thumbPath, "Image-Name"),
                    ImageName        = Path.Combine(imagePath, "Image-Name"),
                    Sequence         = 1,
                    OriginalFileName = "",
                    LastWriteTime    = DateTime.Now
                };
            }
        }
        /// <inheritdoc />
        public override string GetCacheFilePath(string inPath, ProcessImageSettings settings)
        {
            string hash = CacheHash.Create(inPath);

            return(WrapFileName($"/{hash[0]}{hash[1]}/{hash[2]}{hash[3]}/{VirtualPathUtility.GetFileName(inPath)}", settings));
        }
 /// <inheritdoc />
 public override string GetCacheFilePath(string inPath, ProcessImageSettings settings) => WrapFileName(inPath, settings);
 /// <inheritdoc />
 public abstract string GetCacheFilePath(string inPath, ProcessImageSettings settings);
Example #29
0
 internal ProcessImageResult(ProcessImageSettings settings, IEnumerable <PixelSourceStats> stats)
 {
     Settings = settings;
     Stats    = stats;
 }
Example #30
0
        private async Task mapRequest(object sender, EventArgs e)
        {
            var ctx      = ((HttpApplication)sender).Context;
            var vpp      = HostingEnvironment.VirtualPathProvider;
            var vppAsync = vpp as CachingAsyncVirtualPathProvider;

            string path   = ctx.Request.Path;
            bool   exists = vppAsync != null ? await vppAsync.FileExistsAsync(path) : vpp.FileExists(path);

            var folderConfig = imageFolders.FirstOrDefault(f => ctx.Request.Path.StartsWith(f.Path, StringComparison.OrdinalIgnoreCase));

            if (folderConfig == null)
            {
                return;
            }

            var dic = ctx.Request.QueryString.ToDictionary();

            if (folderConfig.DefaultSettings.Count > 0)
            {
                dic = folderConfig.DefaultSettings.ToDictionary().Coalesce(dic);
            }

            var s = ProcessImageSettings.FromDictionary(dic);

            if (exists && s.IsEmpty && !folderConfig.ForceProcessing)
            {
                return;
            }

            var ifi = default(ImageFileInfo);

            if (!exists)
            {
                ctx.Response.TrySkipIisCustomErrors = true;
                ctx.Response.StatusCode             = 404;
                path = NotFoundPath;

                if (s.Width <= 0 && s.Height <= 0)
                {
                    s.Width = s.Height = 100;
                }

                ifi = new ImageFileInfo(s.Width > 0 ? s.Width : s.Height, s.Height > 0 ? s.Height : s.Width);
            }

            ifi = ifi ?? await CacheHelper.GetImageInfoAsync(path);

            s.NormalizeFrom(ifi);

            if (!folderConfig.AllowEnlarge)
            {
                var frame = ifi.Frames[s.FrameIndex];
                if (s.Width > frame.Width)
                {
                    s.Width  = frame.Width;
                    s.Height = 0;
                    s.Fixup(frame.Width, frame.Height);
                }
                if (s.Height > frame.Height)
                {
                    s.Width  = 0;
                    s.Height = frame.Height;
                    s.Fixup(frame.Width, frame.Height);
                }
            }

            if (s.Width * s.Height > folderConfig.MaxPixels)
            {
                ctx.Response.StatusCode = 400;
                ctx.ApplicationInstance.CompleteRequest();
                return;
            }

            var cacheVPath = namingStrategy.Value.GetCacheFilePath(path, s);
            var cachePath  = HostingEnvironment.MapPath(cacheVPath);

            if (File.Exists(cachePath))
            {
                ctx.RewritePath(cacheVPath, null, string.Empty, false);
                return;
            }

            if (path == NotFoundPath)
            {
                ctx.RewritePath(NotFoundPath);
            }

            ctx.Items[ProcessImageSettingsKey] = s;
            ctx.Items[CachePathKey]            = cachePath;
            ctx.RemapHandler(handler);
        }