void btnUpload_Click(object sender, EventArgs e)
        {
            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                if (file.ContentLength <= 0)
                {
                    continue;                          //Skip unused file controls.
                }
                //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
                //Destination paths can have variables like <guid> and <ext>
                ImageJob i = new ImageJob(file, "~/uploads/<guid>_<filename:A-Za-z0-9>.<ext>", new ResizeSettings("width=200&height=200&format=jpg&crop=auto"));
                i.CreateParentDirectory = true; //Auto-create the uploads directory.
                i.Build();
            }

            //Here's an example of getting a byte array for sending to SQL

            ////Loop through each uploaded file
            //foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
            //    HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];

            //    //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
            //    ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto");

            //    using (MemoryStream ms = new MemoryStream()) {
            //        //Resize the image
            //        ImageBuilder.Current.Build(file, ms, resizeCropSettings);

            //        //Upload the byte array to SQL: ms.ToArray();
            //    }
            //}
        }
Example #2
0
        protected void txtUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
        {
            string counter        = DateTime.Now.Ticks.ToString();
            string ext            = Path.GetExtension(e.UploadedFile.FileName);
            string replaced_icode = txtICode.Text.ToLower().Replace("\\", "X1").Replace("/", "X2").Replace(":", "X3").Replace("*", "X4").Replace("?", "X5").Replace("\"", "X6").Replace("<", "X7").Replace(">", "X8").Replace("|", "X9");

            replaced_icode = replaced_icode.Replace("`", "Y001").Replace("~", "Y002").Replace("!", "Y1").Replace("@", "Y2").Replace("#", "Y3").Replace("$", "Y4").Replace("%", "Y5").Replace("^", "Y6").Replace("&", "Y7");
            replaced_icode = replaced_icode.Replace("(", "Y9").Replace(")", "Y0").Replace("-", "Z1").Replace("+", "Z2").Replace("_", "Z3").Replace("=", "Z4").Replace("[", "Z5").Replace("]", "Z6").Replace("{", "Z7").Replace("}", "Z8").Replace(";", "Z9").Replace(",", "C1").Replace(".", "C2") + counter;
            string filename = replaced_icode + ext;

            txtImageFilename.Text = filename;
            string strSavePath = "~\\ItemImages\\" + filename;
            ///hdImageName.Text = strSavePath;
            //e.UploadedFile.SaveAs(Server.MapPath(strSavePath));
            string url = ResolveClientUrl(filename);// + "?" + strSavePath + "?" + DateTime.Now.Ticks.ToString();

            e.CallbackData = url;

            foreach (string filekey in HttpContext.Current.Request.Files.Keys)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[filekey];
                if (file.ContentLength <= 0)
                {
                    continue;                          //Skip unused file controls.
                }
                ImageJob i = new ImageJob(file, "~\\itemImages\\" + filename,
                                          new ImageResizer.ResizeSettings("width=500;height=400;format=png;mode=max"));
                i.CreateParentDirectory = true; //Auto-create the uploads directory.
                i.Build();
                // AddImage(filename, strSavePath);
            }
        }
        protected void btnUploadAndGenerate_Click(object sender, EventArgs e)
        {
            Dictionary <string, string> versions = new Dictionary <string, string>();

            //Define the version to generate
            versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail
            versions.Add("_medium", "maxwidth=400&maxheight=400format=jpg");     //Fit inside 400x400 area, jpeg
            versions.Add("_large", "maxwidth=1900&maxheight=1900&format=jpg");   //Fit inside 1900x1200 area

            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                if (file.ContentLength <= 0)
                {
                    continue;                          //Skip unused file controls.
                }
                //Generate each version
                foreach (string suffix in versions.Keys)
                {
                    ImageJob i = new ImageJob(file, "~/uploads/<guid>" + suffix + ".<ext>", new ResizeSettings(versions[suffix]));
                    i.CreateParentDirectory = true; //Auto-create the uploads directory.
                    i.Build();
                }
            }
        }
Example #4
0
    public Photo(HttpPostedFileBase file, NameValueCollection defaultQuery = null, NameValueCollection preprocessingQuery = null)
    {
        Id           = Guid.NewGuid();
        OriginalName = file.FileName;
        string newPath = PathUtils.SetExtension(Id.ToString(), PathUtils.GetExtension(OriginalName));

        FilePath = newPath;

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

        if (preprocessingQuery == null || !Config.Current.Pipeline.IsAcceptedImageType(OriginalName))
        {
            file.SaveAs(Path.Combine(StoragePath, newPath));
        }
        else
        {
            var j = new ImageJob(file, Path.Combine(StoragePath, Id.ToString()), new ResizeSettings(preprocessingQuery));
            j.AddFileExtension = true;
            j.Build();
            FilePath = Path.GetFileName(j.FinalPath);
        }
        Query = defaultQuery != null ? defaultQuery : new NameValueCollection();
    }
Example #5
0
        public static string FileUploadResize(HttpPostedFileBase file, String parentFileName = null, bool ck = false)
        {
            if (file != null)
            {
                var allowedExtensions = new[] { ".png", ".gif", ".jpeg", ".jpg" };
                var checkextension    = Path.GetExtension(file.FileName).ToLower();

                if (!allowedExtensions.Contains(checkextension))
                {
                    return(null);
                }

                var fileName = (!string.IsNullOrEmpty(parentFileName) ? parentFileName + "_" : "") + Guid.NewGuid().ToString().Split('-').First() + "_" + file.FileName;
                fileName = fileName.Replace(" ", "");
                var pathName = System.Web.HttpContext.Current.Server.MapPath(Settings.ImageUploadFolderPath);

                if (ck)
                {
                    pathName = pathName + "/ckimages";
                }
                var path = Path.Combine(pathName, fileName);

                ImageJob i = new ImageJob(file, path, new ImageResizer.Instructions(
                                              "format=jpg;mode=max;scale=both")); // ----> ვინახავთ ფაილში
                i.CreateParentDirectory = true;                                   //Auto-create the uploads directory.
                i.Build();

                return(fileName);
            }

            return(null);
        }
 private void resizePhoto(Stream fileStream, string path)
 {
     using (FileStream destStream = new FileStream(path, System.IO.FileMode.Create))
     {
         ResizeSettings        rs  = new ResizeSettings("maxwidth=1024&maxheight=768");
         ImageResizer.ImageJob job = new ImageJob(fileStream, destStream, rs);
         job.Build();
     }
 }
Example #7
0
        protected virtual void ResizeImage(HttpPostedFileBase sourceFile, string targetFolder, string targetName, Instructions settings)
        {
            var target = string.Format("~{0}/{1}", targetFolder, targetName);

            ImageJob job = new ImageJob(sourceFile, target, settings);

            job.CreateParentDirectory = true;
            job.Build();
        }
Example #8
0
        protected void ImageSave(HttpPostedFileBase uploadFile, string physicalPath, int size, bool padding = false)
        {
            string query    = padding ? $"w={size};h={size};autorotate=true;" : $"maxwidth={size};maxheight={size};autorotate=true;";
            var    imageJob = new ImageJob(uploadFile, physicalPath, new Instructions(query))
            {
                CreateParentDirectory = true
            };

            imageJob.Build();
        }
Example #9
0
        /// <summary>
        /// Bu metod yüklene fotoğrafı yeniden boyutlandırıp belirtilen klasöre yükler ve dosya yolunu döner
        /// </summary>
        /// <param name="image"></param>
        /// <param name="subfolder"></param>
        /// <param name="width"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string ImageUpload(object image, string subfolder, int width, string format)
        {
            var resize = new ImageJob(image, "~/images/" + subfolder + "/<guid>", new Instructions("format=" + format + ";width=" + width + ";"))
            {
                CreateParentDirectory = true, AddFileExtension = true
            };

            resize.Build();

            return(Path.GetFileName(resize.FinalPath));
        }
Example #10
0
        /// <summary>
        /// Crops the original image and saves it to the specified path.
        /// </summary>
        /// <param name="destPath"></param>
        /// <param name="appendCorrectExtension">If true, the appropriate image extension will be added</param>
        public void Crop(string destPath, bool appendCorrectExtension)
        {
            string path = ImagePath != null ? ImagePath : CroppedUrl;

            //Fix relative paths
            if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("~") && !path.StartsWith("/"))
            {
                path = ResolveUrl(path); //No relative paths here.
            }

            //Fix domain-relative paths into app-relative paths if they're in the same application.
            if (path.StartsWith("/") && path.StartsWith(HostingEnvironment.ApplicationVirtualPath, StringComparison.OrdinalIgnoreCase))
            {
                path = "~/" + path.Substring(HostingEnvironment.ApplicationVirtualPath.Length).TrimStart('/');
            }

            Stream s = null;

            try {
                //Handle same-domain, external apps
                if (path.StartsWith("/"))
                {
                    s = GetUriStream(new Uri(new Uri(Page.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)), new Uri(path)));
                }
                else if (!path.StartsWith("~"))
                {
                    //Everything else
                    s = GetUriStream(new Uri(path));
                }

                ImageJob j = new ImageJob();
                j.Source           = s != null ? (object)s : path;
                j.Dest             = destPath;
                j.AddFileExtension = appendCorrectExtension;
                j.Settings         = new ResizeSettings(CroppedUrlQuerystring);

                NameValueCollection data = CroppedUrlQuerystring;
                j.Settings["cropxunits"] = data["cropxunits"];
                j.Settings["cropyunits"] = data["cropyunits"];
                j.Settings.Quality       = this.JpegQuality;
                if (!string.IsNullOrEmpty(this.ForcedImageFormat))
                {
                    j.Settings.Format = this.ForcedImageFormat;
                }
                j.Settings["crop"] = "(" + X + ", " + Y + ", " + (X + W) + ", " + (Y + H) + ")";

                j.Build();
            } finally {
                if (s != null)
                {
                    s.Dispose();
                }
            }
        }
Example #11
0
            public static Stream ToJpeg(HttpPostedFileBase file)
            {
                var jpegStream = new MemoryStream();

                var resizer = new ImageJob(file, jpegStream, new ResizeSettings("format=jpg;mode=max"));

                resizer.Build();

                jpegStream.Position = 0;
                return(jpegStream);
            }
Example #12
0
        private static void SaveImage(ImageSettings settings, Image img, string fileName)
        {
            var path = Path.Combine(basePath, settings.SubPath, fileName);

            if (settings.Width.HasValue || settings.Height.HasValue)
            {
                if (settings.Width.HasValue && settings.Height.HasValue)
                {
                    var imgJob = new ImageJob(img, path, new Instructions(new NameValueCollection
                    {
                        { "width", settings.Width.Value.ToString() },
                        { "height", settings.Height.Value.ToString() },
                        { "format", "jpg" },
                        { "mode", "crop" }
                    }));

                    imgJob.CreateParentDirectory = true;
                    imgJob.Build();
                }
                else if (settings.Width.HasValue)
                {
                    var imgJob = new ImageJob(img, path, new Instructions(new NameValueCollection
                    {
                        { "width", settings.Width.Value.ToString() },
                        { "format", "jpg" },
                        { "mode", "crop" }
                    }));

                    imgJob.CreateParentDirectory = true;
                    imgJob.Build();
                }
                else if (settings.Height.HasValue)
                {
                    var imgJob = new ImageJob(img, path, new Instructions(new NameValueCollection
                    {
                        { "height", settings.Height.Value.ToString() },
                        { "format", "jpg" },
                        { "mode", "crop" }
                    }));

                    imgJob.CreateParentDirectory = true;
                    imgJob.Build();
                }
            }
            else
            {
                var imgJob = new ImageJob(img, path, new Instructions());

                imgJob.CreateParentDirectory = true;
                imgJob.Build();
            }

            img.Dispose();
        }
Example #13
0
        private static MemoryStream ResizeImage(Stream downloaded)
        {
            var memoryStream = new MemoryStream();
            var settings     = string.Format("mode=crop&width={0}&height={1}", Convert.ToInt32(imgRszeWdth), Convert.ToInt32(imgRszeHgth));

            downloaded.Seek(0, SeekOrigin.Begin);
            var i = new ImageJob(downloaded, memoryStream, new Instructions(settings));

            i.Build();
            memoryStream.Position = 0;
            return(memoryStream);
        }
        public ServiceResult <byte[], Guid> ProcessAndSaveImage(byte[] source, string path)
        {
            var guid     = Guid.NewGuid();
            var imageJob = new ImageJob(source, path + guid, new Instructions("width=300&height=300&format=jpg"))
            {
                CreateParentDirectory = true,
                AddFileExtension      = true,
            };

            imageJob.Build();
            return(ServiceResult <byte[], Guid> .Success(File.ReadAllBytes(imageJob.FinalPath), guid));
        }
Example #15
0
        private static MemoryStream ResizeImage(byte[] downloaded, int width, int height)
        {
            var inputStream  = new MemoryStream(downloaded);
            var memoryStream = new MemoryStream();

            var settings = string.Format("width={0}&height={1}", width, height);
            var i        = new ImageJob(inputStream, memoryStream, new ResizeSettings(settings));

            i.Build();

            return(memoryStream);
        }
        public static void copyOriginalImageToRespectives(ImageType type, string filename, ResizeSettings rs, bool disposeSource, bool addFileExtensions)
        {
            string StrRootPath       = HostingEnvironment.MapPath("~/");
            string SourceFolder      = StrRootPath + @"Modules\AspxCommerce\AspxItemsManagement\uploads\" + @"" + filename + "";
            string DestinationFolder = StrRootPath + @"Modules\AspxCommerce\AspxItemsManagement\uploads\" + @"" + type + @"\" + filename + "";

            using (FileStream fileStream = new FileStream(SourceFolder, FileMode.Open))
            {
                ImageJob i = new ImageJob(fileStream, DestinationFolder, new Instructions(rs));
                i.CreateParentDirectory = false; //Auto-create the uploads directory.
                i.Build();
            }
        }
Example #17
0
        public static void Resize(string srcPath, string newFileName)
        {
            var options  = "maxwidth=1280&maxheight=1280&format=jpg";
            var destPath = HostingEnvironment.MapPath(Path.Combine(uploadFolder, newFileName)) + ".jpg";

            // Let the image builder add the correct extension based on the output file type
            var imageJob = new ImageJob(srcPath, destPath, new Instructions(options));

            imageJob.Build();

            // Delete Original
            Delete(srcPath);
        }
    private static void ResizeImage(Stream input, Stream output, int width)
    {
        var instructions = new Instructions
        {
            Width = width,
            Mode  = FitMode.Carve,
            Scale = ScaleMode.Both
        };
        var imageJob = new ImageJob(input, output, instructions);

        // Do not dispose the source object
        imageJob.DisposeSourceObject = false;
        imageJob.Build();
    }
Example #19
0
        public static string Resize(HttpPostedFileBase file, string directory, int width, int height, bool crop = false)
        {
            List <string> resultPaths = new List <string>();
            var           fileGuid    = Guid.NewGuid().ToString();
            string        mode        = crop ? "crop" : "max";
            var           image       = new ImageJob(file, "~" + directory + fileGuid + ".<ext>", new Instructions($"maxwidth={width}&maxheight={height}&mode={mode}"));

            image.CreateParentDirectory = true;
            image.Build();

            var path = fileGuid + ImageResizer.Util.PathUtils.GetExtension(image.FinalPath);

            return(path);
        }
Example #20
0
        public ActionResult Create(MatHang item, HttpPostedFileBase[] files)
        {
            ThongBaoMvc thongbao;

            item.Image = "";

            var user = kiemtra.getUser(User.Identity.Name);

            if (files[0] != null && files.Length > 0)
            {
                item.Directory = user.MaCN + "/" + BoDau.ConvertToUnsign3(item.Name);

                var pathfile = Server.MapPath("~/Content/Image/") + item.Directory + "/" + Path.GetFileNameWithoutExtension(files[0].FileName);

                var job = new ImageJob(files[0], pathfile, new Instructions("model=max;format=png;width=100;height=300;"));

                job.CreateParentDirectory = true;// tạo folder nếu chưa có
                job.AddFileExtension      = true;
                job.Build();

                item.Image = Path.GetFileNameWithoutExtension(files[0].FileName) + ".png";
            }

            ViewBag.LoaiCap1  = new SelectList(db.LoaiCap1s, "LoaiCap1Id", "Name");
            ViewBag.QuyCachId = new SelectList(db.QuyCachs, "QuyCachId", "Name");
            try
            {
                item.MaCN  = db.TaiKhoans.FirstOrDefault(s => s.UserName.Equals(User.Identity.Name)).MaCN;
                item.IsUse = true;

                db.MatHangs.Add(item);
                db.SaveChanges();
                //Ghi log
                LogMgr.AddLog(User.Identity.Name, (int)FunctionType.AddItem, "Thêm sản phẩm " + item.Name + "-" + item.ItemId);
                thongbao = new ThongBaoMvc {
                    CssClassName = "success", Message = "Thêm sản phẩm thành công"
                };
                TempData["ResultAction"] = thongbao;
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                thongbao = new ThongBaoMvc {
                    CssClassName = "danger", Message = "Lỗi"
                };
                TempData["ResultAction"] = thongbao;
                log.Error("Lỗi khi thêm sản phẩm", ex);
                return(View(item));
            }
        }
        public Stream Resize(Stream image, int?width, int?height, string mode)
        {
            var destinationStream = new MemoryStream();
            var resizedImage      = new ImageJob(
                image,
                destinationStream,
                new Instructions("width=" + width + ";height=" + height + ";mode=" + mode))
            {
                CreateParentDirectory = true
            };

            resizedImage.Build();

            return(destinationStream);
        }
        public void ResizeAndSave(byte[] image, int?width, int?height, string mode, string directory)
        {
            using (var stream = new MemoryStream(image))
            {
                var resizedImage = new ImageJob(
                    stream,
                    directory,
                    new Instructions("width=" + width + ";height=" + height + ";mode=" + mode + ";format=jpg"))
                {
                    CreateParentDirectory = true
                };

                resizedImage.Build();
            }
        }
Example #23
0
        public static Stream Resize(Stream image)
        {
            var result = new MemoryStream();

            result.Seek(0, SeekOrigin.Begin);
            ImageJob job = new ImageJob(image, result, new Instructions()
            {
                Width  = IMAGE_WIDTH,
                Height = IMAGE_HEIGHT,
                Mode   = FitMode.Stretch,
                Scale  = ScaleMode.Both
            });

            job.Build();
            return(result);
        }
Example #24
0
        public Task <HttpResponseMessage> Get(string id, int width, int height, bool isTemp)
        {
            try
            {
                string filePath = HttpContext.Current.Server.MapPath(mscUPLOAD);
                if (isTemp)
                {
                    filePath = HttpContext.Current.Server.MapPath(mscTEMP);
                }

                var destinationPath = Path.Combine(filePath, $"{id}.png");

                Instructions it = new Instructions()
                {
                    Width = width, Height = height
                };
                it.Mode = FitMode.Crop;
                if (!File.Exists(destinationPath))
                {
                    destinationPath = Path.Combine(filePath, "avatar.png");
                }
                if (File.Exists(destinationPath))
                {
                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                    using (FileStream fs = new FileStream(destinationPath, FileMode.Open, FileAccess.Read))
                    {
                        using (var originalStream = new MemoryStream())
                        {
                            ImageJob iJob = new ImageJob(fs, originalStream, it);
                            iJob.Build();
                            result.Content = new ByteArrayContent(originalStream.ToArray());
                        }
                    }
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                    return(Task.FromResult(result));
                }
                else
                {
                    return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)));
                }
            }
            catch (Exception ex)
            {
                CommonFunction.CommonLogError(ex);
            }
            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)));
        }
Example #25
0
        public ActionResult ChiNhanh(ChiNhanh cn, HttpPostedFileBase pic)
        {
            ThongBaoMvc thongbao;
            var         chinhanh = db.ChiNhanhs.FirstOrDefault(x => x.MaCN.Equals(cn.MaCN));

            if (pic != null)
            {
                var pathfile = Server.MapPath("~/Content/Images/") + cn.MaCN + "/" + Path.GetFileNameWithoutExtension(pic.FileName);

                var job = new ImageJob(pic, pathfile, new Instructions("model=max;format=png;width=100;height=300;"));

                job.CreateParentDirectory = true;// tạo folder nếu chưa có
                job.AddFileExtension      = true;
                job.Build();

                chinhanh.Logo = Path.GetFileNameWithoutExtension(pic.FileName) + ".png";
            }
            chinhanh.Name       = cn.Name;
            chinhanh.DiaChi     = cn.DiaChi;
            chinhanh.Email      = cn.Email;
            chinhanh.FaceBook   = cn.FaceBook;
            chinhanh.Fax        = cn.Fax;
            chinhanh.SDT        = cn.SDT;
            chinhanh.SoTaiKhoan = cn.SoTaiKhoan;
            chinhanh.WebSite    = cn.WebSite;


            try
            {
                db.SaveChanges();
                thongbao = new ThongBaoMvc {
                    CssClassName = "success", Message = "Thay đổi thông tin chi nhánh thành công."
                };
                TempData["ResultAction"] = thongbao;
                return(View(chinhanh));
            }
            catch (Exception ex)
            {
                thongbao = new ThongBaoMvc {
                    CssClassName = "danger", Message = "Lỗi."
                };
                TempData["ResultAction"] = thongbao;
                log.Error("Lỗi khi sửa thông tin chi nhánh: " + ex.Message);
            }
            return(View(cn));
        }
Example #26
0
        private byte[] ResizeImage(HttpPostedFileBase file)
        {
            var filename   = Path.GetFileName(file.FileName);
            var fileStream = file.InputStream;

            byte[] imageAsByteArray = null;

            using (var ms = new MemoryStream())
            {
                var instructions = new Instructions(InstructionsQueryString);
                var imageJob     = new ImageJob(fileStream, ms, instructions);
                imageJob.Build();
                imageAsByteArray = ms.ToArray();
            }

            return(imageAsByteArray);
        }
Example #27
0
        public ActionResult ChangeAvatar(IEnumerable <HttpPostedFileBase> files)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                    bool isValid = false;
                    try
                    {
                        using (var img = Image.FromStream(file.InputStream))
                        {
                            isValid = this.ValidImageFormats.Contains(img.RawFormat);
                        }

                        if (isValid)
                        {
                            var    user          = this.Data.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
                            string fileExtension = Path.GetExtension(file.FileName);
                            string fileName      = string.Format("{0}", user.Id);
                            string location      = Server.MapPath("~/img/Avatars");
                            if (!Directory.Exists(location))
                            {
                                Directory.CreateDirectory(location);
                            }

                            file.InputStream.Position = 0;
                            string   newFileName = Path.Combine(location, fileName + ImageSuffix);
                            ImageJob i           = new ImageJob(file, newFileName, new ResizeSettings(ImageSettings), false, true);
                            i.Build();
                            user.ProfilePicture = "/img/Avatars/" + fileName + ImageSuffix + ".jpg";
                            this.Data.SaveChanges();

                            return(RedirectToAction("Profile", new { username = user.UserName }));
                        }
                    }
                    catch (Exception)
                    {
                        return(PartialView("_ChangeAvatar"));
                    }
                }
            }

            return(PartialView("_ChangeAvatar"));
        }
Example #28
0
        /// <summary>
        /// Copies image file to the destination.The destination need not have the file but the destination must add the original file name in its path
        /// </summary>
        /// <param name="rs">The resize setting</param>
        /// <param name="SourceFile">The original image file</param>
        /// <param name="DestinationFolder">The path of the destination folder including the filename same as original image file</param>
        public static void copyOriginalImageToRespectives(ResizeSettings rs, string SourceFile, string DestinationFolder, AspxCommonInfo aspxCommonObj, IsWaterMark isWaterMark)
        {
            // string combinedPath = Path.Combine(SourceFolder, filename);

            if (isWaterMark.ToString() == "True")
            {
                //ResizeSettings settingObj =
                ApplyWaterMarkToImage(aspxCommonObj, rs, SourceFile, DestinationFolder);
            }
            else
            {
                using (FileStream fileStream = new FileStream(SourceFile, FileMode.Open))
                {
                    ImageJob i = new ImageJob(fileStream, DestinationFolder, new Instructions(rs));
                    i.CreateParentDirectory = false;     //Auto-create the uploads directory.
                    i.Build();
                }
            }
        }
        /// <summary>
        /// This is used for resizing the images.
        /// </summary>
        /// <param name="originalFilepath"></param>
        /// <param name="thumbFileName"></param>
        public void ResizeImage(string originalFilepath, string thumbFileName)
        {
            Image FullsizeImage = null;

            try
            {
                int NewHeight = 1100;
                int NewWidth  = 800;
                using (FullsizeImage = Image.FromFile(originalFilepath))
                {
                    // Prevent using images internal thumbnail
                    FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    FullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

                    if (FullsizeImage.Height > 500)
                    {
                        NewHeight = 1100;
                        // Resize with height instead
                        NewWidth = FullsizeImage.Width * NewHeight / FullsizeImage.Height;
                    }
                }

                FullsizeImage.Dispose();
                Dictionary <string, string> Versions = new Dictionary <string, string>
                {
                    { "_Thumb", "width=96&height=72&format=png&dpi=150" }
                };

                string thumbPath = System.IO.Path.Combine(IGroupUtility.Decrypt(ConfigurationManager.AppSettings[ConstantUtility.ConfigKeys.ThumbImagePath]), thumbFileName);

                ImageJob ObjImageJobThumbnail = new ImageJob(originalFilepath, thumbPath, new Instructions(Versions["_Thumb"]));
                ObjImageJobThumbnail.Build();
            }
            catch (Exception ex)
            {
                ErrorUtility.WriteError(ex);
            }
        }
Example #30
0
        public string SaveImage(int?width, int?height, HttpPostedFileBase image, string folder)
        {
            var guid = Guid.NewGuid();

            if (!width.HasValue && !height.HasValue)
            {
                _saverManager.SaveAndGetVirtualPath(image, folder + "{0}");
            }
            if (image.ContentLength <= 0)
            {
                throw new UserFriendlyException("No se encontro imagen");
            }
            var inst = new NameValueCollection {
                { "width", width.ToString() }, { "height", height.ToString() }
            };
            var i = new ImageJob(image, "~/" + folder + "/" + guid + ".<ext>", new Instructions(inst))
            {
                CreateParentDirectory = true
            };

            i.Build();
            return(folder + guid + "." + i.ResultFileExtension);
        }