private async Task <string> UploadedFile(Post post)
        {
            string uniqueFileName = null;

            if (post.CoverImage != null)
            {
                string uploadsFolder = Path.Combine(env.WebRootPath, "uploads");

                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                uniqueFileName = Guid.NewGuid().ToString() + "_" + post.CoverImage.FileName;

                string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                using var fileStream = new FileStream(filePath, FileMode.Create);
                MagicImageProcessor.ProcessImage(post.CoverImage.OpenReadStream(), fileStream, ImageOptions());
                await post.CoverImage.CopyToAsync(fileStream);
            }
            return(uniqueFileName);
        }
예제 #2
0
        public async Task <string> SaveImage(IFormFile image)
        {
            try
            {
                var save_path = Path.Combine(_imagePath);
                if (!Directory.Exists(save_path))
                {
                    Directory.CreateDirectory(save_path);
                }

                //var fileName = image.FileName;
                var ext      = image.FileName.Substring(image.FileName.LastIndexOf('.'));
                var fileName = $"img_{DateTime.Now.ToString("dd-MM-yyyy-ss-HH-mm-ss")}{ext}";

                using (var fileStream = new FileStream(Path.Combine(save_path, fileName), FileMode.Create))
                {
                    //await image.CopyToAsync(fileStream);
                    MagicImageProcessor.ProcessImage(image.OpenReadStream(), fileStream, ImageOptions());
                }

                return(fileName);
            }
            catch (Exception x) { Console.WriteLine(x.Message); return("Error"); }
        }
예제 #3
0
        static void Main(string[] args)
        {
            string folder;

            do
            {
                Console.Clear();
                Console.WriteLine("Source Folder <empty to exit>: ");
                folder = Console.ReadLine();

                var fileList = Directory.GetFiles(folder);
                if (fileList.Length > 0)
                {
                    Console.WriteLine($"\t{fileList.Length} files available.");

                    Console.WriteLine($"Inform destination folder:");
                    string destination = Console.ReadLine();

                    if (string.IsNullOrEmpty(destination))
                    {
                        destination = Path.Combine("D:\\sandbox", (new DirectoryInfo(folder)).Name);
                        Console.WriteLine($"\tAssuming default Sandbox\\<folder>");
                    }

                    if (!Directory.Exists(destination))
                    {
                        Directory.CreateDirectory(destination);
                    }

                    foreach (var sourceFile in fileList)
                    {
                        using (var outStream = new FileStream(Path.Combine(destination, $"{Path.GetFileNameWithoutExtension(sourceFile)}_small.JPG"), FileMode.Create))
                        {
                            ImageFileInfo mi = new ImageFileInfo(sourceFile);

                            Console.SetCursorPosition(1, 10);
                            Console.Write($"\tReducing {Path.GetFileName(sourceFile)} => {Path.GetFileName(outStream.Name)} ");

                            if (mi.Frames[0].Height > mi.Frames[0].Width)
                            {
                                MagicImageProcessor.ProcessImage(sourceFile, outStream, new ProcessImageSettings {
                                    Width = 2000, Height = 2992
                                });
                            }
                            else
                            {
                                MagicImageProcessor.ProcessImage(sourceFile, outStream, new ProcessImageSettings {
                                    Width = 2992, Height = 1800
                                });
                            }

                            mi = null;
                            //Console.ForegroundColor = ConsoleColor.Green;
                            //Console.SetCursorPosition(1, 10);
                            //Console.Write($"[OK]");
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"\t No files selected, closing tool.");
                }
            }while (!string.IsNullOrEmpty(folder));
        }
    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());
        }
    }
예제 #5
0
 public static void CropSquare(int size, Stream input, Stream output)
 {
     MagicImageProcessor.ProcessImage(input, output, new ProcessImageSettings {
         Width = size, Height = size, SaveFormat = FileFormat.Jpeg, ResizeMode = CropScaleMode.Crop
     });
 }
예제 #6
0
 public static void GenerateHero(int size, Stream input, Stream output)
 {
     MagicImageProcessor.ProcessImage(input, output, new ProcessImageSettings {
         Width = size, Height = Convert.ToInt32(Math.Round(size * 0.5625)), SaveFormat = FileFormat.Jpeg, ResizeMode = CropScaleMode.Crop
     });
 }
예제 #7
0
        private async Task UploadImagesAsync(string fileType)
        {
            //create a stream so that the image can be read to be resized
            using (var memoryStream = new MemoryStream())
            {
                //read the file into the stream
                await ImageUploaded.FileToUpload.CopyToAsync(memoryStream);

                //set the position to 0 so that the file is not empty
                memoryStream.Position = 0;

                //create another temp stream that will be used to hold the resized image
                using (var outStream = new MemoryStream())
                {
                    //resize the image uploaded into the correct size
                    MagicImageProcessor.ProcessImage(memoryStream, outStream,
                                                     new ProcessImageSettings
                    {
                        Width      = 400,
                        Height     = 400,
                        ResizeMode = CropScaleMode.Crop,
                        HybridMode = HybridScaleMode.FavorSpeed
                    });

                    //set the position to 0 so that the file is not empty
                    outStream.Position = 0;

                    //get a reference to the file in Azure
                    var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(ImageName, AzureBlobFolder);

                    //set the content type of the blob file so that downloads suggest correct file type to save as
                    blobFileToUpload.Properties.ContentType = fileType;

                    //upload the original resized image
                    await _azureBlob.UploadAzureBlobFileAsync(outStream, blobFileToUpload);
                }

                //create another temp stream that will be used to hold the thumbnail image
                using (var outStream = new MemoryStream())
                {
                    //set the position to 0 so that the file is not empty
                    memoryStream.Position = 0;

                    //resize the image uploaded into the correct size
                    MagicImageProcessor.ProcessImage(memoryStream, outStream,
                                                     new ProcessImageSettings
                    {
                        Width      = 200,
                        Height     = 200,
                        ResizeMode = CropScaleMode.Crop,
                        HybridMode = HybridScaleMode.FavorSpeed
                    });

                    //set the position to 0 so that the file is not empty
                    outStream.Position = 0;

                    //get a reference to the file in Azure
                    var blobFileToUpload = _azureBlob.GetAzureBlobFileReference(ThumbnailName, AzureBlobFolder);

                    //set the content type of the blob file so that downloads suggest correct file type to save as
                    blobFileToUpload.Properties.ContentType = fileType;

                    //upload the original resized image
                    await _azureBlob.UploadAzureBlobFileAsync(outStream, blobFileToUpload);
                }
            }
        }
예제 #8
0
        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
                };
            }
        }
예제 #9
0
        public void Transform(string url)
        {
            var request = WebRequest.CreateHttp(url);

            request.Timeout                   = 10000;
            request.ReadWriteTimeout          = 10000;
            request.AllowReadStreamBuffering  = false;
            request.AllowWriteStreamBuffering = false;

            MemoryStream borrowedStream;

            using (var response = request.GetResponse())
            {
                if (response.ContentLength == -1)                   // Means that content length is NOT sent back by the third party server
                {
                    borrowedStream = _streamManager.GetStream(url); // then we let the stream manager had this
                }
                else
                {
                    borrowedStream = _streamManager.GetStream(url, (int)response.ContentLength); // otherwise we borrow a stream with the exact size
                }

                int bufferSize;

                if (response.ContentLength == -1 || response.ContentLength > 81920)
                {
                    bufferSize = 81920;
                }
                else
                {
                    bufferSize = (int)response.ContentLength;
                }

                // close the http response stream asap, we only need the contents, we don't need to keep it open
                using (var responseStream = response.GetResponseStream())
                {
                    responseStream.CopyTo(borrowedStream, bufferSize);
                }
            }

            borrowedStream.Position = 0L;

            MagicImageProcessor.EnableSimd           = false;
            MagicImageProcessor.EnablePlanarPipeline = true;

            using (borrowedStream)
            {
                // upload scaledImage to AWS S3 in production, in the test harness write to disk

                using (var fileStream = File.Create(@"..\..\v4.jpg"))
                {
                    MagicImageProcessor.ProcessImage(borrowedStream, fileStream, new ProcessImageSettings()
                    {
                        Width       = 320,
                        Height      = 240,
                        ResizeMode  = CropScaleMode.Max,
                        SaveFormat  = FileFormat.Jpeg,
                        JpegQuality = 70,
                        HybridMode  = HybridScaleMode.Turbo
                    });
                }
            }
        }
예제 #10
0
        private static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            try
            {
                Console.WriteLine();
                Console.WriteLine("------------------------------------------");
                Console.WriteLine();

                var body       = Encoding.UTF8.GetString(message.Body);
                var bodyParsed = JsonSerializer.Deserialize <Body>(body);

                // Context image
                var localPath     = "./data/";
                var guid          = Guid.NewGuid().ToString();
                var fileName      = guid + ".jpg";
                var localFilePath = Path.Combine(localPath, fileName);
                await File.WriteAllBytesAsync(localFilePath, bodyParsed.ContextImageJpg);

                var blobClient = containerClient.GetBlobClient(fileName);
                using FileStream uploadFileStream = File.OpenRead(localFilePath);
                var info = await blobClient.UploadAsync(uploadFileStream);

                uploadFileStream.Close();

                // Real image
                var localPath2     = "./data2/";
                var guid2          = Guid.NewGuid().ToString();
                var fileName2      = guid2 + ".jpg";
                var fileName3      = "Resized" + guid2 + ".jpg";
                var localFilePath2 = Path.Combine(localPath2, fileName2);
                var localFilePath3 = Path.Combine(localPath2, fileName3);
                await File.WriteAllBytesAsync(localFilePath2, bodyParsed.LicensePlateImageJpg);

                // Resize
                var settings = new ProcessImageSettings {
                    Width = 200
                };
                using var outStream = new FileStream(localFilePath3, FileMode.Create);
                MagicImageProcessor.ProcessImage(localFilePath2, outStream, settings);
                var blobClient2 = containerClient.GetBlobClient(fileName2);
                outStream.Close();
                using FileStream uploadFileStream2 = File.OpenRead(localFilePath3);
                var info2 = await blobClient2.UploadAsync(uploadFileStream2);

                uploadFileStream2.Close();

                if (IsWanted(bodyParsed.LicensePlate, out var wantedPlate))
                {
                    bodyParsed.LicensePlate = wantedPlate;

                    await PostBasicAsync(JsonSerializer.Serialize(bodyParsed.ToBodySend(blobClient.Uri.ToString())));

                    Console.WriteLine("WANTED 1 : " + bodyParsed.LicensePlate);
                }
                else
                {
                    // POST
                    using var request       = new HttpRequestMessage(HttpMethod.Post, "https://hackatown.cognitiveservices.azure.com/vision/v2.0/recognizeText?mode=Printed");
                    using var stringContent = new StringContent($"{{\"url\" : \"{blobClient2.Uri.ToString()}\"}}", Encoding.UTF8, "application/json");
                    request.Content         = stringContent;

                    using var responsePost = await client3
                                             .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None)
                                             .ConfigureAwait(false);

                    Console.WriteLine("PATATE : " + responsePost.StatusCode);
                    Console.WriteLine("PATATE2 : " + await responsePost.Content.ReadAsStringAsync());
                    var location = responsePost.Headers.GetValues("Operation-Location").First();

                    // GET
                    VisionResult result;
                    do
                    {
                        var response = await client4.GetStringAsync(location);

                        result = JsonSerializer.Deserialize <VisionResult>(response);
                    } while (result.status != "Succeeded");

                    bool found = false;
                    foreach (var line in result.recognitionResult.lines)
                    {
                        var trimed = line.text.Replace(" ", "").Replace(".", "").Replace("-", "").Replace("#", "").Replace("\"", "").Replace(":", "").Replace("=", "");
                        if (IsWanted(trimed, out var wantedPlate2))
                        {
                            found = true;

                            bodyParsed.LicensePlate = wantedPlate2;

                            await PostBasicAsync(JsonSerializer.Serialize(bodyParsed.ToBodySend(blobClient.Uri.ToString())));

                            Console.WriteLine("\n**************** WANTED 2 **************** : " + bodyParsed.LicensePlate);

                            break;
                        }
                        else
                        {
                            Console.Write(trimed + "     ");
                        }
                    }

                    if (!found)
                    {
                        Console.WriteLine("\nNot wanted : " + bodyParsed.LicensePlate);
                    }
                }
            }
            catch (InvalidOperationException) { }

            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
        }