Exemplo 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);
        }
Exemplo n.º 2
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")
                                    );
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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"));
        }
        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);
        }
Exemplo n.º 6
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.");
            }
        }
Exemplo n.º 7
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);
            }
        }
Exemplo n.º 8
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"));
        }
Exemplo n.º 9
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());
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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"));
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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();
            }
        }
Exemplo n.º 14
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());
        }
Exemplo n.º 15
0
        //Save multi image
        public async Task <ActionResult> OptimizeAsync3(HttpPostedFileBase[] imag)
        {
            List <string> forDownload = new List <string>();

            Tinify.Key = "jpR72pbwbnRvxWvKfVjrvxZVDXxD5vR4";
            foreach (HttpPostedFileBase item in imag)
            {
                var urlPath = Path.Combine(Server.MapPath("~/Images"), item.FileName);
                item.SaveAs(urlPath);

                var source = Tinify.FromFile(urlPath);
                await source.ToFile(urlPath);

                forDownload.Add(item.FileName);
                TempData["for"] = forDownload;
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 16
0
        //Save one image
        public async Task <ActionResult> OptimizeAsync2(HttpPostedFileBase imag)
        {
            try
            {
                Tinify.Key = "jpR72pbwbnRvxWvKfVjrvxZVDXxD5vR4";
                var urlPath = Path.Combine(Server.MapPath("~/Images"), imag.FileName);
                imag.SaveAs(urlPath);

                var source = Tinify.FromFile(urlPath);
                await source.ToFile(urlPath);

                TempData["Url"] = imag.FileName;
            }
            catch
            {
                TempData["Error"] = "EROORR EROR";
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 17
0
        public static async Task compressionPng(string path, Action claa)
        {
            try
            {
                var source = Tinify.FromFile(path);
                await source.ToFile(path);

                if (claa != null)
                {
                    claa.Invoke();
                }
            }
            catch (AccountException e)
            {
                System.Console.WriteLine("The error message is:key压缩数量已达到上限 " + e.Message);
                key[Tinify.Key] = true;
                CheckKey();
                compressionPng(path, claa).Wait();
                // Verify your API key and account limit.
            }
            catch (ClientException e)
            {
                // Check your source image and request options.
                Console.WriteLine("由于提交的数据存在问题,无法完成请求。异常消息将包含更多信息。您不应该重试该请求。");
            }
            catch (ServerException e)
            {
                // Temporary issue with the Tinify API.
                Console.WriteLine("由于Tinify API存在临时问题,无法完成请求。几分钟后重试请求是安全的。如果您在较长时间内反复看到此错误,请 与我们联系。");
            }
            catch (ConnectionException e)
            {
                Console.WriteLine("无法发送请求,因为连接到Tinify API时出现问题。您应该验证您的网络连接。重试请求是安全的。");

                compressionPng(path, claa).Wait();
                // A network connection error occurred.
            }
            catch (System.Exception e)
            {
                // Something else went wrong, unrelated to the Tinify API.
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 18
0
        public async Task <IActionResult> EditOffer(OfferViewModel vm)
        {
            Offer o = db.Offer.Where(i => i.OfferId == vm.OfferId).FirstOrDefault();

            o.ModifiedDate = DateTime.Now;
            o.OfferName    = vm.OfferName;
            o.Description  = vm.Description;
            o.Price        = vm.Price;
            o.EndDate      = vm.EndDate;
            o.Percentage   = vm.Percentage;
            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    if (vm.Image != null && vm.Image.Length > 0)
                    {
                        o.ImgUrl = Utils.UploadImageU(env, "/Uploads/Chefs/" + HttpContext.Session.Get <SessionData>(SessionUser).CNIC + "/Offer", vm.Image, o.ImgUrl);
                    }
                    db.Offer.Update(o);
                    db.SaveChanges();

                    tr.Commit();

                    if (vm.Image != null && 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"));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> EditMenu(MenuViewModel vm)
        {
            Menu menu = db.Menu.Where(i => i.MenuId == vm.MenuId).FirstOrDefault();

            menu.ModifiedDate = DateTime.Now;
            menu.DishName     = vm.DishName;
            menu.Price        = vm.Price;
            menu.Status       = vm.Status;
            menu.Description  = vm.Description;
            menu.Serving      = vm.Serving;
            using (var tr = db.Database.BeginTransaction())
            {
                try
                {
                    if (vm.Image != null && vm.Image.Length > 0)
                    {
                        menu.ImgUrl = Utils.UploadImageU(env, "/Uploads/Chefs/" + HttpContext.Session.Get <SessionData>(SessionUser).CNIC + "/Menu", vm.Image, menu.ImgUrl);
                    }
                    db.Menu.Update(menu);
                    db.SaveChanges();

                    tr.Commit();

                    if (vm.Image != null && menu.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + menu.ImgUrl))
                    {
                        var source  = Tinify.FromFile(env.WebRootPath + menu.ImgUrl);
                        var resized = source.Resize(new
                        {
                            method = "cover",
                            width  = 300,
                            height = 168
                        });
                        await resized.ToFile(env.WebRootPath + menu.ImgUrl);
                    }
                }
                catch
                {
                    tr.Rollback();
                }
            }
            return(Redirect("Account"));
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");
            if (args.Length != 3)
            {
                Console.WriteLine("参数长度需要为3:当前输入长度:" + args.Length);
                return;
            }
            try
            {
                Tinify.Key = args[0];
                string        Dir_Input  = args[1];
                string        Dir_Output = args[2];
                List <string> Ls_File    = new List <string>();
                FileHelper.GetAllFiles(Ls_File, Dir_Input);
                List <Task> Ls_Tasks = new List <Task>();
                foreach (var fp in Ls_File)
                {
                    if (Path.GetExtension(fp) != ".png" && Path.GetExtension(fp) != ".jpg")
                    {
                        continue;
                    }
                    var outpath    = Dir_Output + fp.Substring(Dir_Input.Length, fp.Length - Dir_Input.Length);
                    var outpathdir = Path.GetDirectoryName(outpath);
                    FileHelper.CreatPath(outpathdir);
                    Console.WriteLine(outpath);
                    //////////////////
                    Ls_Tasks.Add(Tinify.FromFile(fp).ToFile(outpath));
                }

                Task.WaitAll(Ls_Tasks.ToArray());

                Console.WriteLine("任务完成");
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }


            Console.ReadKey();
        }
Exemplo n.º 21
0
        async Task CompressFile(string file)
        {
            try
            {
                Console.WriteLine($"Compressing {Path.GetFileName(file)}...");

                var originalSizeInBytes = new FileInfo(file).Length;

                var source = Tinify.FromFile(file);
                await source.ToFile(file);

                var newSizeInBytes = new FileInfo(file).Length;
                var percentChange  = (newSizeInBytes - originalSizeInBytes) * 100.0 / originalSizeInBytes;

                Console.WriteLine($"Compression complete. {Path.GetFileName(file)} was {originalSizeInBytes.Bytes()}, now {newSizeInBytes.Bytes()} (-{percentChange:0}%)");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"An error occurred compressing {Path.GetFileName(file)}: ");
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 22
0
        static void process(ImageProcess imageProcess)
        {
            string urlPath = null;

            if (imageProcess.ImageTypeId == Enums.ImageTypes.Product)
            {
                urlPath = Path.Combine(Stc.ImageSourceUrl, "product");
            }
            else if (imageProcess.ImageTypeId == Enums.ImageTypes.Profile)
            {
                urlPath = Path.Combine(Stc.ImageSourceUrl, "profile");
            }

            string fileName = Path.Combine(urlPath,
                                           imageProcess.StoreTypeId == StoreType.Normal ? "" : "thumbnail", imageProcess.UniqueId.ToString().ToUpper() + "." + imageProcess.FileTypeId.ToString());

            var         source      = Tinify.FromFile(fileName);
            TaskAwaiter taskAwaiter = source.ToFile(fileName).GetAwaiter();

            taskAwaiter.OnCompleted(() =>
                                    done(imageProcess)
                                    );
        }
Exemplo n.º 23
0
    public async Task CompressImages(string path)
    {
        var log          = new List <string>();
        var compressions = new List <ImageTransformation>();

        Tinify.Key = tbTinyPngKey.Text;
        var isApiKeyValid = await Tinify.Validate();

        if (!isApiKeyValid)
        {
            log.Add("API key is invald: " + Tinify.Key);
        }
        else
        {
            var files = GetFiles(path).Take(5);
            // var files = GetFiles(path); //uncomment to optimize all files
            foreach (var img in files)
            {
                var sourcePath      = img.FilePath;
                var filename        = PathExtensions.GetRelativePath(path, sourcePath);
                var destinationPath = Path.Combine(DestinationFolderPath, filename);
                // ensure the folder exists for proper working source.ToFile();
                new DirectoryInfo(Path.GetDirectoryName(destinationPath)).Create();

                var compression = new ImageTransformation()
                {
                    Path    = destinationPath,
                    OldSize = img.Size,
                };

                var compressionsThisMonth = Tinify.CompressionCount == null ? 0 : Tinify.CompressionCount;
                if (compressionsThisMonth < 500)
                {
                    try
                    {
                        // Use the Tinify API client.
                        var source = Tinify.FromFile(sourcePath);
                        await source.ToFile(destinationPath);

                        compression.NewSize = source.GetResult().Result.Size;
                        compressions.Add(compression);
                    }
                    catch (AccountException e)
                    {
                        log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message));
                        //System.Console.WriteLine("The error message is: " + e.Message);
                        // Verify your API key and account limit.
                    }
                    catch (ClientException e)
                    {
                        log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message));
                        var mimetype = MimeTypes.getMimeFromFile(sourcePath);
                        log.Add(String.Format("The actual mime type of '{0}' image is '{1}' ", filename, mimetype));

                        // Check your source image and request options.
                    }
                    catch (ServerException e)
                    {
                        log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message));

                        // Temporary issue with the Tinify API.
                    }
                    catch (ConnectionException e)
                    {
                        log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message));

                        // A network connection error occurred.
                    }
                    catch (System.Exception e)
                    {
                        log.Add(string.Format("Error for image '{0}'. Error message: ", filename, e.Message));

                        // Something else went wrong, unrelated to the Tinify API.
                    }
                }
                else
                {
                    log.Add("Free API usage is near the limit: " + compressionsThisMonth);
                    //break;
                }
            }
        }

        using (TextWriter writer = new StreamWriter(Server.MapPath("~/errors.xml")))
        {
            var serializer = new XmlSerializer(typeof(List <string>));
            serializer.Serialize(writer, log);
        }

        using (TextWriter writer = new StreamWriter(Server.MapPath("~/compressions.xml")))
        {
            var serializer = new XmlSerializer(typeof(List <ImageTransformation>));
            serializer.Serialize(writer, compressions);
        }

        RadGrid1.DataSource = log;
        RadGrid1.DataBind();
    }
Exemplo n.º 24
0
 public void Should_ReturnSourceTask()
 {
     Assert.IsInstanceOf <Task <Source> >(
         Tinify.FromFile("test/Tinify.Tests/examples/dummy.png")
         );
 }
Exemplo n.º 25
0
 /// <summary>
 /// 裁剪图片
 /// </summary>
 public async Task Resize(string filePath, string savePath, object options)
 {
     var source  = Tinify.FromFile(filePath);
     var resized = source.Resize(options);
     await resized.ToFile(savePath);
 }
Exemplo n.º 26
0
 /// <summary>
 /// 压缩图片
 /// </summary>
 public async Task Compress(string filePath, string savePath)
 {
     var source = Tinify.FromFile(filePath);
     await source.ToFile(savePath);
 }
Exemplo n.º 27
0
 public void Should_ReturnSourceTask()
 {
     Assert.IsInstanceOf <Task <Source> >(
         Tinify.FromFile(AppContext.BaseDirectory + "/examples/dummy.png")
         );
 }
Exemplo n.º 28
0
        public async Task <IActionResult> ModifyDetails(ModifyDetailsViewModel vm)
        {
            if (ModelState.IsValid)
            {
                if (string.Equals(vm.Role.Trim(), "chef", StringComparison.OrdinalIgnoreCase))
                {
                    Chef c = db.Chef.Where(i => i.ChefId == HttpContext.Session.Get <SessionData>(SessionUser).Id).FirstOrDefault();
                    c.FirstName    = vm.FirstName;
                    c.LastName     = vm.LastName;
                    c.Gender       = vm.Gender;
                    c.Dob          = vm.Dob;
                    c.Email        = vm.Email;
                    c.ModifiedDate = DateTime.Now;
                    c.PhoneNo      = vm.PhoneNo;
                    c.City         = vm.City;
                    c.Area         = vm.Area;
                    c.Street       = vm.Street;
                    c.Status       = vm.Status;
                    c.About        = vm.About;

                    using (var tr = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (vm.Image != null && vm.Image.Length > 0)
                            {
                                c.ImgUrl = Utils.UploadImageU(env, "/Uploads/Chefs/" + vm.Cnic, vm.Image, vm.ImgUrl);
                            }
                            db.Chef.Update(c);
                            db.SaveChanges();
                            tr.Commit();

                            if (c.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + c.ImgUrl) && vm.Image != null)
                            {
                                var source  = Tinify.FromFile(env.WebRootPath + c.ImgUrl);
                                var resized = source.Resize(new
                                {
                                    method = "fit",
                                    width  = 300,
                                    height = 168
                                });
                                await resized.ToFile(env.WebRootPath + c.ImgUrl);
                            }
                            ViewBag.Success = " Your data is successfully modified.";

                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl,
                                About = c.About
                            }));
                        }
                        catch
                        {
                            tr.Rollback();

                            ModelState.AddModelError("", "We are having some problem in Updating your record.");
                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl,
                                About = c.About
                            }));
                        }
                    }
                }
                else if (string.Equals(vm.Role.Trim(), "customer", StringComparison.OrdinalIgnoreCase))
                {
                    Customer c = db.Customer.Where(i => i.CustomerId == HttpContext.Session.Get <SessionData>(SessionUser).Id).FirstOrDefault();
                    c.FirstName    = vm.FirstName;
                    c.LastName     = vm.LastName;
                    c.Gender       = vm.Gender;
                    c.Dob          = vm.Dob;
                    c.Email        = vm.Email;
                    c.ModifiedDate = DateTime.Now;
                    c.PhoneNo      = vm.PhoneNo;
                    c.City         = vm.City;
                    c.Area         = vm.Area;
                    c.Street       = vm.Street;
                    c.Status       = vm.Status;

                    using (var tr = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (vm.Image != null && vm.Image.Length > 0)
                            {
                                c.ImgUrl = Utils.UploadImageU(env, "/Uploads/Customer/" + vm.Cnic, vm.Image, vm.ImgUrl);
                            }

                            db.Customer.Update(c);
                            db.SaveChanges();

                            tr.Commit();

                            if (c.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + c.ImgUrl) && vm.Image != null)
                            {
                                var source  = Tinify.FromFile(env.WebRootPath + c.ImgUrl);
                                var resized = source.Resize(new
                                {
                                    method = "fit",
                                    width  = 300,
                                    height = 168
                                });
                                await resized.ToFile(env.WebRootPath + c.ImgUrl);
                            }
                            ViewBag.Success = " Your data is successfully modified.";

                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl
                            }));
                        }
                        catch
                        {
                            tr.Rollback();
                            ModelState.AddModelError("", "We are having some problem in Updating your record.");
                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl
                            }));
                        }
                    }
                }
                else if (string.Equals(vm.Role.Trim(), "DBoy", StringComparison.OrdinalIgnoreCase))
                {
                    DeliveryBoy c = db.DeliveryBoy.Where(i => i.DeliveryBoyId == HttpContext.Session.Get <SessionData>(SessionUser).Id).FirstOrDefault();
                    c.FirstName    = vm.FirstName;
                    c.LastName     = vm.LastName;
                    c.Gender       = vm.Gender;
                    c.Dob          = vm.Dob;
                    c.Email        = vm.Email;
                    c.ModifiedDate = DateTime.Now;
                    c.PhoneNo      = vm.PhoneNo;
                    c.City         = vm.City;
                    c.Area         = vm.Area;
                    c.Street       = vm.Street;
                    c.Status       = vm.Status;

                    using (var tr = db.Database.BeginTransaction())
                    {
                        try
                        {
                            if (vm.Image != null && vm.Image.Length > 0)
                            {
                                c.ImgUrl = Utils.UploadImageU(env, "/Uploads/DBoy/" + vm.Cnic, vm.Image, vm.ImgUrl);
                            }
                            db.DeliveryBoy.Update(c);
                            db.SaveChanges();
                            tr.Commit();
                            if (c.ImgUrl != null && System.IO.File.Exists(env.WebRootPath + c.ImgUrl) && vm.Image != null)
                            {
                                var source  = Tinify.FromFile(env.WebRootPath + c.ImgUrl);
                                var resized = source.Resize(new
                                {
                                    method = "fit",
                                    width  = 300,
                                    height = 168
                                });
                                await resized.ToFile(env.WebRootPath + c.ImgUrl);
                            }
                            ViewBag.Success = " Your data is successfully modified.";

                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl
                            }));
                        }
                        catch
                        {
                            tr.Rollback();
                            ModelState.AddModelError("", "We are having some problem in Updating your record.");
                            return(View(new ModifyDetailsViewModel
                            {
                                Role = c.Role,
                                Status = c.Status,
                                FirstName = c.FirstName,
                                LastName = c.LastName,
                                Gender = c.Gender,
                                Dob = c.Dob,
                                Email = c.Email,
                                PhoneNo = c.PhoneNo,
                                City = c.City,
                                Area = c.Area,
                                Street = c.Street,
                                Cnic = c.Cnic,
                                ImgUrl = c.ImgUrl
                            }));
                        }
                    }
                }
            }
            return(RedirectToAction("ModifyDetails", "Account"));
        }
Exemplo n.º 29
0
        public async Task <ActionResult> EditUser(EditUserProfileViewModel model, HttpPostedFileBase image = null)
        {
            if (ModelState.IsValid)
            {
                var user = _userProfileService.GetUserProfile(u => u.Id == model.Id, i => i.ApplicationUser);

                if (user != null)
                {
                    user.Name = model.Name;
                    user.ApplicationUser.UserName             = model.Name;
                    user.ApplicationUser.Email                = model.Email;
                    user.ApplicationUser.EmailConfirmed       = model.EmailConfirmed;
                    user.ApplicationUser.PhoneNumber          = model.PhoneNumber;
                    user.ApplicationUser.PhoneNumberConfirmed = model.PhoneNumberConfirmed;
                    user.RegistrationDate = model.RegistrationDate;
                    user.Balance          = model.Balance;
                    if (image != null && (image.ContentType == "image/jpeg" || image.ContentType == "image/png"))
                    {
                        string extName    = System.IO.Path.GetExtension(image.FileName);
                        string fileName32 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);
                        string fileName48 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);
                        string fileName96 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);

                        // сохраняем файл в папку Files в проекте
                        string fullPath32 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName32);
                        string urlPath32  = Url.Content("~/Content/Images/Avatars/" + fileName32);
                        string fullPath48 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName48);
                        string urlPath48  = Url.Content("~/Content/Images/Avatars/" + fileName48);
                        string fullPath96 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName96);
                        string urlPath96  = Url.Content("~/Content/Images/Avatars/" + fileName96);

                        Tinify.Key = ConfigurationManager.AppSettings["TINYPNG_APIKEY"];
                        //Default.png

                        var name32 = user.Avatar32Path.Split('/').LastOrDefault();
                        var name48 = user.Avatar48Path.Split('/').LastOrDefault();
                        var name96 = user.Avatar96Path.Split('/').LastOrDefault();
                        if (name32 != null && name48 != null && name96 != null)
                        {
                            if (name32 != "Default32.png" && name48 != "Default48.png" && name96 != "Default96.png")
                            {
                                System.IO.File.Delete(Server.MapPath(user.Avatar32Path));
                                System.IO.File.Delete(Server.MapPath(user.Avatar48Path));
                                System.IO.File.Delete(Server.MapPath(user.Avatar96Path));
                            }
                        }

                        image.SaveAs(fullPath32);
                        image.SaveAs(fullPath48);
                        image.SaveAs(fullPath96);
                        try
                        {
                            using (var s = Tinify.FromFile(fullPath32))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 32,
                                    height = 32
                                });
                                await resized.ToFile(fullPath32);
                            }
                            using (var s = Tinify.FromFile(fullPath48))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 48,
                                    height = 48
                                });
                                await resized.ToFile(fullPath48);
                            }
                            using (var s = Tinify.FromFile(fullPath96))
                            {
                                var resized = s.Resize(new
                                {
                                    method = "fit",
                                    width  = 96,
                                    height = 96
                                });
                                await resized.ToFile(fullPath96);
                            }
                        }
                        catch (System.Exception)
                        {
                            // ignored
                        }


                        user.Avatar32Path = urlPath32;
                        user.Avatar48Path = urlPath48;
                        user.Avatar96Path = urlPath96;
                        _userProfileService.SaveUserProfile();
                    }
                    _userProfileService.SaveUserProfile();
                    return(RedirectToAction("FilterItemList"));
                }
            }
            return(HttpNotFound());
        }
Exemplo n.º 30
0
        public async Task <ActionResult> Upload(HttpPostedFileBase image)
        {
            var user = _userProfileService.GetUserProfileById(User.Identity.GetUserId());

            if (user != null)
            {
                if (image != null && image.ContentLength <= 1000000 && (image.ContentType == "image/jpeg" || image.ContentType == "image/png"))
                {
                    string extName    = System.IO.Path.GetExtension(image.FileName);
                    string fileName32 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);
                    string fileName48 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);
                    string fileName96 = String.Format(@"{0}{1}", System.Guid.NewGuid(), extName);

                    // сохраняем файл в папку Files в проекте
                    string fullPath32 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName32);
                    string urlPath32  = Url.Content("~/Content/Images/Avatars/" + fileName32);
                    string fullPath48 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName48);
                    string urlPath48  = Url.Content("~/Content/Images/Avatars/" + fileName48);
                    string fullPath96 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\Content\\Images\\Avatars", fileName96);
                    string urlPath96  = Url.Content("~/Content/Images/Avatars/" + fileName96);

                    Tinify.Key = ConfigurationManager.AppSettings["TINYPNG_APIKEY"];
                    //Default.png

                    var name32 = user.Avatar32Path.Split('/').LastOrDefault();
                    var name48 = user.Avatar48Path.Split('/').LastOrDefault();
                    var name96 = user.Avatar96Path.Split('/').LastOrDefault();
                    if (name32 != null && name48 != null && name96 != null)
                    {
                        if (name32 != "Default32.png" && name48 != "Default48.png" && name96 != "Default96.png")
                        {
                            System.IO.File.Delete(Server.MapPath(user.Avatar32Path));
                            System.IO.File.Delete(Server.MapPath(user.Avatar48Path));
                            System.IO.File.Delete(Server.MapPath(user.Avatar96Path));
                        }
                    }


                    image.SaveAs(fullPath32);
                    image.SaveAs(fullPath48);
                    image.SaveAs(fullPath96);
                    try
                    {
                        using (var s = Tinify.FromFile(fullPath32))
                        {
                            var resized = s.Resize(new
                            {
                                method = "thumb",
                                width  = 32,
                                height = 32
                            });
                            await resized.ToFile(fullPath32);
                        }
                        using (var s = Tinify.FromFile(fullPath48))
                        {
                            var resized = s.Resize(new
                            {
                                method = "thumb",
                                width  = 48,
                                height = 48
                            });
                            await resized.ToFile(fullPath48);
                        }
                        using (var s = Tinify.FromFile(fullPath96))
                        {
                            var resized = s.Resize(new
                            {
                                method = "thumb",
                                width  = 96,
                                height = 96
                            });
                            await resized.ToFile(fullPath96);
                        }
                    }
                    catch (System.Exception)
                    {
                        // ignored
                    }


                    user.Avatar32Path = urlPath32;
                    user.Avatar48Path = urlPath48;
                    user.Avatar96Path = urlPath96;
                    _userProfileService.SaveUserProfile();

                    //catch (TinifyAPI.Exception)
                    //{
                    //    return HttpNotFound();
                    //}

                    //catch (System.Exception)
                    //{
                    //    return HttpNotFound();
                    //}



                    return(RedirectToAction("Buy", "Offer"));
                }
            }
            return(HttpNotFound());
        }