Example #1
0
        public void ResizeImage(string _path, IFormFile uploadedFile, string file_name, int desiredWidth, int desiredHeight)
        {
            string webroot = _path;

            try
            {
                if (uploadedFile.Length > 0)
                {
                    using (var stream = uploadedFile.OpenReadStream())
                    {
                        var uploadedImage = System.Drawing.Image.FromStream(stream);

                        //decide how to scale dimensions
                        if (desiredHeight == 0 && desiredWidth > 0)
                        {
                            var img = ImageResize.ScaleByWidth(uploadedImage, desiredWidth); // returns System.Drawing.Image file
                            img.SaveAs(Path.Combine(webroot, file_name));
                        }
                        else if (desiredWidth == 0 && desiredHeight > 0)
                        {
                            var img = ImageResize.ScaleByHeight(uploadedImage, desiredHeight); // returns System.Drawing.Image file
                            img.SaveAs(Path.Combine(webroot, file_name));
                        }
                        else
                        {
                            var img = ImageResize.Scale(uploadedImage, desiredWidth, desiredHeight); // returns System.Drawing.Image file
                            img.SaveAs(Path.Combine(webroot, file_name));
                        }
                    }
                }
            }
            catch { }
            return;
        }
Example #2
0
        public File ResizeImage(IFormFile file)
        {
            using (var stream = file.OpenReadStream())
            {
                var uploadedImage = Image.FromStream(stream);
                var ms            = new MemoryStream();

                if (uploadedImage.Width > 640 && uploadedImage.Height > 480)
                {
                    Image img = ImageResize.Scale(uploadedImage, 640, 480);
                    img.Save(ms, ImageFormat.Png);
                }
                else
                {
                    Image img = ImageResize.Scale(uploadedImage, uploadedImage.Width, uploadedImage.Height);
                    img.Save(ms, ImageFormat.Png);
                }

                return(new File
                {
                    FileName = file.FileName,
                    MimeType = file.ContentType,
                    Content = ms.ToArray(),
                    LastModified = DateTime.Now.ToUniversalTime()
                });
            }
        }
Example #3
0
        public IActionResult SaveIMG(IFormFile file)
        {
            try
            {
                if (file != null)
                {
                    using (var stream = file.OpenReadStream())
                    {
                        var uploadedImage = Image.FromStream(stream);

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

                        int ratiO = height / width;

                        int widthNew = 500;

                        //returns Image file
                        var img = ImageResize.Scale(uploadedImage, widthNew, widthNew * ratiO);

                        var path = Path.Combine(
                            Directory.GetCurrentDirectory(), "Assert/ImagesBlog",
                            file.FileName);

                        img.SaveAs(path);

                        string url = string.Format("http://{0}/assert/imagesblog/{1}", Request.Host.ToString(), file.FileName);

                        return(Json(new
                        {
                            status = true,
                            originalName = file.FileName,
                            generatedName = file.FileName,
                            msg = "Image upload successful",
                            imageUrl = url
                        }));
                    }
                }
                return(Json(new
                {
                    status = false,
                    originalName = "Error",
                    generatedName = "Error",
                    msg = "Image upload failed",
                }));
            }
            catch (Exception e)
            {
                return(Json(new
                {
                    status = false,
                    originalName = "Error",
                    generatedName = "Error",
                    msg = "Image upload failed" + e,
                }));
            }
        }
Example #4
0
        public string changeImage(IHostingEnvironment _hostingEnvironment, IFormFile httpPostedFile, string folderName, int id)
        {
            if (httpPostedFile != null)
            {
                string directory = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/" + folderName + "/" + id);

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

                string uniqueFileName  = null;
                string uniqueFileName1 = null;

                string uploadsFolder = directory;
                uniqueFileName = Guid.NewGuid().ToString() + "_" + httpPostedFile.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                httpPostedFile.CopyTo(new FileStream(filePath, FileMode.Create));
                // shop.avatar = uniqueFileName;

                //string uploadsFolder1 = directory + "/thumb";
                //string filePath1 = Path.Combine(uploadsFolder1, uniqueFileName);
                //var input_Image_Path = filePath;
                // var output_Image_Path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/thumb");
                uniqueFileName1 = Guid.NewGuid().ToString() + "_" + httpPostedFile.FileName;
                using (var stream = httpPostedFile.OpenReadStream())
                {
                    var uploadedImage = Image.FromStream(stream);
                    var x             = uploadedImage.Width;
                    var y             = uploadedImage.Height;
                    if (x > y)
                    {
                        x = 175;
                        y = y / x * 175;
                    }
                    else
                    {
                        y = 150;
                        x = x / y * 150;
                    }
                    //returns Image file
                    var img = ImageResize.Scale(uploadedImage, x, y);

                    img.SaveAs(uploadsFolder + "/" + uniqueFileName1);
                }

                return("{" + '"' + "avatar" + '"' + ":" + '"' + uniqueFileName + '"' + "," + '"' + "thumb" + '"' + ":" + '"' + uniqueFileName1 + '"' + "}");
                //shop.thumb = uniqueFileName;
            }
            else
            {
                return("");
            }
        }
 public void CreateScaledImage(Image image, string path, int width, int height = 0)
 {
     if (height > 0)
     {
         var finalImage = ImageResize.Scale(image, width, height);
         finalImage.SaveAs(path);
     }
     else
     {
         var finalImage = ImageResize.ScaleByWidth(image, width);
         finalImage.SaveAs(path);
     }
 }
Example #6
0
        public async Task <string> ImagesUpload(IFormFile file, string directory, string directory2)
        {
            try {
                if (file != null)
                {
                    string filename = "";
                    var    rnd      = new Random();
                    int    rand     = rnd.Next(10, 99999999);
                    if (file.Length > 0 && file.Length < 20971520)
                    {
                        string extension = Path.GetExtension(file.FileName);
                        filename = Guid.NewGuid().ToString() + rand.ToString() + extension;
                        if (extension == ".jpg" || extension == ".png" || extension == ".jpeg" || extension == ".pjpeg" || extension == ".gif" || extension == "tiff")
                        {
                            string filePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), directory));

                            using (var fileStream = new FileStream(
                                       Path.Combine(filePath, filename),
                                       FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                            }
                            var newImage   = Image.FromFile(directory2 + filename);
                            var scaleImage = ImageResize.Scale(newImage, 1280, 1280);
                            scaleImage.SaveAs("" + directory2 + "\\1" + filename);
                            newImage.Dispose();
                            scaleImage.Dispose();
                            var oldImages = Path.Combine(Directory.GetCurrentDirectory(), directory, filename);
                            filename = "1" + filename;
                            System.IO.File.Delete(oldImages);
                        }
                        else
                        {
                            filename = "File must be either .jpg, .jpeg, .png and Maximum Size is 4MB";
                        }
                    }
                    return(filename);
                }
                else
                {
                    string fileName = "";
                    return(fileName);
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
Example #7
0
        public static void ResizeAndSaveImage(string inputFile, int maxWidth)
        {
            var img       = Image.FromFile(inputFile);
            var extension = System.IO.Path.GetExtension(inputFile);


            string tempfile = Environment.CurrentDirectory
                              + "\\" + DateTime.Now.Ticks.ToString()
                              + extension;


            int maxHeight = img.Height;


            if (maxWidth == 0)
            {
                maxWidth = img.Width;
            }


            var ratioX = (double)maxWidth / img.Width;
            var ratioY = (double)maxHeight / img.Height;
            var ratio  = Math.Min(ratioX, ratioY);


            var newWidth  = (int)(img.Width * ratio);
            var newHeight = (int)(img.Height * ratio);


            //resize the image to 600x400
            var newImg = ImageResize.Scale(img, newWidth, newHeight);


            //save new image
            newImg.SaveAs(tempfile);


            //dispose to free up memory
            img.Dispose();
            newImg.Dispose();


            // delete original file
            System.IO.File.Delete(inputFile);


            // rename tempfile
            System.IO.File.Move(tempfile, inputFile);
        }
        public void AddImage(IFormFile image, int id)
        {
            string directory = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/products");

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

            string uploadsFolder = directory + "/" + id;

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

            string uniqueFileName  = null;
            string uniqueFileName1 = null;

            uniqueFileName = Guid.NewGuid().ToString() + "_" + image.FileName;
            string filePath = Path.Combine(uploadsFolder, uniqueFileName);

            image.CopyTo(new FileStream(filePath, FileMode.Create));

            uniqueFileName1 = Guid.NewGuid().ToString() + "_resize" + "_" + image.FileName;
            using (var stream = image.OpenReadStream())
            {
                var uploadedImage = Image.FromStream(stream);
                var x             = uploadedImage.Width;
                var y             = uploadedImage.Height;
                if (x > y)
                {
                    x = 175;
                    y = y / x * 175;
                }
                else
                {
                    y = 150;
                    x = x / y * 150;
                }
                //returns Image file
                var img = ImageResize.Scale(uploadedImage, x, y);
                img = new Bitmap(stream);
                img.SaveAs(uploadsFolder + "/" + uniqueFileName1);
            }
            _productsRepository.AddImages(id, uniqueFileName1);
        }
Example #9
0
        public async Task <IActionResult> AddImageToGallery(Guid galleryId, IFormFileCollection uploads)
        {
            // Проверяем размер каждого изображения
            foreach (var image in uploads)
            {
                if (image.Length > 2097152)
                {
                    ModelState.AddModelError("Image", "Размер изображения должен быть не более 2МБ.");
                    break;
                }
            }

            List <ImageFile> images = new List <ImageFile>();

            foreach (var uploadedImage in uploads)
            {
                // Присваиваем загружаемому файлу уникальное имя на основе Guid
                string imageName = Guid.NewGuid() + "_" + uploadedImage.FileName;
                // Путь сохранения файла
                string pathNormal = "/files/images/normal/" + imageName; // изображение исходного размера
                string pathScaled = "/files/images/scaled/" + imageName; // уменьшенное изображение
                // сохраняем файл в папку files в каталоге wwwroot
                using (FileStream file = new FileStream(_appEnvironment.WebRootPath + pathNormal, FileMode.Create))
                {
                    await uploadedImage.CopyToAsync(file);
                }
                // Создаем объект класса Image со всеми параметрами
                ImageFile image = new ImageFile {
                    Id = Guid.NewGuid(), ImageName = imageName, ImagePathNormal = pathNormal, ImagePathScaled = pathScaled, TargetId = galleryId
                };
                // Добавляем объект класса Image в ранее созданный список images
                images.Add(image);

                // Делаем уменьшенную копию изображения
                var img         = Image.FromFile(_appEnvironment.WebRootPath + pathNormal);
                var scaledImage = ImageResize.Scale(img, 300, 300);
                scaledImage.SaveAs(_appEnvironment.WebRootPath + pathScaled, 50);
            }

            await websiteDB.Images.AddRangeAsync(images);

            await websiteDB.SaveChangesAsync();

            return(RedirectToAction("Gallery", "Home", new { galleryId }));
        }
Example #10
0
        public List <Image> DangTaiHinhAnh(IFormFileCollection AssetImage, string AssetID)
        {
            List <Image> lsAssetImage = new List <Image>();

            try
            {
                foreach (IFormFile file in AssetImage)
                {
                    Image          obj            = new Image();
                    string         image_name     = AssetID + DateTime.Now.ToString("yyMMddhhmmss");
                    string         file_name      = AssetID + "/" + image_name + Path.GetExtension(file.FileName);
                    CloudBlockBlob cloudBlockBlob = GenerateCloudBlockBlobImage(file_name);
                    cloudBlockBlob.UploadFromStream(file.OpenReadStream());
                    string path = cloudBlockBlob.Uri.AbsoluteUri + "?v=" + DateTime.Now.ToString("yyMMddhhmmss");

                    //Resize
                    var    img          = ImageResize.Scale(System.Drawing.Image.FromStream(file.OpenReadStream()), 200, 200);
                    string file_name200 = AssetID + "/" + image_name + "_200" + Path.GetExtension(file.FileName);
                    cloudBlockBlob = GenerateCloudBlockBlobImage(file_name200);
                    cloudBlockBlob.UploadFromStream(ToStream(img, ImageFormat.Png));
                    string pathThumbNail = cloudBlockBlob.Uri.AbsoluteUri + "?v=" + DateTime.Now.ToString("yyMMddhhmmss");

                    obj.Guid          = Guid.NewGuid().ToString();
                    obj.OriginalName  = file.FileName;
                    obj.ImageName     = image_name + Path.GetExtension(file.FileName);
                    obj.Path          = path;
                    obj.PathThumbNail = pathThumbNail;
                    obj.ReferenceId   = AssetID;
                    lsAssetImage.Add(obj);
                }
                return(lsAssetImage);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                //Ghi log va tra ve string
                return(lsAssetImage);
            }
        }
Example #11
0
        //public Uploaded UploadFile(IFormFile file)
        //{
        //    try
        //    {
        //        // Get current date time
        //        string Year = DateTime.Now.Year.ToString();
        //        string Month = DateTime.Now.Month.ToString();
        //        string Day = DateTime.Now.Day.ToString();

        //        string SubPathDirectory = "\\" + Year + "\\" + Month + "\\" + Day;
        //        string SubPathFileUrl = Year + "/" + Month + "/" + Day + "/";

        //        Commons common = new Commons();
        //        string Uploaded = common.DirectoryUploaded();
        //        // Create Uploads folder if not exists
        //        common.CreateDirectoryIfNotExists(SubPathDirectory);

        //        //1 check if the file length is greater than 0 bytes
        //        if (file.Length > 0)
        //        {
        //            if (!common.AllowMimeTypesFile())
        //                throw new Exception(Configs.NOT_FOUND_FILE);
        //            if (!common.CheckFileSize(file.Length))
        //                throw new Exception(Configs.FILE_SIZE_TOO_BIG);
        //            string SubName = Path.GetFileNameWithoutExtension(file.FileName);
        //            string FileName = common.CreateFileName(SubPathDirectory, file.FileName);
        //            //4 set the path where file will be copied
        //            string filePath = Path.GetFullPath(Path.Combine(common.GetCurrentDirectoryForUpload(SubPathDirectory)));
        //            //5 copy the file to the path
        //            using (var fileStream = new FileStream(Path.Combine(filePath, FileName), FileMode.Create))
        //            {
        //                file.CopyTo(fileStream);
        //            }
        //            SubPathFileUrl += FileName;

        //            Uploaded uploaded = new Uploaded(file.ContentType, FileName, SubName, file.Length, SubPathFileUrl);
        //            return uploaded;
        //        }
        //        else
        //        {
        //            throw new Exception(Configs.NOT_FOUND_FILE);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        // This upload one file
        public UploadedFull UploadFile(IFormFile file)
        {
            try
            {
                // Get current date time
                string Year  = DateTime.Now.Year.ToString();
                string Month = DateTime.Now.Month.ToString();
                string Day   = DateTime.Now.Day.ToString();

                string SubPathDirectory = "\\" + Year + "\\" + Month + "\\" + Day;
                string SubPathFileUrl   = Year + "/" + Month + "/" + Day + "/";

                Commons common   = new Commons();
                string  Uploaded = common.DirectoryUploaded();
                // Create Uploads folder if not exists
                common.CreateDirectoryIfNotExists(SubPathDirectory);

                //1 check if the file length is greater than 0 bytes
                if (file.Length > 0)
                {
                    if (!common.AllowMimeTypesFile())
                    {
                        throw new Exception(Configs.NOT_FOUND_FILE);
                    }
                    if (!common.CheckFileSize(file.Length))
                    {
                        throw new Exception(Configs.FILE_SIZE_TOO_BIG);
                    }
                    string SubName  = Path.GetFileNameWithoutExtension(file.FileName);
                    string FileName = common.CreateFileName(SubPathDirectory, file.FileName);
                    //4 set the path where file will be copied
                    string filePath = Path.GetFullPath(Path.Combine(common.GetCurrentDirectoryForUpload(SubPathDirectory)));

                    //5 copy the file to the path
                    using (var fileStream = new FileStream(Path.Combine(filePath, FileName), FileMode.Create))
                    {
                        file.CopyTo(fileStream);
                    }

                    Uploaded uploaded = new Uploaded(file.ContentType, FileName, SubName, file.Length, SubPathFileUrl + FileName, "original");

                    // This process Resize image
                    UploadedFull uploadedFull = new UploadedFull
                    {
                        Uploaded = uploaded
                    };

                    if (common.CheckImageTypeForResize(file.FileName))
                    {
                        string ResizeLargeFolder  = SubPathDirectory + "\\" + Configs.RESIZE_LAGRE_LABEL;
                        string ResizeMediumFolder = SubPathDirectory + "\\" + Configs.RESIZE_MEDIUM_LABEL;
                        string ResizeSmallFolder  = SubPathDirectory + "\\" + Configs.RESIZE_SMALL_LABEL;

                        common.CreateDirectoryIfNotExists(ResizeLargeFolder);
                        common.CreateDirectoryIfNotExists(ResizeMediumFolder);
                        common.CreateDirectoryIfNotExists(ResizeSmallFolder);

                        using (var stream = file.OpenReadStream())
                        {
                            var             uploadedImage = Image.FromStream(stream);
                            List <Uploaded> uploadeds     = new List <Uploaded>();
                            // Returns Image file
                            // For Large
                            var    ImgLarge      = ImageResize.Scale(uploadedImage, Configs.RESIZE_LARGE_WIDTH, Configs.RESIZE_LARGE_HEIGHT);
                            string filePathLarge = Path.GetFullPath(Path.Combine(common.GetCurrentDirectoryForUpload(ResizeLargeFolder)));
                            ImgLarge.SaveAs($"{filePathLarge}\\{FileName}");
                            string   SubFilePathLarge = SubPathFileUrl + "/" + ResizeLargeFolder + "/" + FileName;
                            Uploaded uploadedLarge    = new Uploaded(file.ContentType, FileName, SubName, file.Length, SubFilePathLarge, "large");
                            uploadeds.Add(uploadedLarge);

                            // For Medium
                            var    ImgMedium      = ImageResize.Scale(uploadedImage, Configs.RESIZE_MEDIUM_WIDTH, Configs.RESIZE_MEDIUM_HEIGHT);
                            string filePathMedium = Path.GetFullPath(Path.Combine(common.GetCurrentDirectoryForUpload(ResizeMediumFolder)));
                            ImgMedium.SaveAs($"{filePathMedium}\\{FileName}");
                            string   SubFilePathMedium = SubPathFileUrl + "/" + ResizeMediumFolder + "/" + FileName;
                            Uploaded uploadedMedium    = new Uploaded(file.ContentType, FileName, SubName, file.Length, SubFilePathMedium, "medium");
                            uploadeds.Add(uploadedMedium);

                            // For Small
                            var    ImgSmall      = ImageResize.Scale(uploadedImage, Configs.RESIZE_SMALL_WIDTH, Configs.RESIZE_SMALL_HEIGHT);
                            string filePathSmall = Path.GetFullPath(Path.Combine(common.GetCurrentDirectoryForUpload(ResizeSmallFolder)));
                            ImgSmall.SaveAs($"{filePathSmall}\\{FileName}");
                            string   SubFilePathSmall = SubPathFileUrl + "/" + ResizeSmallFolder + "/" + FileName;
                            Uploaded uploadedSmall    = new Uploaded(file.ContentType, FileName, SubName, file.Length, SubFilePathSmall, "small");
                            uploadeds.Add(uploadedSmall);

                            uploadedFull.ResizeUploaded = uploadeds;
                        }
                    }
                    return(uploadedFull);
                }
                else
                {
                    throw new Exception(Configs.NOT_FOUND_FILE);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #12
0
        public async Task <IActionResult> AddNews(AddNewsViewModel model, IFormFileCollection uploads)
        {
            // Проверяем размер каждого изображения
            foreach (var image in uploads)
            {
                if (image.Length > 2097152)
                {
                    ModelState.AddModelError("Image", "Размер изображения должен быть не более 2МБ.");
                    break;
                }
            }

            if (ModelState.IsValid)
            {
                News news = new News()
                {
                    Id        = Guid.NewGuid(),
                    NewsTitle = model.NewsTitle,
                    NewsBody  = model.NewsBody,
                    NewsDate  = DateTime.Now,
                    UserName  = User.Identity.Name
                };

                // Создаем список изображений
                List <ImageFile> images = new List <ImageFile>();
                foreach (var uploadedImage in uploads)
                {
                    // Присваиваем загружаемому файлу уникальное имя на основе Guid
                    string imageName = Guid.NewGuid() + "_" + uploadedImage.FileName;
                    // Путь сохранения файла
                    string pathNormal = "/files/images/normal/" + imageName; // изображение исходного размера
                    string pathScaled = "/files/images/scaled/" + imageName; // уменьшенное изображение
                    // сохраняем файл в папку files в каталоге wwwroot
                    using (FileStream file = new FileStream(_appEnvironment.WebRootPath + pathNormal, FileMode.Create))
                    {
                        await uploadedImage.CopyToAsync(file);
                    }
                    // Создаем объект класса Image со всеми параметрами
                    ImageFile image = new ImageFile {
                        Id = Guid.NewGuid(), ImageName = imageName, ImagePathNormal = pathNormal, ImagePathScaled = pathScaled, TargetId = news.Id
                    };
                    // Добавляем объект класса Image в ранее созданный список images
                    images.Add(image);

                    // Делаем уменьшенную копию изображения
                    var img         = Image.FromFile(_appEnvironment.WebRootPath + pathNormal);
                    var scaledImage = ImageResize.Scale(img, 300, 300);
                    scaledImage.SaveAs(_appEnvironment.WebRootPath + pathScaled, 50);
                }
                // Сохраняем новые объекты в БД
                await websiteDB.Images.AddRangeAsync(images);

                await websiteDB.News.AddAsync(news);

                await websiteDB.SaveChangesAsync();

                return(RedirectToAction("Index", "Home"));
            }

            // Редирект на случай невалидности модели
            return(View(model));
        }
Example #13
0
        public string upload(IHostingEnvironment _hostingEnvironment, IFormFile httpPostedFile, string folderName, int id)
        {
            if (httpPostedFile != null)
            {
                string directory = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/" + folderName);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string subDirectory = directory + "/" + id;
                if (!Directory.Exists(subDirectory))
                {
                    Directory.CreateDirectory(subDirectory);
                }

                string uniqueFileName  = null;
                string uniqueFileName1 = null;
                string uploadsFolder   = subDirectory;
                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                // string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/avatar");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + httpPostedFile.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                httpPostedFile.CopyTo(new FileStream(filePath, FileMode.Create));

                // shop.avatar = uniqueFileName;

                //string uploadsFolder1 = subDirectory + "/thumb";
                //if (!Directory.Exists(uploadsFolder1))
                //{
                //    Directory.CreateDirectory(uploadsFolder1);
                //}
                //string filePath1 = Path.Combine(uploadsFolder1, uniqueFileName);
                //var input_Image_Path = filePath;
                // var output_Image_Path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/thumb");
                uniqueFileName1 = Guid.NewGuid().ToString() + "_" + httpPostedFile.FileName;
                using (var stream = httpPostedFile.OpenReadStream())
                {
                    var uploadedImage = Image.FromStream(stream);
                    var x             = uploadedImage.Width;
                    var y             = uploadedImage.Height;
                    if (x > y)
                    {
                        x = 175;
                        y = y / x * 175;
                    }
                    else
                    {
                        y = 150;
                        x = x / y * 150;
                    }
                    //returns Image file
                    var img = ImageResize.Scale(uploadedImage, x, y);
                    img.SaveAs(uploadsFolder + "/" + uniqueFileName1);
                }

                return("{" + '"' + "avatar" + '"' + ":" + '"' + uniqueFileName + '"' + "," + '"' + "thumb" + '"' + ":" + '"' + uniqueFileName1 + '"' + "}");
                //shop.thumb = uniqueFileName;
            }
            else
            {
                string directory = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/" + folderName);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                string subDirectory = directory + "/" + id;
                if (!Directory.Exists(subDirectory))
                {
                    Directory.CreateDirectory(subDirectory);
                }

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

                //string uploadsFolder1 = subDirectory + "/thumb";
                //if (!Directory.Exists(uploadsFolder1))
                //{
                //    Directory.CreateDirectory(uploadsFolder1);
                //}

                string n              = id.ToString();
                string sourceDir      = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
                string backupDir      = Path.Combine(_hostingEnvironment.WebRootPath, "uploads/" + folderName + n);
                string uniqueFileName = null;
                uniqueFileName = "no-image.png";
                //System.IO.File.Copy(Path.Combine(sourceDir, "default.png"), Path.Combine(uploadsFolder, uniqueFileName), true);
                //System.IO.File.Copy(Path.Combine(sourceDir, "default.png"), Path.Combine(uploadsFolder1, uniqueFileName), true);
                //shop.avatar = uniqueFileName;
                //shop.thumb = uniqueFileName;
                return("{" + '"' + "avatar" + '"' + ":" + '"' + uniqueFileName + '"' + "," + '"' + "thumb" + '"' + ":" + '"' + uniqueFileName + '"' + "}");
            }
        }
Example #14
0
        public ActionResult ImageUpload(IFormFile file, IFormCollection col, string category)
        {
            if (file != null)
            {
                if (!Directory.Exists(directorypath))
                {
                    Directory.CreateDirectory(directorypath);
                }
                if (Path.GetExtension(file.FileName) == ".jpg" || Path.GetExtension(file.FileName) == ".JPG")
                {
                    if (!string.IsNullOrEmpty(category))
                    {
                        if (file.Length > 0)
                        {
                            ımager = Image.FromStream(file.OpenReadStream());
                            var exifinfo = ExifReader.ReadJpeg(file.OpenReadStream());
                            this.ımposition.ExifFNumber      = Convert.ToString(exifinfo.FNumber);
                            this.ımposition.ExifExposureTime = Convert.ToString(exifinfo.ExposureTime);
                            this.ımposition.Make             = exifinfo.Make;
                            this.ımposition.Model            = exifinfo.Model;
                            this.ımposition.Dates            = exifinfo.DateTime;
                            var    img      = ImageResize.Scale(ımager, 1296, 864);
                            string filename = Path.GetFileName(file.FileName);
                            img.SaveAs($"Contents\\upload\\{category}\\{filename}");
                            string added = category + "/" + filename;
                            resımagepath = Path.Combine(directorypath, Convert.ToString(added)).Replace(@"\", "/");
                        }
                    }
                }

                this.fblogin.UserFbId        = col["fbıd"];
                this.fblogin.UserName        = col["fbname"];
                this.fblogin.UserEmail       = col["fbemail"];
                this.ımposition.UserCategory = col["category"];
                this.ımposition.Approval     = Convert.ToInt32(col["app"]);
                this.ımposition.ImagePath    = resımagepath;
                this.ımposition.Story        = col["story"];

                list.Add(
                    new ArrayList {
                    this.fblogin.UserFbId,
                    this.fblogin.UserName,
                    this.fblogin.UserEmail,
                    this.ımposition.UserCategory,
                    this.ımposition.ImagePath,
                    this.ımposition.Story,
                    this.ımposition.Approval,
                    this.ımposition.ExifFNumber,
                    this.ımposition.ExifExposureTime,
                    this.ımposition.Make,
                    this.ımposition.Model,
                    this.ımposition.Dates
                }
                    );
                try
                {
                    this.connection.Database.ExecuteSqlRaw("AddImages @UserFbId,@UserName,@UserEmail,@UserCategory,@ImagePath,@Story,@Approval,@ExifExposureTime,@ExifFNumber,@Make,@Model,@Dates", new[] {
                        SqlParam("@UserFbId", this.fblogin.UserFbId),
                        SqlParam("@UserName", this.fblogin.UserName),
                        SqlParam("@UserEmail", this.fblogin.UserEmail),
                        SqlParam("@UserCategory", this.ımposition.UserCategory),
                        SqlParam("@ImagePath", this.ımposition.ImagePath),
                        SqlParam("@Story", this.ımposition.Story),
                        SqlParam("@Approval", this.ımposition.Approval),
                        SqlParam("@ExifExposureTime", this.ımposition.ExifExposureTime),
                        SqlParam("@ExifFNumber", this.ımposition.ExifFNumber),
                        SqlParam("@Make", this.ımposition.Make),
                        SqlParam("@Model", this.ımposition.Model),
                        SqlParam("@Dates", this.ımposition.Dates)
                    });
                }catch (SqlException ex)
                {
                    throw ex;
                }
            }
            return(Json(this.list));
        }