Ejemplo n.º 1
0
        static async Task <int> Main(string[] args)
        {
            Tinify.Key = "A5lM3cfqk5BhU0nGFa0JEjKEQd550JAO";

            const string outPath = "C://Users//rkvillegas//output";

            var directories =
                Directory.GetDirectories(
                    "C://Users//rkvillegas//Downloads//Pictures-20180802T153825Z-001//Pictures");

            foreach (var dir in directories)
            {
                foreach (var file in Directory.GetFiles(dir))
                {
                    var fileInfo = new FileInfo(file);
                    var src      = await Tinify.FromFile(file);

                    src = src
                          .Resize(new
                    {
                        method = "fit",
                        width  = 2408,
                        height = 1365,
                    });

                    await src.ToFile($"{outPath}//{fileInfo.Name}");
                }
            }

            Console.ReadLine();

            return(0);
        }
Ejemplo n.º 2
0
        async Task <bool> SetApiKeyAsync(IConsole console)
        {
            try
            {
                var apiKey = string.IsNullOrEmpty(ApiKey)
                    ? Environment.GetEnvironmentVariable(Constants.ApiKeyEnvironmentVariable)
                    : ApiKey;

                if (string.IsNullOrWhiteSpace(apiKey))
                {
                    console.Error.WriteLine("Error: No API Key provided");
                    return(false);
                }

                Tinify.Key = apiKey;
                await Tinify.Validate();

                console.WriteLine("TinyPng API Key verified");
                return(true);
            }
            catch (System.Exception ex)
            {
                console.Error.WriteLine("Validation of TinyPng API key failed.");
                console.Error.WriteLine(ex);
                return(false);
            }
        }
Ejemplo n.º 3
0
        private static async Task SetApiKey()
        {
            while (_activeKeyIndex < ApiKeys.Length)
            {
                if (--_remainingRequests >= 0)
                {
                    Debug.WriteLine($"Existing key used. Remaining compressions count {_remainingRequests}");
                    return;
                }

                Tinify.Key = ApiKeys[_activeKeyIndex++];

                if (!await Tinify.Validate().ConfigureAwait(false) || Tinify.CompressionCount == null)
                {
                    continue;
                }

                _remainingRequests = CompressionsLimit - Tinify.CompressionCount.Value;

                if (--_remainingRequests >= 0)
                {
                    Debug.WriteLine($"New key set. Remaining compressions count {_remainingRequests}");
                    return;
                }
            }

            throw new Exception("The limit of Tinify compressions has been reached. Please add more API keys");
        }
Ejemplo n.º 4
0
        public static async Task <byte[]> Fit(byte[] image, int width, int height)
        {
            try
            {
                IncrementPending();
                await SemaphoreSlim.WaitAsync().ConfigureAwait(false);

                Task <Source> resized;
                try
                {
                    await SetApiKey().ConfigureAwait(false);

                    var source = Tinify.FromBuffer(image);
                    resized = source.Resize(new { method = "fit", width, height });
                }
                finally
                {
                    SemaphoreSlim.Release();
                }
                Debug.WriteLine("Sending compression request");
                var result = await resized.ToBuffer().ConfigureAwait(false);

                return(result);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                throw;
            }
            finally
            {
                DecrementPending();
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> TinifySettings()
        {
            var model = new TinifySettingsViewModel
            {
                Enable        = bool.Parse(await _settingsHelper.Get(Settings.EnableTinifyCompress)),
                StatusMessage = StatusMessage
            };

            if (!model.Enable)
            {
                return(View(model));
            }

            var tinifyKey = await(_settingsHelper.Get(Settings.TinifyApiKey));
            var tinify    = new Tinify(tinifyKey);

            try
            {
                await tinify.ValidateKey();

                model.ApiKeyValid = true;
            }
            catch
            {
                model.ApiKeyValid = false;
            }

            model.CompressedCount = await tinify.GetCompressionCount();

            model.ApiKey = await _settingsHelper.Get(Settings.TinifyApiKey);

            return(View(model));
        }
Ejemplo n.º 6
0
        async Task <bool> SetApiKeyAsync(IConsole console)
        {
            try
            {
                var apiKey = string.IsNullOrEmpty(ApiKey)
                    ? this.readApikey()
                    : ApiKey;

                if (string.IsNullOrWhiteSpace(apiKey))
                {
                    console.Error.WriteLine("Error: No API Key provided");
                    return(false);
                }

                Tinify.Key = apiKey;
                await Tinify.Validate();

                console.WriteLine("TinyPng API Key verified");

                // save
                this.writeApikey(apiKey);
                return(true);
            }
            catch (System.Exception ex)
            {
                console.Error.WriteLine("Validation of TinyPng API key failed.");
                console.Error.WriteLine(ex);
                return(false);
            }
        }
Ejemplo n.º 7
0
        public static void Init()
        {
            Tinify.Key   = Environment.GetEnvironmentVariable("TINIFY_KEY");
            Tinify.Proxy = Environment.GetEnvironmentVariable("TINIFY_PROXY");

            var unoptimizedPath = AppContext.BaseDirectory + "/examples/voormedia.png";

            optimized = Tinify.FromFile(unoptimizedPath);
        }
Ejemplo n.º 8
0
        static void dene()
        {
            var         source      = Tinify.FromFile(@"C:\Users\ismail-PC\Desktop\barcodes\images\8680530125330.jpg");
            TaskAwaiter taskAwaiter = source.ToFile(@"C:\Users\ismail-PC\Desktop\barcodes\images\compressed\8680530125330.jpg").GetAwaiter();

            taskAwaiter.OnCompleted(() =>
                                    Console.WriteLine("bitti")
                                    );
        }
Ejemplo n.º 9
0
        public static async Task <string> TinifyModulAsync(string base64String, string type)
        {
            try
            {
                var stringbase64 = "";
                var data64       = Regex.Split(base64String, ";base64,");
                if (data64.Length > 1)
                {
                    stringbase64 = data64[1];
                }
                else
                {
                    stringbase64 = data64[0];
                }
                byte[] bytes = System.Convert.FromBase64String(stringbase64);
                Tinify.Key = "3bfrr65Nl2QYQTk8lGHGQ8w8ZGJ358ND";
                var    source = Tinify.FromBuffer(bytes);
                string Key    = type + "/" + CommonFunction.GetTimestamp(DateTime.UtcNow) + "_" + CommonFunction.RandomNumber(0, 99999999);
                await source.Store(new
                {
                    service               = "s3",
                    aws_access_key_id     = "AKIAJZMY3NCCEJQXACJA",
                    aws_secret_access_key = "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",
                    region = "ap-southeast-1",
                    path   = bucketname + "/" + Key,
                });

                return(Key);
            }
            catch (AccountException e)
            {
                return("");
                // Verify your API key and account limit.
            }
            catch (ClientException e)
            {
                return("");
                // Check your source image and request options.
            }
            catch (ServerException e)
            {
                return("");
                // Temporary issue with the Tinify API.
            }
            catch (ConnectionException e)
            {
                return("");
                // A network connection error occurred.
            }
            catch (System.Exception e)
            {
                return("");
                // Something else went wrong, unrelated to the Tinify API.
            }
        }
        /// <summary>
        /// Reduce the physical size and byte size of an image
        /// </summary>
        /// <param name="buffer">Image to reduce as <see cref="byte[]"/></param>
        /// <param name="maxWidth">Maximum Width of Image as <see cref="int?"/></param>
        /// <param name="maxHeight">Maximum Height of Image as <see cref="int?"/></param>
        /// <returns>Image as <see cref="byte[]</returns>
        public async Task <byte[]> ResizeImage(byte[] buffer, int?maxWidth, int?maxHeight)
        {
            try
            {
                // TinyPNG Developer API KEY  https://tinypng.com/developers
                Tinify.Key = ConfigurationAgent["ApplicationSettings:TinyPNG:ApiKey"];

                var source = await Tinify.FromBuffer(buffer).ConfigureAwait(false);

                Source resized;
                if (maxWidth.HasValue && maxHeight.HasValue)
                {
                    resized = source.Resize(new { method = "fit", width = maxWidth, height = maxHeight });
                }
                else if (maxWidth.HasValue)
                {
                    resized = source.Resize(new { method = "scale", width = maxWidth });
                }
                else if (maxHeight.HasValue)
                {
                    resized = source.Resize(new { method = "scale", height = maxHeight });
                }
                else
                {
                    return(buffer);
                }

                return(await resized.ToBuffer().ConfigureAwait(false));
            }
            catch (AccountException accountEx)
            {
                // Verify API key and account limit.
                var x = await Tinify.Validate().ConfigureAwait(false);

                var compressionsThisMonth = Tinify.CompressionCount;

                var properties = new Dictionary <string, string> {
                    { "compressionsThisMonth", compressionsThisMonth.HasValue ? compressionsThisMonth.Value.ToString(CultureInfo.CurrentCulture) : "0" }
                };
                LoggingAgent.TrackException(accountEx, properties);
            }

            catch (TinifyAPI.Exception tex)
            {
                LoggingAgent.TrackException(tex);
            }
            catch (System.Exception ex)
            {
                LoggingAgent.TrackException(ex);
                throw;
            }

            // something went wrong, just return input value
            return(buffer);
        }
Ejemplo n.º 11
0
        public async Task <byte[]> CompressImage(byte[] uncomressedBytes)
        {
            var uncompressedFilesize = GetFileSize(uncomressedBytes);

            Console.WriteLine($"TINYPNG Uncompressed Filesize: {uncompressedFilesize}");
            var compressedImage = await Tinify.FromBuffer(uncomressedBytes).ToBuffer();

            var compressedFilesize = GetFileSize(compressedImage);

            Console.WriteLine($"TINYPNG Compressed Filesize: {compressedFilesize}");
            return(compressedImage);
        }
Ejemplo n.º 12
0
        // Save original and optimized image
        public async Task <ActionResult> OptimizeAsync(HttpPostedFileBase imag)
        {
            var urlPath = Path.Combine(Server.MapPath("~/Images/Orginal"), imag.FileName);

            imag.SaveAs(urlPath);

            Tinify.Key = "nnpQB5zB0HS0czxmS7YTFwTrw35CQwJd";
            var source = Tinify.FromFile(urlPath);
            await source.ToFile(Path.Combine(Server.MapPath("~/Images/Optimized"), "optimized_" + imag.FileName));

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 13
0
        public void WithValidKey_Should_ReturnTrue()
        {
            Tinify.Key = "valid";

            Helper.MockClient(Tinify.Client);
            Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond(
                HttpStatusCode.BadRequest,
                new StringContent("{\"error\":\"Input missing\",\"message\":\"No input\"}")
                );

            Assert.AreEqual(true, Tinify.Validate().Result);
        }
Ejemplo n.º 14
0
        public void WithLimitedKey_Should_ReturnTrue()
        {
            Tinify.Key = "valid";

            Helper.MockClient(Tinify.Client);
            Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond(
                (HttpStatusCode)429,
                new StringContent("{\"error\":\"Too may requests\",\"message\":\"Your monthly limit has been exceeded\"}")
                );

            Assert.AreEqual(true, Tinify.Validate().Result);
        }
Ejemplo n.º 15
0
        private async void compress(PictureBox picSrc, PictureBox picDest, Label lblSize)
        {
            PlayAnimation();
            var source = Tinify.FromBuffer(ImgToByte(picSource.Image));

            source = source.Preserve("copyright");
            var result = await source.ToBuffer();

            picDest.Image = ByteToImg(result);
            computeSize(picDest, lblSize);
            StopAnimation();
            MessageBox.Show(Tinify.CompressionCount.Value.ToString());
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Start compression task.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button_start_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBox_apiKey.Text))
            {
                if (!string.IsNullOrWhiteSpace(textBox_folder.Text))
                {
                    // Collect all image files and save in list
                    MessageBox.Show("Important: All files will be overwritten, please make a backup of your source images.");
                    tinyKey = textBox_apiKey.Text;
                    string        path     = textBox_folder.Text;
                    List <string> fileList = FileList(path);

                    // Compress every image file in list
                    foreach (string file in fileList)
                    {
                        try
                        {
                            textBox_currentFile.Text = ".." + file.Replace(textBox_folder.Text, "");
                            textBox_currentFile.Update();
                            double fileSize = new FileInfo(filePath).Length;
                            Log("Compress File: .." + file.Replace(textBox_folder.Text, ""));
                            // Log("Original Size:" + HumanReadableFileSize(filePath, fileSize));
                            Tinify.Key = tinyKey;
                            Task <Source> source = Tinify.FromFile(filePath);
                            await source.ToFile(filePath);

                            Thread.Sleep(1000);
                            UpdateLabels();
                            double fileSizeCompressed = new FileInfo(filePath).Length;
                            // Log("Compressed Size:" + HumanReadableFileSize(filePath, fileSizeCompressed) + " ---> Saved: " + CompressedPercentage(fileSize, fileSizeCompressed) + "%");
                            Log("Saved: " + CompressedPercentage(fileSize, fileSizeCompressed) + "%");
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }

                    textBox_currentFile.Text = "";
                }
                else
                {
                    MessageBox.Show("Please choose a directory.");
                }
            }
            else
            {
                MessageBox.Show("Please provide your api key.");
            }
        }
        public async Task CompressPic(string picPath)
        {
            var source = Tinify.FromFile(picPath);

            try
            {
                await source.ToFile(picPath);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e);
            }
            _callback.OnCompressionDone(picPath);
        }
Ejemplo n.º 18
0
        public void WithError_Should_ThrowException()
        {
            Tinify.Key = "valid";

            Helper.MockClient(Tinify.Client);
            Helper.MockHandler.Expect("https://api.tinify.com/shrink").Respond(
                HttpStatusCode.Unauthorized,
                new StringContent("{\"error\":\"Unauthorized\",\"message\":\"Credentials are invalid\"}")
                );

            Assert.ThrowsAsync <AccountException>(async() =>
            {
                await Tinify.Validate();
            });
        }
Ejemplo n.º 19
0
        public async Task SaveImagesAsync(IEnumerable <IFormFile> images)
        {
            Tinify.Key = API_KEY;
            foreach (var image in images)
            {
                var pathToFile = Path.Combine(pathToDirectory, image.FileName);
                using (Stream fileStream = new FileStream(pathToFile, FileMode.Create))
                {
                    await image.CopyToAsync(fileStream);
                }

                var source = Tinify.FromFile(pathToFile);
                source.ToFile(pathToFile);
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Offer(OfferViewModel vm)
        {
            Offer o = new Offer
            {
                OfferName    = vm.OfferName,
                Price        = vm.Price,
                Description  = vm.Description,
                EndDate      = vm.EndDate,
                Percentage   = vm.Percentage,
                Status       = true,
                ChefId       = HttpContext.Session.Get <SessionData>(SessionUser).Id,
                CreatedDate  = DateTime.Now,
                ModifiedDate = DateTime.Now,
                StartDate    = DateTime.Now
            };

            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    if (vm.Image != null && vm.Image.Length > 0)
                    {
                        o.ImgUrl = Utils.UploadImageR(env, "/Uploads/Chefs/" + HttpContext.Session.Get <SessionData>(SessionUser).CNIC + "/Offer", vm.Image);
                    }
                    db.Offer.Add(o);
                    db.SaveChanges();

                    tr.Commit();

                    if (o.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + o.ImgUrl))
                    {
                        var source  = Tinify.FromFile(env.WebRootPath + o.ImgUrl);
                        var resized = source.Resize(new
                        {
                            method = "cover",
                            width  = 300,
                            height = 168
                        });
                        await resized.ToFile(env.WebRootPath + o.ImgUrl);
                    }
                }
                catch
                {
                    tr.Rollback();
                }
            }
            return(Redirect("Account"));
        }
Ejemplo n.º 21
0
        public static async Task <int> Execute(OptimizeOptions options, IConsole console, InvocationContext context = null)
        {
            if (options == null)
            {
                console.Error.WriteLine("Invalid File TemplateRepositoryPath");
                return(ReturnCodes.Error);
            }

            var settingsManager = new TinifySettingsManager(new FileSystemRoamingProfileAppEnvironment());

            TinifySettings settings = settingsManager.LoadSettings();

            try
            {
                console.Out.WriteLine("Validating Tinify API Key");

                Tinify.Key = settings.Key;
                bool validKey = await Tinify.Validate().ConfigureAwait(false);

                if (!validKey)
                {
                    console.Error.WriteLine("Invalid Tinify API Key");
                    return(ReturnCodes.Error);
                }

                long originalSizeInBytes = options.FilePath.Length;

                console.Out.WriteLine($"Original size: {originalSizeInBytes / 1024}KB");

                Source source = await Tinify.FromFile(options.FilePath.FullName).ConfigureAwait(false);

                await source.ToFile(options.FilePath.FullName);

                long   newSizeInBytes = new FileInfo(options.FilePath.FullName).Length;
                double percentChange  = (newSizeInBytes - originalSizeInBytes) * 100.0 / originalSizeInBytes;

                console.Out.WriteLine($"New size: {newSizeInBytes / 1024}KB");
                console.Out.WriteLine($"{percentChange:00}% Reduction");
            }
            catch (Exception exception)
            {
                console.Error.WriteLine(exception.Message);

                return(ReturnCodes.Exception);
            }

            return(ReturnCodes.Ok);
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> Menu(MenuViewModel vm)
        {
            Menu m = new Menu {
                DishName     = vm.DishName,
                Price        = vm.Price,
                Description  = vm.Description,
                Status       = true,
                CreatedDate  = DateTime.Now,
                ModifiedDate = DateTime.Now,
                DishDislike  = 0,
                DishLike     = 0,
                Serving      = vm.Serving,
                ChefId       = HttpContext.Session.Get <SessionData>(SessionUser).Id
            };

            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    if (vm.Image != null && vm.Image.Length > 0)
                    {
                        m.ImgUrl = Utils.UploadImageR(env, "/Uploads/Chefs/" + HttpContext.Session.Get <SessionData>(SessionUser).CNIC + "/Menu", vm.Image);
                    }

                    db.Menu.Add(m);
                    db.SaveChanges();

                    tr.Commit();

                    if (m.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + m.ImgUrl))
                    {
                        var source  = Tinify.FromFile(env.WebRootPath + m.ImgUrl);
                        var resized = source.Resize(new
                        {
                            method = "cover",
                            width  = 300,
                            height = 168
                        });
                        await resized.ToFile(env.WebRootPath + m.ImgUrl);
                    }
                }
                catch
                {
                    tr.Rollback();
                }
            }
            return(Redirect("Account"));
        }
Ejemplo n.º 23
0
        public async Task <ActionResult> EditFilterItem(CreateFilterItemViewModel model, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                var filterItem = _filterItemService.GetFilterItem(model.Id);
                var filter     = _filterService.GetFilterByValue(model.FilterValue);

                if (filterItem != null && filter != null)
                {
                    filterItem.Name   = model.Name;
                    filterItem.Value  = model.Value;
                    filterItem.Rank   = model.Rank;
                    filterItem.Filter = filter;
                    if (image != null && (image.ContentType == "image/jpeg" || image.ContentType == "image/png"))
                    {
                        Tinify.Key = ConfigurationManager.AppSettings["TINYPNG_APIKEY"];
                        var extName  = System.IO.Path.GetExtension(image.FileName);
                        var fileName = $@"{Guid.NewGuid()}{extName}";

                        // сохраняем файл в папку Files в проекте
                        string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\FilterItems", fileName);
                        var    urlPath  = Url.Content("~/Content/Images/FilterItems/" + fileName);
                        image.SaveAs(fullPath);
                        try
                        {
                            using (var s = Tinify.FromFile(fullPath))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 100,
                                    height = 70
                                });
                                await resized.ToFile(fullPath);
                            }
                        }
                        catch (System.Exception)
                        {
                            // ignored
                        }
                        filterItem.ImagePath = urlPath;
                    }
                    _filterItemService.SaveFilterItem();
                    return(RedirectToAction("FilterItemList"));
                }
            }
            return(HttpNotFound());
        }
Ejemplo n.º 24
0
 public static async Task <byte[]> CompressBase64(byte[] buffer, int w = 500, int h = 500)
 {
     try
     {
         Tinify.Key = "hdrdBNqcCwkPQqVYml22fqsqtGf71xdC";
         return(await Tinify.FromBuffer(buffer).Resize(new {
             method = "fit",
             width = w,
             height = h
         }).ToBuffer());
     }
     catch (TinifyAPI.Exception ex)
     {
         return(new byte[] { });
     }
 }
Ejemplo n.º 25
0
 public static async Task <byte[]> CompressFile(byte[] buffer, int w = 500, int h = 500)
 {
     try
     {
         return(await Tinify.FromBuffer(buffer).Resize(new
         {
             method = "fit",
             width = w,
             height = h
         }).ToBuffer());
     }
     catch (TinifyAPI.Exception ex)
     {
         return(new byte[] { });
     }
 }
Ejemplo n.º 26
0
        public static Task <bool> CheckKey()
        {
            string zcf = GetUnusedKeys();

            if (zcf != String.Empty)
            {
                Tinify.Key = zcf;
            }
            else
            {
                Console.WriteLine("keys已经使用完成请添加可用的key");
                Console.ReadKey();
                ;
            }
            return(Tinify.Validate());
        }
Ejemplo n.º 27
0
        static async Task MainAsync(string[] args, string path)
        {
            Program p = new Program();

            try
            {
                Tinify.Key = ConfigurationManager.AppSettings["TinyKey"];
                await Tinify.Validate();
            }
            catch (AccountException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("API KEY ERROR: " + e.Message);
                Console.ReadLine();
                Environment.Exit(0);
            }
            List <FileInfo> files   = new List <FileInfo>();
            long            counter = 0;

            if (Directory.Exists(path))
            {
                files = p.TraverseTree(path);
                Console.WriteLine("\n------------------ {0} FILES FOUND --------------------\n", files.Count);
                foreach (FileInfo f in files)
                {
                    long length = f.Length;
                    var  source = Tinify.FromFile(f.FullName);
                    try
                    {
                        await source.ToFile(f.FullName);

                        counter++;
                        Console.WriteLine("{0} compressed successfully...", f.Name);
                    }
                    catch (ClientException e)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("{0} has an unsupported data format...[skipped]", f.Name);
                        Console.ForegroundColor = ConsoleColor.Green;
                        continue;
                    }
                }
            }
            Console.WriteLine("\n Complete! {0} files compressed. You have done {1} compression(s) so far. Press Enter to close...", counter, Tinify.CompressionCount);
            Console.ReadLine();
            Environment.Exit(0);
        }
Ejemplo n.º 28
0
        async Task TinyPNG(params string[] files)
        {
            try
            {
                image.Visible = true;

                var folders = new List <string>();
                foreach (var item in files)
                {
                    var path = Path.Combine(Path.GetDirectoryName(item), "opt");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    label.Text = Path.GetFileName(item);
                    var source = Tinify.FromFile(item);
                    await source.ToFile(Path.Combine(path, Path.GetFileName(item)));

                    if (!folders.Contains(path))
                    {
                        folders.Add(path);
                    }
                }

                foreach (var item in folders)
                {
                    Process.Start(item);
                }
                label.Text    = string.Empty;
                image.Visible = false;
            }
            catch (System.Exception e)
            {
                var errors = new List <string>();
                var err    = e;
                while (err != null)
                {
                    errors.Add(err.Message);
                    err = e.InnerException;
                }
                errors.Reverse();
                MessageBox.Show(string.Join("\n", errors));
                Close();
            }
        }
Ejemplo n.º 29
0
        private async void CompresserBtn_Click(object sender, EventArgs e)
        {
            if (resimYol.Count != 0 && (!string.IsNullOrWhiteSpace(metroTextBox1.Text)))
            {
                try
                {
                    progressPanel1.Show();
                    ToplamDurumProgressBar.Show();
                    kayitYeri = KlasorOlustur();
                    indirilenDosyaListBox.Items.Clear();
                    int i = 0;

                    int boyut = 100 / resimYol.Count;
                    foreach (var resim in resimYol)
                    {
                        ToplamDurumProgressBar.Percentage = boyut * i;
                        Image img        = Image.FromFile(resim.Value);
                        var   resultData = await Tinify.FromBuffer(Util.ImgToByte(img)).ToBuffer();

                        Image responseImage = Util.ByteToImage(resultData);
                        responseImage.Save(kayitYeri + "\\" + resim.Key);
                        indirilenDosyaListBox.Items.Add(resim.Key);

                        i++;
                        ToplamDurumProgressBar.Percentage = boyut * i;
                    }
                }
                catch (Exception t)
                {
                    MessageBox.Show(t.Message);
                    ToplamDurumProgressBar.Hide();
                }
                finally
                {
                    ToplamDurumProgressBar.Percentage = 100;
                    progressPanel1.Hide();
                    resimYol.Clear();
                    dosyaListBox.Items.Clear();
                }
            }
            else
            {
                MessageBox.Show("Klasör Seçili değil veya API Key alanı boş!");
            }
        }
Ejemplo n.º 30
0
        public async Task <ActionResult> EditGame(EditGameViewModel model, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                var game = _gameService.GetGame(model.Id);
                if (game != null)
                {
                    game.Name  = model.Name;
                    game.Value = model.Value;
                    game.Rank  = model.Rank;
                    if (image != null && (image.ContentType == "image/jpeg" || image.ContentType == "image/png"))
                    {
                        string extName  = System.IO.Path.GetExtension(image.FileName);
                        string fileName = $@"{Guid.NewGuid()}{extName}";

                        // сохраняем файл в папку Files в проекте
                        string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\GameIcons", fileName);
                        string urlPath  = Url.Content("~/Content/Images/GameIcons/" + fileName);
                        image.SaveAs(fullPath);
                        Tinify.Key = ConfigurationManager.AppSettings["TINYPNG_APIKEY"];
                        try
                        {
                            using (var s = Tinify.FromFile(fullPath))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 40,
                                    height = 40
                                });
                                await resized.ToFile(fullPath);
                            }
                        }
                        catch (System.Exception)
                        {
                            // ignored
                        }
                        game.ImagePath = urlPath;
                    }
                    _gameService.SaveGame();
                    return(RedirectToAction("GameList"));
                }
            }
            return(HttpNotFound());
        }