public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {
                // Calculate dimensions
                var top = Convert.ToInt32(t.Replace("-", "").Replace("px", ""));
                var left = Convert.ToInt32(l.Replace("-", "").Replace("px", ""));
                var height = Convert.ToInt32(h.Replace("-", "").Replace("px", ""));
                var width = Convert.ToInt32(w.Replace("-", "").Replace("px", ""));

                // Get file from temporary folder
                var fn = Path.Combine(Server.MapPath(MapTempFolder), Path.GetFileName(fileName));
                // ...get image and resize it, ...
                var img = new WebImage(fn);
                img.Resize(width, height);
                // ... crop the part the user selected, ...
                img.Crop(top, left, img.Height - top - AvatarStoredHeight, img.Width - left - AvatarStoredWidth);
                // ... delete the temporary file,...
                System.IO.File.Delete(fn);
                // ... and save the new one.
                var newFileName = Path.Combine(AvatarPath, Path.GetFileName(fn));
                var newFileLocation = HttpContext.Server.MapPath(newFileName);
                if (Directory.Exists(Path.GetDirectoryName(newFileLocation)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newFileLocation));
                }

                img.Save(newFileLocation);
                return Json(new { success = true, avatarFileLocation = newFileName });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
        public ActionResult EditImage(EditorInputModel editor)
        {
            string fileName = editor.Profile.ImageUrl;
            var image = new WebImage(HttpContext.Server.MapPath("/Images/Temp/") + fileName);

            double ratio = editor.Width / 620;
            //the values to crop off.
            double top = editor.Top * ratio;
            double left = editor.Left * ratio;
            double bottom = editor.Height - editor.Bottom * ratio;
            double right = editor.Width - editor.Right * ratio;

            image.Crop((int)top, (int)left, (int)bottom, (int)right);

            //the image size I need at the end
            image.Resize(620, 280);
            image.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News"), fileName));
            System.IO.File.Delete(Path.Combine(HttpContext.Server.MapPath("/Images/Temp/"), fileName));

            var imageThumb = image;
            imageThumb.Resize(65, 50);
            imageThumb.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News/Thumb"), fileName));
            editor.Profile.ImageUrl = fileName;
            return View("Index", editor.Profile);
        }
        public ActionResult Crop(ImageModel imageModel)
        {
            WebImage image = new WebImage(_PATH + imageModel.ImagePath);
            var height = image.Height;
            var width = image.Width;
            var top = imageModel.Top;
            var left = imageModel.Left;
            var bottom = imageModel.Bottom;
            var right = imageModel.Right;

            image.Crop(top, left, height - bottom, width - right);
            image.Resize(140, 200, false, false);
            image.Save(_PATH + imageModel.ImagePath);

            return RedirectToAction("Index");
        }
        public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {
                // Calculate dimensions
                var top = Convert.ToInt32(t.Replace("-", "").Replace("px", ""));
                var left = Convert.ToInt32(l.Replace("-", "").Replace("px", ""));
                var height = Convert.ToInt32(h.Replace("-", "").Replace("px", ""));
                var width = Convert.ToInt32(w.Replace("-", "").Replace("px", ""));

                // Get file from temporary folder
                var fn = Path.Combine(Server.MapPath(MapTempFolder), Path.GetFileName(fileName));
                // ...get image and resize it, ...
                var img = new WebImage(fn);
                img.Resize(width, height);
                // ... crop the part the user selected, ...
                img.Crop(top, left, img.Height - top - AvatarStoredHeight, img.Width - left - AvatarStoredWidth);
                // ... delete the temporary file,...
                System.IO.File.Delete(fn);
                // ... and save the new one.

                var newFileName = Path.GetFileName(fn);
                img.Save(Server.MapPath("~/" + newFileName));

                Account account = new Account(
                "lifedemotivator",
                "366978761796466",
                "WMYLmdaTODdm4U6VcUGhxapkcjI"
                );
                ImageUploadResult uploadResult = new ImageUploadResult();
                CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(account);
                var uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(Server.MapPath("~/" + newFileName)),
                    PublicId = User.Identity.Name + newFileName,
                };
                uploadResult = cloudinary.Upload(uploadParams);
                System.IO.File.Delete(Server.MapPath("~/" + newFileName));
                UrlAvatar = uploadResult.Uri.ToString();

                return Json(new { success = true, avatarFileLocation = UrlAvatar });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
        private WebImage CropImage(WebImage image, int width, int height)
        {
            var cropper = new Cropping();
            double multi = cropper.GetMultiplicator(new Size(image.Width, image.Height), new Size(width, height));

            double fWidth = image.Width*multi;
            double fHeight = image.Height*multi;

            image = image.Resize((int)fWidth, (int)fHeight,preserveAspectRatio:false    );
            int iWidth = image.Width;
            int iHeight = image.Height;
            int top = Math.Max((iHeight - height) / 2, 0);
            int left = Math.Max((iWidth - width) / 2, 0);
            int bottom = Math.Max(iHeight - (height + top), 0);
            int right = Math.Max(iWidth - (width + left), 0);
            return image.Crop(top, left, bottom, right);
        }
        public JsonResult CropImage(string coords, string url)
        {
            var coordinates = new JavaScriptSerializer().Deserialize<Dictionary<string, int>>(coords);
            var image = new WebImage(_userImagesService.GetImageStream(url));
            image.FileName = "cropped." + image.ImageFormat;
            image.Crop(
                coordinates["y1"],
                coordinates["x1"],
                image.Height - coordinates["y2"],
                image.Width - coordinates["x2"]);

            return
                Json(
                    _userImagesService.SaveUserImageStream(
                        new MemoryStream(image.GetBytes()),
                        image.FileName,
                        image.ImageFormat, image.Height, image.Width),
                    "text/plain");
        }
        public ActionResult Edit(EditorInputModel editor)
        {
            string fileName = editor.Profile.ImageUrl;
            Console.WriteLine("test");
            var image = new WebImage(HttpContext.Server.MapPath("/Images/") + fileName);
            //the values to crop off.
            double top = editor.Top;
            double left = editor.Left;
            double bottom = editor.Bottom;
            double right = editor.Right;

            image.Crop((int)top, (int)left, (int)bottom, (int)right);

            //the image size I wanted
            image.Resize(620, 280);
            image.Save(Path.Combine(HttpContext.Server.MapPath("/Images/News"), fileName));
            System.IO.File.Delete(Path.Combine(HttpContext.Server.MapPath("/Images/"), fileName));
            editor.Profile.ImageUrl = fileName;
            return View("Index", editor.Profile);
        }
Exemple #8
0
 public int UploadAjax(Stream InputStream, string fileName, bool thumbnail = true)
 {
     int num = -1;
     using (StreamReader streamReader = new StreamReader(InputStream))
     {
         string[] strArray = streamReader.ReadToEnd().Split(new char[1] { ',' });
         string str1 = strArray[0].Split(new char[1] { ':' })[1];
         byte[] numArray = Convert.FromBase64String(strArray[1]);
         if (numArray.Length > 0)
         {
             if (str1.Contains("image"))
             {
                 string imageFormat = str1.Split(new char[1] { ';' })[0].Replace("image/", "");
                 WebImage webImage = new WebImage(numArray);
                 if (webImage != null)
                 {
                     string str2 = "upload_" + (object)DateTime.Now.Ticks;
                     webImage.Save(this._Path + str2, imageFormat, true);
                     if (thumbnail)
                     {
                         webImage.Resize(this._ThumbHeight, this._ThumbWidth, true, false);
                         webImage.Crop(1, 1, 0, 0).Save(this._ThumbnailPath + str2, imageFormat, true);
                     }
                     num = 1;
                 }
             }
             else
             {
                 string str2 = "upload_" + (object)DateTime.Now.Ticks + new FileInfo(fileName).Extension;
                 TFile.StreamToFile((Stream)new MemoryStream(numArray), this._Path + str2);
                 num = 1;
             }
         }
     }
     return num;
 }
Exemple #9
0
        public ActionResult Edit(EditorInputViewModel editor)
        {
            // cleaning directory just for demonstrations
            foreach (var f in Directory.GetFiles(StorageCrop)) System.IO.File.Delete(f);

            var image = new WebImage(StorageRoot + editor.Imagem);

            int _height = (int)editor.Height;
            int _width = (int)editor.Width;

            if (_width > 0 && _height > 0)
            {
                image.Resize(_width, _height, false, false);

                int _top = (int)(editor.Top);
                int _bottom = (int)editor.Bottom;
                int _left = (int)editor.Left;
                int _right = (int)editor.Right;

                _height = (int)image.Height;
                _width = (int)image.Width;

                image.Crop(_top, _left, (_height - _bottom), (_width - _right));
            }

            var originalFile = editor.Imagem;

            var name = "profile-c" + Path.GetExtension(image.FileName);

            editor.Imagem = Url.Content(StorageCrop + name);
            image.Save(editor.Imagem);

            System.IO.File.Delete(Url.Content(StorageRoot + originalFile));

            return RedirectToAction("Index", "Home");
        }
Exemple #10
0
        public static string SaveSmallImageDetail(WebImage image, int widthRequired = 100, int heightRequired = 100)
        {
            if (image != null)
            {
                var width = image.Width;
                var height = image.Height;
                var filename = Path.GetFileName(image.FileName);
                if (width > height)
                {
                    var leftRightCrop = (width - height) / 2;
                    image.Crop(0, leftRightCrop, 0, leftRightCrop);
                }
                else if (height > width)
                {
                    var topBottomCrop = (height - width) / 2;
                    image.Crop(topBottomCrop, 0, topBottomCrop, 0);
                }

                if (image.Width > widthRequired)
                {
                    image.Resize(widthRequired, ((heightRequired * image.Height) / image.Width));
                }

                var filepath = Path.Combine(DefaulDetailImg, filename);
                image.Save(filepath);
                return filepath.TrimStart('~');

            }
            return "";
        }
Exemple #11
0
 public int UploadForm(HttpPostedFileBase file, bool thumbnail = true)
 {
     int num = -1;
     if (file.ContentLength > 0)
     {
         if (file.ContentType.Contains("image"))
         {
             WebImage webImage = new WebImage(file.InputStream);
             if (webImage != null)
             {
                 string imageFormat = file.ContentType.Replace("image/", "");
                 string str = "upload_" + (object)DateTime.Now.Ticks;
                 webImage.Save(this._Path + str, imageFormat, true);
                 if (thumbnail)
                 {
                     webImage.Resize(this._ThumbHeight, this._ThumbWidth, true, false);
                     webImage.Crop(1, 1, 0, 0).Save(this._ThumbnailPath + str, imageFormat, true);
                 }
                 num = 1;
             }
         }
         else
         {
             string str = "upload_" + (object)DateTime.Now.Ticks + new FileInfo(file.FileName).Extension;
             TFile.StreamToFile(file.InputStream, this._Path + str);
         }
     }
     return num;
 }
Exemple #12
0
        private string SaveImageFile(HttpPostedFileBase file, Guid id)
        {
            // Define destination
            string folderName = Url.Content(ConfigurationManager.AppSettings["NewsImage"]);

            if (string.IsNullOrWhiteSpace(folderName)) { throw new ArgumentNullException(); }

            string FileUrl = string.Format(folderName, id.ToString());
            string fullFileName = HttpContext.Server.MapPath(FileUrl);
            var serverPath = Path.GetDirectoryName(fullFileName);
            if (Directory.Exists(serverPath) == false)
            {
                Directory.CreateDirectory(serverPath);
            }


            var img = new WebImage(file.InputStream);
            int width = 1280;
            int height = 750;
            int minheight = 400;

            double ratio = (double)img.Width / img.Height;
            double desiredRatio = (double)width / height;

            if (ratio > desiredRatio)
            {
                height = Convert.ToInt32(width / ratio);
                if (height < minheight)
                {
                    int delta = Convert.ToInt32((minheight * ratio - img.Width) / 2);
                    img.Crop(0, delta, 0, delta);
                }
            }
            if (ratio < desiredRatio)
            {
                int delta = Convert.ToInt32((img.Height - img.Width / desiredRatio) / 2);
                img.Crop(delta, 0, delta, 0);
            }


            img.Resize(width, height, true, true);

            if (System.IO.File.Exists(fullFileName))
                System.IO.File.Delete(fullFileName);

            img.Save(fullFileName);

            return FileUrl;
        }
        public ActionResult Crop(CropForm form)
        {
            if (form.x <= 0 && form.y <= 0 && form.x2 <= 0 && form.y2 <= 0)
            {
                ModelState.AddModelError("", "You must provide a selection!");
                return View(form);
            }

            if (db.Resources.Any(x => x.Title == form.Title))
            {
                ModelState.AddModelError("Title", "Another Resource has this Title.");
                return View(form);
            }

            string oldImagePath = Path.Combine(Server.MapPath("~/ResourceUploads"), form.ResourceID.ToString());
            FileStream stream = new FileStream(oldImagePath, FileMode.Open);

            WebImage image = new WebImage(stream);

            int width = image.Width;
            int height = image.Height;

            image.Crop((int)Math.Ceiling(form.y), (int)Math.Ceiling(form.x), height - (int)Math.Ceiling(form.y2), width - (int)Math.Ceiling(form.x2));
            //image.Crop((int)form.y, (int)form.x, (int)form.y2, (int)form.x2);

            Resource newResource = new Resource
            {
                ID = Guid.NewGuid(),
                Title = form.Title,
                CreatorID = SiteAuthentication.GetUserCookie().ID,
                DateAdded = DateTime.Now,
                Type = form.Type,
                Source = form.Source,
                SourceTextColorID = form.SourceTextColorID
            };

            string newImagePath = Path.Combine(Server.MapPath("~/ResourceUploads"), newResource.ID.ToString());

            db.Resources.Add(newResource);

            image.Save(newImagePath, null, false);

            db.SaveChanges();

            return View("_CloseAndRefreshParent");
        }
        //private string GetWebsiteHtml(string url)
        //{
        //    WebRequest request = WebRequest.Create(url);
        //    WebResponse response = request.GetResponse();
        //    Stream stream = response.GetResponseStream();
        //    StreamReader reader = new StreamReader(stream);
        //    string result = reader.ReadToEnd();
        //    stream.Dispose();
        //    reader.Dispose();
        //    return result;
        //}

        private string SaveImageFile(string imageUrl, Guid id, int num)
        {
            // Define destination
            string folderName = Url.Content(ConfigurationManager.AppSettings["NewsImage"]);

            if (string.IsNullOrWhiteSpace(folderName)) { throw new ArgumentNullException(); }

            string FileUrl = num == 0 ? string.Format(folderName, id.ToString()) : string.Format(folderName, id.ToString() + "_" + num.ToString());
            string fullFileName = HttpContext.Server.MapPath(FileUrl);
            var serverPath = Path.GetDirectoryName(fullFileName);
            if (Directory.Exists(serverPath) == false)
            {
                Directory.CreateDirectory(serverPath);
            }

            // Generate unique file name
            //var fileName = id.ToString() + ".jpg";                                //Path.GetFileName(file.FileName);
            //fileName = SaveTemporaryAvatarFileImage(file, serverPath, fileName);
            WebImage img;
            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                img = new WebImage(stream);

                webResponse.Close();
            }
            catch (Exception ex)
            {
                return null;
            }






            int width = 1280;
            int height = 750;
            int minheight = 400;

            double ratio = (double)img.Width / img.Height;
            double desiredRatio = (double)width / height;

            if (ratio > desiredRatio)
            {
                height = Convert.ToInt32(width / ratio);
                if (height < minheight)
                {
                    int delta = Convert.ToInt32((minheight * ratio - img.Width) / 2);
                    img.Crop(0, delta, 0, delta);
                }
                //width = Convert.ToInt32(height * ratio);
            }
            if (ratio < desiredRatio)
            {
                int delta = Convert.ToInt32((img.Height - img.Width / desiredRatio) / 2);
                img.Crop(delta, 0, delta, 0);
            }


            img.Resize(width, height, true, true);





            //img.Resize(400, (int)(400 * ratio)); // ToDo - Change the value of the width of the image oin the screen
            //string fullFileName = string.Format(serverPath, id.ToString());

            if (System.IO.File.Exists(fullFileName))
                System.IO.File.Delete(fullFileName);

            img.Save(fullFileName);

            return FileUrl;
        }
        /// <summary>
        /// Resizes the image and crop to fit.
        /// </summary>
        /// <param name="sourceStream">The source stream.</param>
        /// <param name="destinationStream">The destination stream.</param>
        /// <param name="size">The size.</param>
        private void ResizeImageAndCropToFit(Stream sourceStream, Stream destinationStream, Size size)
        {
            using (var tempStream = new MemoryStream())
            {
                sourceStream.Seek(0, SeekOrigin.Begin);
                sourceStream.CopyTo(tempStream);

                var image = new WebImage(tempStream);

                // Make image rectangular.
                WebImage croppedImage;
                var diff = (image.Width - image.Height) / 2.0;
                if (diff > 0)
                {
                    croppedImage = image.Crop(0, Convert.ToInt32(Math.Floor(diff)), 0, Convert.ToInt32(Math.Ceiling(diff)));
                }
                else if (diff < 0)
                {
                    diff = Math.Abs(diff);
                    croppedImage = image.Crop(Convert.ToInt32(Math.Floor(diff)), 0, Convert.ToInt32(Math.Ceiling(diff)));
                }
                else
                {
                    croppedImage = image;
                }

                var resizedImage = croppedImage.Resize(size.Width, size.Height);

                var bytes = resizedImage.GetBytes();
                destinationStream.Write(bytes, 0, bytes.Length);
            }
        }
        public ActionResult Save(int x, int y, int x2, int y2, string fileName)
        {
            string ProfilDirSetting = Url.Content(ConfigurationManager.AppSettings["ProfileImage"]);

            if (string.IsNullOrWhiteSpace(ProfilDirSetting)) { throw new ArgumentNullException(); }

            string folderName = Url.Content(ConfigurationManager.AppSettings["TempDir"]);

            if (string.IsNullOrWhiteSpace(folderName)) { throw new ArgumentNullException(); }

            try
            {
                // Get file from temporary folder
                var fn = Path.Combine(Server.MapPath(Url.Content(ConfigurationManager.AppSettings["TempDir"])), Path.GetFileName(fileName));

                // Calculate dimesnions
                //int top = Convert.ToInt32(t);
                //int left = Convert.ToInt32(l);
                //int height = Convert.ToInt32(h);
                //int width = Convert.ToInt32(w);

                // Get image and resize it, ...
                var img = new WebImage(fn);

                // ... crop the part the user selected, ...
                img.Crop(y, x, (img.Height - y2) < 0 ? 0 : img.Height - y2, (img.Width - x2) < 0 ? 0 : img.Width - x2);
                img.Resize(_avatarWidth, _avatarHeight);
                // ... delete the temporary file,...
                System.IO.File.Delete(fn);
                // ... and save the new one.
                string newFileName = string.Format(ProfilDirSetting, Path.GetFileNameWithoutExtension(fn));
                string newFileLocation = HttpContext.Server.MapPath(newFileName);
                if (Directory.Exists(Path.GetDirectoryName(newFileLocation)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newFileLocation));
                }

                img.Save(newFileLocation);

                return Json(new { success = true, avatarFileLocation = newFileName + "?" + DateTime.Now.Millisecond.ToString() });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
Exemple #17
0
        /// <summary>
        /// Save file in our host
        /// </summary>
        /// <param name="image">Image which will be save</param>
        /// <param name="width">min Width</param>
        /// <param name="height">min Height</param>
        /// <param name="quality">quality of new image from 1 to 99</param>
        /// <param name="filePath">destination path</param>
        /// <returns>True: save is success AND ELSE</returns>
        private string SaveFileInHost(Stream image, int width, int height, string filePath)
        {
            try
            {
                if (image == null)
                    return string.Empty;
                var newImage = new WebImage(image);

                var original_width = newImage.Width;
                var original_height = newImage.Height;

                if (original_width > original_height)
                {
                    var leftRightCrop = (original_width - original_height) / 2;
                    newImage.Crop(0, leftRightCrop, 0, leftRightCrop);
                }
                else if (original_height > original_width)
                {
                    var topBottomCrop = (original_height - original_width) / 2;
                    newImage.Crop(topBottomCrop, 0, topBottomCrop, 0);
                }
                newImage.Resize(width, height);
                newImage.Save(filePath, "jpg");
                return filePath;
            }
            catch
            {
                return string.Empty;
            }
        }
        public static string ResizeAndCrop(string imagePath, string folderName, Guid guidId, int width, int height)
        {
            if (String.IsNullOrEmpty(imagePath))
            {
                return "";
            }
            string fileName = Path.GetFileName(imagePath);
            string filePathPhysical = HttpContext.Current.Server.MapPath(imagePath);
            string thumbFolderPath = HttpContext.Current.Server.MapPath(Path.Combine("~\\Thumbs\\", folderName, guidId.ToString(), width.ToString() + "x" + height.ToString()));
            string thumbFilePathVirtual = "~/Thumbs/" + folderName + "/" + guidId.ToString() + "/" + width.ToString() + "x" + height.ToString() + "/" + fileName;
            string thumbFilePathPhysical = HttpContext.Current.Server.MapPath(Path.Combine("~\\Thumbs\\", folderName, guidId.ToString(), width.ToString() + "x" + height.ToString(), fileName));

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

            if (File.Exists(thumbFilePathPhysical))
            {
                return thumbFilePathVirtual;
            }

            WebImage image = new WebImage(filePathPhysical);

            int originalWidth = image.Width;
            int originalHeight = image.Height;
            float originalRatio = (float)originalWidth / (float)originalHeight;

            float ratio = (float)(width) / (float)(height);

            if (ratio > originalRatio)
            {
                image.Resize(width, 9999, true, false);
                int overSize = image.Height - height;
                int toCrop = overSize / 2;
                int cropFix = 0;
                if (overSize % 2 != 0)
                {
                    cropFix = 1;
                }
                image.Crop(toCrop, 0, (toCrop + cropFix), 0);
            }
            else if (ratio < originalRatio)
            {
                image.Resize(9999, height, true, false);
                int overSize = image.Width - width;
                int toCrop = overSize / 2;
                int cropFix = 0;
                if (overSize % 2 != 0)
                {
                    cropFix = 1;
                }
                image.Crop(0, (toCrop + cropFix), 0, toCrop);
            }
            else
            {
                image.Resize(width, height, true, false);
            }
            image.Save(thumbFilePathPhysical);
            return thumbFilePathVirtual;
        }
 public string SaveJevelPhot(int top, int left, int height, int width, string path)
 {
     FileInfo f = new FileInfo(path);
     var img = new WebImage(path); // наше изображение
     img.Resize(width, height); // уменьшим его
     /********************************************************************************/
     int nHeight = img.Height - top - PhotoGallery.Height; // подготовим ширину и высоту
     int nWidth = img.Width - left - PhotoGallery.Width;
     if (nHeight < 0) nHeight = 0;
     /****************** Обрежим изображение, по выбранным кординатам ***************************************************/
     img.Crop(top, left, nHeight, nWidth);
     try
     {
         img.Save(JewelPHotoFolder + @"\big\" + f.Name);
         img.Resize(PhotoGalleryPreView.Width, PhotoGalleryPreView.Height);
         img.Save(JewelPHotoFolder + @"\small\" + f.Name);
         return f.Name;
     }
     catch (Exception)
     {
         throw new ArgumentException("Произошла ошибка при попытке сохранения изображени.");
     }
 }
        /// <summary>
        /// Created image thmbnail in PNG format: resizes the image and crops to fit.
        /// </summary>
        /// <param name="sourceStream">The source stream.</param>
        /// <param name="destinationStream">The destination stream.</param>
        /// <param name="size">The size.</param>
        private void CreatePngThumbnail(Stream sourceStream, Stream destinationStream, Size size)
        {
            using (var tempStream = new MemoryStream())
            {
                sourceStream.Seek(0, SeekOrigin.Begin);
                sourceStream.CopyTo(tempStream);

                var image = new WebImage(tempStream);

                // Make image rectangular.
                WebImage croppedImage;

                ImageFormat format = null;
                if (transparencyFormats.TryGetValue(image.ImageFormat, out format))
                {
                    using (Image resizedBitmap = new Bitmap(size.Width, size.Height))
                    {
                        using (Bitmap source = new Bitmap(new MemoryStream(image.GetBytes())))
                        {
                            using (Graphics g = Graphics.FromImage(resizedBitmap))
                            {
                                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                g.DrawImage(source, 0, 0, size.Width, size.Height);
                            }
                        }
                        using (MemoryStream ms = new MemoryStream())
                        {
                            resizedBitmap.Save(ms, ImageFormat.Png);
                            croppedImage = new WebImage(ms);
                        }
                    }
                }
                else
                {

                    var diff = (image.Width - image.Height) / 2.0;
                    if (diff > 0)
                    {
                        croppedImage = image.Crop(0, Convert.ToInt32(Math.Floor(diff)), 0, Convert.ToInt32(Math.Ceiling(diff)));
                    }
                    else if (diff < 0)
                    {
                        diff = Math.Abs(diff);
                        croppedImage = image.Crop(Convert.ToInt32(Math.Floor(diff)), 0, Convert.ToInt32(Math.Ceiling(diff)));
                    }
                    else
                    {
                        croppedImage = image;
                    }
                    croppedImage = croppedImage.Resize(size.Width, size.Height);
                }

                var resizedImage = croppedImage;

                var bytes = resizedImage.GetBytes();
                destinationStream.Write(bytes, 0, bytes.Length);
            }
        }
Exemple #21
0
        public ActionResult Save(string t, string l, string h, string w, string fileName)
        {
            try
            {

                // Get file from temporary folder
                var fn = Path.Combine(Server.MapPath("~/Temp"), Path.GetFileName(fileName));

                // Calculate dimesnions
                int top = Convert.ToInt32(t.Replace("-", "").Replace("px", ""));
                int left = Convert.ToInt32(l.Replace("-", "").Replace("px", ""));
                int height = Convert.ToInt32(h.Replace("-", "").Replace("px", ""));
                int width = Convert.ToInt32(w.Replace("-", "").Replace("px", ""));

                // Get image and resize it, ...
                var img = new WebImage(fn);
                img.Resize(width, height);
                // ... crop the part the user selected, ...

                img.Crop(top, left, img.Height - top - _avatarHeight, img.Width - left - _avatarWidth);
                // ... delete the temporary file,...
                System.IO.File.Delete(fn);
            /*
                string username = User.Identity.Name;

                var userprofile = from u in db.Users
                                  where u.Username == username
                                  select u;
            */
                Int64 UserID = Convert.ToInt64(User.Identity.Name);

                // Check if userID does exist
                var userprofile = from u in db.Users
                          where u.ID == UserID
                          select u;

                string userid = "-1";

                if (userprofile != null && userprofile.Count() > 0)
                {
                    userid = userprofile.First().ID.ToString();
                }

                // ... and save the new one.
                string newFileName = "/Images/ProfileImages/User/" + userid + "/" + Path.GetFileName(fn);
                //string newFileName = "/Images/ProfileImages/User/" + userid + "/" + "profileimage.png";
                string newFileLocation = HttpContext.Server.MapPath(newFileName);

                userprofile.First().ProfileImage = newFileName;

                if (Directory.Exists(Path.GetDirectoryName(newFileLocation)) == false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(newFileLocation));
                }

                DirectoryInfo folder = new DirectoryInfo(Path.GetDirectoryName(newFileLocation));

                foreach (FileInfo file in folder.GetFiles())
                {
                    file.Delete();
                }

                img.Save(newFileLocation);
                db.SaveChanges();

                return Json(new { success = true, avatarFileLocation = newFileName });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, errorMessage = "Unable to upload file.\nERRORINFO: " + ex.Message });
            }
        }
        private string SaveImageFile(HttpPostedFileBase file, Guid id)
        {
            // Define destination
            string folderName = Url.Content(ConfigurationManager.AppSettings["SponsorLogo"]);

            if (string.IsNullOrWhiteSpace(folderName)) { throw new ArgumentNullException(); }

            string FileUrl = string.Format(folderName, id.ToString() + Path.GetExtension(file.FileName));
            string fullFileName = HttpContext.Server.MapPath(FileUrl);
            var serverPath = Path.GetDirectoryName(fullFileName);
            if (Directory.Exists(serverPath) == false)
            {
                Directory.CreateDirectory(serverPath);
            }


            var img = new WebImage(file.InputStream);
            int width = 250;
            int height = 250;
            int minheight = 20;

            double ratio = (double)img.Width / img.Height;
            double desiredRatio = (double)width / height;

            if (ratio > desiredRatio)
            {
                height = Convert.ToInt32(width / ratio);
                if (height < minheight)
                {
                    int delta = Convert.ToInt32((minheight * ratio - img.Width) / 2);
                    img.Crop(0, delta, 0, delta);
                }
            }
            if (ratio < desiredRatio)
            {
                int delta = Convert.ToInt32((img.Height - img.Width / desiredRatio) / 2);
                img.Crop(delta, 0, delta, 0);
            }


            img.Resize(width, height, true, true);

            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(serverPath+"/"));
            FileInfo[] files = dir.GetFiles(id.ToString() + ".*");
            if (files.Any())
            {
                foreach (FileInfo dfile in files)
                {
                    System.IO.File.Delete(dfile.FullName);
                }

            }

            //if (System.IO.File.Exists(fullFileName))
            //    System.IO.File.Delete(fullFileName);

            img.Save(fullFileName);

            return FileUrl;
        }
        //---------------------------------------------------------------------------------------------------

        //--Изменят размер и обрезает изображение или просто изменяет размер---------------------------------
        public void GetResizeImage(int id, int rWidth = 320, int rHeight = 320, int cWidth = 0, int cHeight = 0)
        {
            ImageDetails img = repository.Load(id);
            WebImage wbImage = new WebImage(img.image);
            wbImage.Resize(rWidth, rHeight); //--изменяем размер картинки--

            int h = wbImage.Height, w = wbImage.Width;

            wbImage.Crop(cHeight, cWidth, cHeight, cWidth); //--обрезаем картинку--
            wbImage.FileName = img.title + ".jpg";

            wbImage.Write();
        }
Exemple #24
0
        public void GetThumbnail(string url)
        {
            if (url != null)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                WebImage image = new WebImage(response.GetResponseStream());

                var iwidth = image.Width;
                var iheight = image.Height;

                if (iwidth >= iheight)
                {
                    var leftRightCrop = (iwidth - iheight) / 2;
                    image.Crop(0, leftRightCrop, 0, leftRightCrop).Write();
                }
                else if (iheight > iwidth)
                {
                    var topBottomCrop = (iheight - iwidth) / 2;
                    image.Crop(topBottomCrop, 0, topBottomCrop, 0).Write();
                }
            }
            else
            {
                new WebImage("~/Content/Icons/no_image.jpg").Crop(1,1).Write();
            }
        }
Exemple #25
0
        public ActionResult CreateStep3(ImageInput editor)
        {
            var image = new WebImage("~" + editor.Image.ImageUrl);
            var height = image.Height;
            var width = image.Width;
            var tempUrl = editor.Image.ImageUrl;
            var saveUrl = @BlogGlobals.SlideImageFolder + Path.GetFileName(image.FileName);

            image.Crop((int)editor.Top, (int)editor.Left, (int)(height - editor.Bottom), (int)(width - editor.Right));
            image.Resize(190, 190, true, false);
            image.Save(saveUrl);
            System.IO.File.Delete(Server.MapPath(tempUrl));

            ViewBag.PostId = new SelectList(db.Posts, "PostId", "Title");
            ViewBag.imageUrl = saveUrl;

            Slide slide = new Slide();

            return View("CreateStep3", slide);
        }
        /// <summary>
        /// Crops the image.
        /// </summary>
        /// <param name="mediaImageId">The media image id.</param>
        /// <param name="version">The version.</param>
        /// <param name="x1">The x1.</param>
        /// <param name="y1">The y1.</param>
        /// <param name="x2">The x2.</param>
        /// <param name="y2">The y2.</param>
        public void CropImage(Guid mediaImageId, int version, int x1, int y1, int x2, int y2)
        {
            var imageEntity = GetImageEntity(mediaImageId, version);

            var downloadResponse = storageService.DownloadObject(imageEntity.OriginalUri);
            var image = new WebImage(downloadResponse.ResponseStream);
            var croppedImage = image.Crop(y1, x1, image.Height - y2, image.Width - x2);
            var bytes = croppedImage.GetBytes();
            var memoryStream = new MemoryStream(bytes);
            storageService.UploadObject(new UploadRequest { InputStream = memoryStream, Uri = imageEntity.FileUri });

            imageEntity.Width = croppedImage.Width;
            imageEntity.Height = croppedImage.Height;
            imageEntity.Size = bytes.Length;
            imageEntity.Version = version;

            UpdateThumbnail(imageEntity, ThumbnailSize);

            repository.Save(imageEntity);
        }