Exemple #1
0
        public string UploadResize(int x, int y, string dir, HttpPostedFileBase file)
        {
            /*
            Para o uso dessa função é preciso adicionar o imageresizer
            que se encontra na seguinte URL: http://imageresizing.net/

            Para o funcionamento, voce deve passar como parametro
            (Largura, Altura, Diretorio onde vai ser salvo, arquivo)

            by:
                twitter: @DashTail
                facebook: /faelbcabral
                git: /rafacabral
            */

            var fileName = file.FileName;
            if (file != null && file.ContentLength > 0)
            {
                String FileExtn = System.IO.Path.GetExtension(file.FileName).ToLower();
                if (!(FileExtn == ".jpg" || FileExtn == ".png" || FileExtn == ".gif"))
                {
                    //@ViewBag.error = "msg de erro";
                }
                else
                {
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, dir + "" + fileName, new ImageResizer.ResizeSettings(
                                "width=" + x + ";height=" + y + ";format=jpg;mode=max"));
                    i.CreateParentDirectory = true; //Auto-create the uploads directory.
                    i.Build();
                }
            }
            return fileName;
        }
Exemple #2
0
        public static List<string> UploadAndRename(HttpPostedFileBase file)
        {
            const string uploadFolder = "~/Uploads/";

            if (file == null || file.ContentLength <= 0) throw new Exception("Image error: File is null or has no content.");

            var generatedFiles = new List<string>();
            var versions = new Dictionary<string, string>
            {
                {"_s", "width=160&height=160&crop=auto&format=jpg"},
                {"_x", "maxwidth=1280&maxheight=1280&format=jpg"}
            };

            // Generate a filename (GUIDs are best).
            var fileName = Path.Combine(uploadFolder, Guid.NewGuid().ToString());

            // Generate each version
            foreach (string suffix in versions.Keys)
            {
                // Let the image builder add the correct extension based on the output file type
                var imageJob = new ImageResizer.ImageJob(file, fileName + suffix + ".<ext>",
                    new ImageResizer.Instructions(versions[suffix]));
                imageJob.Build();
                generatedFiles.Add(fileName.Replace(uploadFolder, "") + suffix + ".jpg");
            }

            return generatedFiles;
        }
        private void changeOrientaion()//?
        {
            var userCookie = Request.Headers.GetCookies("session").FirstOrDefault();

            // change to appliction
            CookieState vals = userCookie["session"];
            string      ID   = HttpContext.Current.Application[vals["username"]].ToString();

            m_Conn = new MySql.Data.MySqlClient.MySqlConnection(Database.Connect());

            m_Conn.Open(); // open connection

            m_QueryStr = "SELECT Path FROM gis.photodetails WHERE ID = '" + ID + "'";
            m_Cmd      = new MySql.Data.MySqlClient.MySqlCommand(m_QueryStr, m_Conn);

            Reader = m_Cmd.ExecuteReader();
            List <String> path = new List <String>();

            while (Reader.Read())
            {
                path.Add(Reader[0].ToString());
            }

            string localfilepath = HttpContext.Current.Server.MapPath(path[0]);

            m_Conn.Close();
            ImageResizer.ImageJob i = new ImageResizer.ImageJob(localfilepath, localfilepath, new ImageResizer.Instructions("width=3000;height=3000;format=jpg;mode=max;autorotate=true"));
            i.Build();
        }
        /// <summary>
        /// Generate a thumbnail from frontpage of a PDF document.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="documentfile"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GenerateThumbnail(Document document, HttpPostedFileBase documentfile, string url)
        {
            if (document.documentUrl.Contains(".pdf"))
            {
                string filtype;
                string seofilename     = MakeSeoFriendlyDocumentName(documentfile, out filtype, out seofilename);
                string documentNameSeo = RegisterUrls.MakeSeoFriendlyString(document.name);

                string input  = Path.Combine(Server.MapPath(Constants.DataDirectory + Document.DataDirectory), document.register.seoname + "_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + "." + filtype);
                string output = Path.Combine(Server.MapPath(Constants.DataDirectory + Document.DataDirectory), document.register.seoname + "_thumbnail_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + ".jpg");
                GhostscriptWrapper.GenerateOutput(input, output, GsSettings());

                ImageResizer.ImageJob newImage =
                    new ImageResizer.ImageJob(output, output,
                                              new ImageResizer.Instructions("maxwidth=160;maxheight=300;quality=75"));

                newImage.Build();

                return(url + document.register.seoname + "_thumbnail_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + ".jpg");
            }
            else if (document.documentUrl.Contains(".xsd"))
            {
                return("/Content/xsd.svg");
            }
            else
            {
                return("/Content/pdf.jpg");
            }
        }
        public async Task<IActionResult> Create(IFormFile croppedImage1, IFormFile croppedImage2, int distance)
        {

            var uploads = Path.Combine(_environment.WebRootPath, "Uploads");

            if (croppedImage1.Length > 0 && croppedImage2.Length > 0)
            {
                var puzzleImageId = Guid.NewGuid().ToString();
                var fileName = string.Format("{0}.jpg", puzzleImageId);

                await croppedImage1.SaveAsAsync(Path.Combine(uploads, fileName));

                ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "400", fileName),
                                new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max"));

                img1.Build();

                ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "1065", fileName),
                                                new ImageResizer.Instructions("maxheight=1065;&scale=both;format=jpg;mode=max"));

                img2.Build();


                if (ModelState.IsValid)
                {
                    await _puzzleRepository.AddPuzzleAsync(User, puzzleImageId, distance, _shopRepository.GetUserShop(User).ID);
                }
            }

            return View();

        }
        public async Task <IActionResult> Create(IFormFile croppedImage1, IFormFile croppedImage2, int distance)
        {
            var uploads = Path.Combine(_environment.WebRootPath, "Uploads");

            if (croppedImage1.Length > 0 && croppedImage2.Length > 0)
            {
                var puzzleImageId = Guid.NewGuid().ToString();
                var fileName      = string.Format("{0}.jpg", puzzleImageId);

                await croppedImage1.SaveAsAsync(Path.Combine(uploads, fileName));

                ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "400", fileName),
                                                                       new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max"));

                img1.Build();

                ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "16-9", "1065", fileName),
                                                                       new ImageResizer.Instructions("maxheight=1065;&scale=both;format=jpg;mode=max"));

                img2.Build();


                if (ModelState.IsValid)
                {
                    await _puzzleRepository.AddPuzzleAsync(User, puzzleImageId, distance, _shopRepository.GetUserShop(User).ID);
                }
            }

            return(View());
        }
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;

                HttpPostedFile file     = files[0];
                string         fileName = DateTime.Now.Ticks.ToString() + "_" + file.FileName;

                if (context.Request.QueryString["type"] != null && context.Request.QueryString["type"].ToString() == "contentImage")
                {
                    string fname       = "~/UploadedImages/StaticPageImages/" + fileName;//context.Server.MapPath("~/UploadedImages/StaticPageImages/" + fileName);
                    var    instruction = new ImageResizer.Instructions();
                    instruction.Width       = 500;
                    instruction.Height      = 500;
                    instruction.Mode        = ImageResizer.FitMode.Max;
                    instruction.JpegQuality = 80;

                    ImageResizer.ImageJob imageJob = new ImageResizer.ImageJob(file, fname, instruction);
                    imageJob.Build();

                    //file.SaveAs(fname);

                    context.Response.ContentType = "text/plain";
                    context.Response.Write("/UploadedImages/StaticPageImages/" + fileName);
                }
            }
        }
        public string IncluirFoto(Guid assistidoId)
        {
            string base64String = string.Empty;

            if (HttpContext.Request.Files.AllKeys.Any())
            {
                var foto = HttpContext.Request.Files["foto"];

                var diretorioFoto = $"{HttpRuntime.AppDomainAppPath}\\fotos\\{assistidoId}.jpg";

                ImageResizer.ImageJob i = new ImageResizer.ImageJob(foto, diretorioFoto, new ImageResizer.ResizeSettings("width=300;height=300;format=jpg;mode=max"));

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

                using (var image = Image.FromFile(diretorioFoto))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        image.Save(m, image.RawFormat);
                        byte[] imageBytes = m.ToArray();

                        base64String = Convert.ToBase64String(imageBytes);
                    }
                }
            }

            return(base64String);
        }
        public static void OptimizeImage(HttpPostedFile file, int maxWidth, int maxHeight, string outputPath, int quality = 70)
        {
            ImageResizer.ImageJob newImage =
                new ImageResizer.ImageJob(file, outputPath,
                                          new ImageResizer.Instructions("maxwidth=" + maxWidth + ";maxheight=" + maxHeight + ";quality=" + quality));

            newImage.Build();
        }
        public static void OptimizeImage(HttpPostedFileBase file, int maxWidth, int maxHeight, string outputPath, int quality = 70)
        {
            ImageResizer.ImageJob newImage =
                new ImageResizer.ImageJob(file, outputPath,
                new ImageResizer.Instructions("maxwidth=" + maxWidth + ";maxheight=" + maxHeight + ";quality=" + quality));

            newImage.Build();
        }
Exemple #11
0
        public ActionResult Create([Bind(Include = "SaugatId,Title,Description,LinkUrl,ImageUrl,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Saugat saugat, HttpPostedFileBase ImageUrl, HttpPostedFileBase LinkUrl)

        {
            if (ModelState.IsValid)
            {
                db.Entry(saugat).State = EntityState.Added;
                saugat.CreatedBy       = User.Identity.GetUserId();
                saugat.CreatedDate     = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/saugat";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/saugat/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=200;height=200;format=jpg;mode=max"));
                    i.Build();

                    saugat.ImageUrl = imageUrl;

                    db.Saugats.Add(saugat);
                }


                if (LinkUrl != null)
                {
                    string pathToCreate = "~/Documents/Saugat";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension     = Path.GetExtension(LinkUrl.FileName);
                    string fileName      = Path.GetFileNameWithoutExtension(LinkUrl.FileName);
                    string id            = Guid.NewGuid().ToString();
                    string LinkUrlToSave = "/Documents/Saugat/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;
                    LinkUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    saugat.LinkUrl = LinkUrlToSave;
                }

                db.Saugats.Add(saugat);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(saugat));
        }
Exemple #12
0
        public ActionResult Edit([Bind(Include = "NewsId,Title,LinkUrl,ImageUrl,Description,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] News news, HttpPostedFileBase ImageUrl, HttpPostedFileBase LinkUrl)


        {
            if (ModelState.IsValid)
            {
                db.Entry(news).State = EntityState.Modified;

                news.ModifiedBy   = User.Identity.GetUserId();
                news.ModifiedDate = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/news";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/news/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=200;height=200;format=jpg;mode=max"));
                    i.Build();
                    news.ImageUrl = imageUrl;
                }
                else if (LinkUrl != null && LinkUrl.ContentLength > 0)
                {
                    string pathToCreate = "~/UploadedDocuments/News";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(LinkUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(LinkUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string linkurl   = "/UploadedDocuments/News/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;
                    LinkUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    // extract only the filename
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    // store the file inside ~/App_Data/uploads folder
                    news.LinkUrl = linkurl;

                    db.News.Add(news);
                }
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(news));
        }
        public HttpResponseMessage Get(string id, string type)
        {
            string orig = HttpContext.Current.Server.MapPath("~/snaps/orig/");
            string root = HttpContext.Current.Server.MapPath("~/snaps/" + type + "/");
            var path = root + id;
            var orig_path = orig + id;

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            if (File.Exists(path) == false)
            {

                // try regenerating it if the original file exists
                if(File.Exists(orig_path) == true) {

                    FileInfo fileInfo = new FileInfo(orig_path);

                    // generate 640px version (retina display)
                    string sz640_dir = HttpContext.Current.Server.MapPath("~/snaps/640/");
                    string filename = sz640_dir + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions(
                                    "width=640;height=900;format=jpg;mode=max;autorotate=true"));
                    i.CreateParentDirectory = true; //Auto-create the uploads directory.
                    i.Build();

                    // generate a 500px version
                    string sz500_dir = HttpContext.Current.Server.MapPath("~/snaps/500/");
                    filename = sz500_dir + id;
                    i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions(
                                    "width=500;height=900;format=jpg;mode=max;autorotate=true"));
                    i.CreateParentDirectory = true; //Auto-create the uploads directory.
                    i.Build();

                    // generate thumb version
                    string thumb_dir = HttpContext.Current.Server.MapPath("~/snaps/thumb/");
                    filename = thumb_dir + id;
                    i = new ImageResizer.ImageJob(orig_path, filename, new ImageResizer.Instructions(
                                    "width=75;height=75;format=jpg;mode=max;autorotate=true"));
                    i.CreateParentDirectory = true; //Auto-create the uploads directory.
                    i.Build();

                } else {
                    // doesn't exist.. so... do nothing
                    return new HttpResponseMessage();
                }

            }

            var stream = new FileStream(path, FileMode.Open);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType =
                 new MediaTypeHeaderValue("image/jpeg");
            result.StatusCode = HttpStatusCode.OK;

            return result;
        }
        private string SaveLogoOptimizedToDisk(HttpPostedFileBase file, string organizationNumber)
        {
            string filename = organizationNumber + "_" + Path.GetFileName(file.FileName);
            var    path     = Path.Combine(Server.MapPath(Constants.DataDirectory + Organization.DataDirectory), filename);

            ImageResizer.ImageJob newImage =
                new ImageResizer.ImageJob(file, path,
                                          new ImageResizer.Instructions("maxwidth=215;maxheight=215;quality=75"));

            newImage.Build();

            return(filename);
        }
        private string SaveImageOptimizedToDisk(HttpPostedFileBase file, string seo)
        {
            string filename = seo + "_thumb_" + Path.GetFileName(file.FileName);
            var    path     = Path.Combine(Server.MapPath(Constants.DataDirectory + "img/"), filename);

            ImageResizer.ImageJob newImage =
                new ImageResizer.ImageJob(file, path,
                                          new ImageResizer.Instructions("maxwidth=300;maxheight=1000;quality=75"));

            newImage.Build();

            return(filename);
        }
Exemple #16
0
        public static byte[] ResizeImage(byte[] imageBytes, int?height = null, int?width = null, string mode = "", int quality = 80)
        {
            if (height != null || width != null)
            {
                string z     = "";
                string y     = "";
                string x     = "";
                string scale = "";
                string q     = "";

                if (height != null && mode != "max")
                {
                    y = "maxheight=" + height + ";";
                }
                if (width != null && mode != "max")
                {
                    x = "maxwidth=" + width + ";";
                }
                if (mode == "max")
                {
                    y = "h=" + height + ";";
                    x = "w=" + width + ";";
                }
                if (mode == "crop")
                {
                    scale = "scale=both;";
                }
                if (!string.IsNullOrEmpty(mode))
                {
                    z = "mode=" + mode + ";";
                }

                q = "quality=" + quality + ";format=jpg;";

                MemoryStream stream = new MemoryStream();
                try
                {
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(imageBytes, stream, new ImageResizer.Instructions(x + y + z + scale + q));
                    i.Build();
                    return(stream.ToArray());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return(imageBytes);
            }
        }
Exemple #17
0
        private void GuardarFoto(HttpPostedFile foto)
        {
            if (foto != null && foto.ContentLength > 0)
            {
                var ext = Path.GetExtension(foto.FileName);

                var path = "~\\Content\\Images";
                var full = Path.Combine(path, "foto.jpg"); //cambiar nombre
                var tmp  = Path.GetTempFileName() + "." + ext;


                try
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    if (File.Exists(full))
                    {
                        File.Move(full, full.Replace(".jpg", DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".jpg"));
                    }

                    foto.SaveAs(tmp);
                    foto.SaveAs(full);

                    Stream stream = foto.InputStream;
                    System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

                    var k      = image.Height / image.Width;
                    var height = image.Height > 500 ? 500 : image.Height;
                    var width  = image.Height > 500 ? 500 / k : image.Width;;

                    var job = new ImageResizer.ImageJob(tmp, full, new ImageResizer.Instructions("width=" + width + ";height=" + height + ";format=jpg"));
                    job.Build();
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    Imagen imagen = new Imagen();
                    imagen.JugadorId  = LogicaJugador.FindAll().FirstOrDefault().JugadorId;
                    imagen.RutaImagen = full;
                    LogicaImagen.Add(imagen);

                    File.Delete(tmp);
                }
            }
        }
Exemple #18
0
        public static Models.Picture ReadPicture(HttpPostedFileBase upload)
        {
            if (upload == null)
            {
                return(null);
            }
            var avatar = new Models.Picture
            {
                FileName    = System.IO.Path.GetFileName(upload.FileName),
                PictureType = Models.PictureType.Avatar,
                ContentType = upload.ContentType
            };
            HttpPostedFileBase uploadforMini = upload;

            //make small
            upload.InputStream.Seek(0, 0);
            using (var stream = new System.IO.MemoryStream())
            {
                ImageResizer.ImageJob image = new ImageResizer.ImageJob(upload, stream, new ImageResizer.Instructions("width=200;height=200;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100"));

                image.Build();

                System.Drawing.Image   Image = System.Drawing.Image.FromStream(stream);
                System.IO.MemoryStream ms    = new System.IO.MemoryStream();
                Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                avatar.Content = ms.ToArray();
                //make smaller

                uploadforMini.InputStream.Seek(0, 0);
                using (var streamMini = new System.IO.MemoryStream())
                {
                    ImageResizer.ImageJob imageMini = new ImageResizer.ImageJob(uploadforMini, streamMini, new ImageResizer.Instructions("width=50;height=50;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100"));

                    imageMini.Build();

                    System.Drawing.Image   ImageMini = System.Drawing.Image.FromStream(streamMini);
                    System.IO.MemoryStream msMini    = new System.IO.MemoryStream();

                    ImageMini.Save(msMini, System.Drawing.Imaging.ImageFormat.Jpeg);
                    avatar.ContentMini = msMini.ToArray();

                    return(avatar);
                    //}
                }
            }
            //return null;
        }
        public ActionResult Create([Bind(Include = "PastExComMemberId,Name,Position,ImageUrl,Year,Linkedin,Facebook,Email,Mobile,Landline,Address,DOB,UniqueId,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] PastExComMember pastExComMember, HttpPostedFileBase ImageUrl)

        {
            if (ModelState.IsValid)
            {
                db.Entry(pastExComMember).State = EntityState.Added;
                pastExComMember.CreatedBy       = User.Identity.GetUserId();
                pastExComMember.CreatedDate     = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/pastExComMember";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/pastExComMember/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=200;height=200;format=jpg;mode=max"));
                    i.Build();

                    pastExComMember.ImageUrl = imageUrl;

                    db.PastExComMembers.Add(pastExComMember);
                }
                else
                {
                    db.PastExComMembers.Add(pastExComMember);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(pastExComMember));
        }
        public ActionResult Create([Bind(Include = "SitesetId,Phone,Address,Email,ImageUrl,FbId,TwitterId,GoogleId,InstagramId,LinkedinId,Copyright,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Siteset siteset, HttpPostedFileBase ImageUrl)

        {
            if (ModelState.IsValid)
            {
                db.Entry(siteset).State = EntityState.Added;
                siteset.CreatedBy       = User.Identity.GetUserId();
                siteset.CreatedDate     = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/siteset";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/siteset/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=200;height=200;format=jpg;mode=max"));
                    i.Build();

                    siteset.ImageUrl = imageUrl;

                    db.Sitesets.Add(siteset);
                }
                else
                {
                    db.Sitesets.Add(siteset);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(siteset));
        }
        public ActionResult Create([Bind(Include = "MainsponsorId,ImageUrl,Title,Phone,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Mainsponsor mainsponsor, HttpPostedFileBase ImageUrl)

        {
            if (ModelState.IsValid)
            {
                db.Entry(mainsponsor).State = EntityState.Added;
                mainsponsor.CreatedBy       = User.Identity.GetUserId();
                mainsponsor.CreatedDate     = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/mainsponsor";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/mainsponsor/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=308;height=270;format=jpg;mode=max"));
                    i.Build();

                    mainsponsor.ImageUrl = imageUrl;

                    db.Mainsponsors.Add(mainsponsor);
                }
                else
                {
                    db.Mainsponsors.Add(mainsponsor);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }

                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(mainsponsor));
        }
        public HttpResponseMessage Post()
        {
            Photo newPhoto = new Photo();

            // Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                // Skip unused file controls.
                if (file.ContentLength <= 0) continue;

                string guid = Guid.NewGuid().ToString();
                string fileName = guid + fileExtension;
                string src = hostName + hostContainer + "/" + fileName;

                // Add filename to srcList
                newPhoto = new Photo
                {
                    Id = guid,
                    DateTimeCreated = new DateTimeOffset(DateTime.UtcNow),
                    Source = src,
                    Width = photoWidth
                };

                // Retrieve reference to the blob we want to create            
                CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName);

                // Populate our blob with contents from the uploaded file.
                using (var ms = new MemoryStream())
                {
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(file.InputStream,
                            ms, new ImageResizer.ResizeSettings("width=" + photoWidth
                                + ";format=" + fileExtension));
                    i.Build();

                    blockBlob.Properties.ContentType = contentType;
                    ms.Seek(0, SeekOrigin.Begin);
                    blockBlob.UploadFromStream(ms);
                }
            }

            return Request.CreateResponse(HttpStatusCode.Created, newPhoto);
        }
Exemple #23
0
        public IActionResult Create(IFormFile croppedImage1, string shortDesc, string longDesc, decimal originalPrice, decimal discountPrice)
        {
            //Save image
            var uploads = Path.Combine(_environment.WebRootPath, "Uploads");

            if (croppedImage1.Length > 0)
            {
                var prizeImageId = Guid.NewGuid().ToString();
                var fileName     = string.Format("{0}.jpg", prizeImageId);

                croppedImage1.SaveAs(Path.Combine(uploads, fileName));

                ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "400", fileName),
                                                                       new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max"));

                img1.Build();

                ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "600", fileName),
                                                                       new ImageResizer.Instructions("maxheight=600;&scale=both;format=jpg;mode=max"));

                img2.Build();

                Prize newPrize = new Prize();
                newPrize.PrizeImage    = prizeImageId;
                newPrize.ShortDesc     = shortDesc;
                newPrize.LongDesc      = longDesc;
                newPrize.OriginalPrice = originalPrice;
                newPrize.DiscountPrice = discountPrice;

                newPrize.ShopId = 2;
                newPrize.Status = (int)EnumHelper.PrizeStatus.InProduction;

                if (ModelState.IsValid)
                {
                    _context.Prize.Add(newPrize);
                    _context.SaveChanges();
                }
            }

            return(View());
        }
Exemple #24
0
        public IActionResult Create(IFormFile croppedImage1, string shortDesc, string longDesc, decimal originalPrice, decimal discountPrice)
        {
            //Save image
            var uploads = Path.Combine(_environment.WebRootPath, "Uploads");
            if (croppedImage1.Length > 0)
            {
                var prizeImageId = Guid.NewGuid().ToString();
                var fileName = string.Format("{0}.jpg", prizeImageId);

                croppedImage1.SaveAs(Path.Combine(uploads, fileName));

                ImageResizer.ImageJob img1 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "400", fileName),
                                new ImageResizer.Instructions("maxheight=400;&scale=both;format=jpg;mode=max"));

                img1.Build();

                ImageResizer.ImageJob img2 = new ImageResizer.ImageJob(Path.Combine(uploads, fileName), Path.Combine(uploads, "Prizes", "600", fileName), 
                                                new ImageResizer.Instructions("maxheight=600;&scale=both;format=jpg;mode=max"));

                img2.Build();

                Prize newPrize = new Prize();
                newPrize.PrizeImage = prizeImageId;
                newPrize.ShortDesc = shortDesc;
                newPrize.LongDesc = longDesc;
                newPrize.OriginalPrice = originalPrice;
                newPrize.DiscountPrice = discountPrice;

                newPrize.ShopId = 2;
                newPrize.Status = (int)EnumHelper.PrizeStatus.InProduction;

                if (ModelState.IsValid)
                {
                    _context.Prize.Add(newPrize);
                    _context.SaveChanges();
                }
            }

            return View();

        }
Exemple #25
0
        public byte[] ProcessPicture(HttpPostedFileBase upload)
        {
            if (upload == null)
            {
                return(null);
            }


            upload.InputStream.Seek(0, 0);
            System.IO.Stream      stream = new System.IO.MemoryStream();
            ImageResizer.ImageJob image  = new ImageResizer.ImageJob(upload, stream, new ImageResizer.Instructions("width=50;height=50;crop=auto;format=jpg;anchor=middlecenter;autorotate=true;quality=100"));

            image.Build();



            System.Drawing.Image   Image = System.Drawing.Image.FromStream(stream);
            System.IO.MemoryStream ms    = new System.IO.MemoryStream();
            Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return(ms.ToArray());
        }
Exemple #26
0
        public ActionResult Edit([Bind(Include = "EventId,Title,LinkUrl,ImageUrl,EventDate,Description,Phone,Timing,Address,IsCompleted,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy,DelFlg")] Event @event, HttpPostedFileBase ImageUrl)


        {
            if (ModelState.IsValid)
            {
                db.Entry(@event).State = EntityState.Modified;

                @event.ModifiedBy   = User.Identity.GetUserId();
                @event.ModifiedDate = DateTime.Now;

                if (ImageUrl != null)
                {
                    string pathToCreate = "~/Images/@event";
                    if (!Directory.Exists(Server.MapPath(pathToCreate)))
                    {
                        //Now you know it is ok, create it
                        Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    }
                    string extension = Path.GetExtension(ImageUrl.FileName);
                    string fileName  = Path.GetFileNameWithoutExtension(ImageUrl.FileName);
                    string id        = Guid.NewGuid().ToString();
                    string imageUrl  = "/Images/@event/" + fileName + "" + /*main.MainId.ToString()*/ id + extension;

                    ImageUrl.SaveAs(Path.Combine(Server.MapPath(pathToCreate), fileName + "" + /*main.MainId.ToString()*/ id + extension));
                    string DestinationPath = Path.Combine(Server.MapPath(pathToCreate));
                    DestinationPath += "\\" + fileName + id;
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_thumb.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=200;height=200;format=jpg;mode=max"));
                    i.Build();
                    ImageResizer.ImageJob j = new ImageResizer.ImageJob(DestinationPath + extension, DestinationPath + "_list.jpg", new ImageResizer.ResizeSettings(
                                                                            "width=500;height=250;format=jpg;mode=crop"));
                    j.Build();
                    @event.ImageUrl = imageUrl;
                }
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(@event));
        }
        public virtual ActionResult Upload(HttpPostedFileBase image, string imageUrl)
        {
            try
            {

                var i = new ImageResizer.ImageJob(image ?? (object) imageUrl, "~/Content/Temp/<guid>.<ext>",
                                                  new ImageResizer.ResizeSettings(
                                                      string.Format("width={0};height={0};mode=max",
                                                                    MaxDimension))) {AllowDestinationPathVariables = true};
                i.Build();

                var sitePath = Server.MapPath(@"~");
                var relativePath = i.FinalPath.Replace(sitePath, @"~/");

                var url = ResolveServerUrl(VirtualPathUtility.ToAbsolute(relativePath), false);
            //    System.IO.File.Delete(i.FinalPath);

                return Json(new { success = true, imageUrl = url }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, error = ex.Message }, "text/html", JsonRequestBehavior.AllowGet);
            }
        }
Exemple #28
0
        public Guid ManageNewsUpdateAndCreate(ManageNewsModel manageNewsModel)
        {
            Content content;

            //var item1 = content.Content_Languages.Where(z => z.Title == manageNewsModel.Title);

            if (manageNewsModel.ID == Guid.Empty)//New
            {
                content                   = new Content();
                manageNewsModel.ID        = content.ID;
                content.Content_Languages = new List <Content_Language>();
                //----------- Duplicate Check ----
                if (content.Content_Languages.Where(z => z.Title == manageNewsModel.Title).Count() > 0)
                {
                    string a = manageNewsModel.Title;
                }
                //----------- Duplicate Check ----
                content.CreatedBy   = TSM.Model.TSMContext.CurrentUser.ID;
                content.CreatedDate = DateTime.UtcNow;
                content.ContentDate = manageNewsModel.ContentDate.Value.Date;
                //content.RecordID = manageNewsModel.RecordId;
                //content.RegionID = manageNewsModel.RegionID;
                //content.CountryID = manageNewsModel.CountryID;
                content.HrefLink = manageNewsModel.HrefLink;
                if (manageNewsModel.File != null)
                {
                    string fileName = DateTime.Now.Ticks.ToString() + "_" + manageNewsModel.File.FileName;
                    string path     = System.IO.Path.Combine(
                        HttpContext.Current.Server.MapPath("~/UploadedImages/NewsImages/"), fileName);
                    var instruction = new ImageResizer.Instructions();
                    instruction.Width       = 500;
                    instruction.Height      = 500;
                    instruction.Mode        = ImageResizer.FitMode.Max;
                    instruction.JpegQuality = 80;
                    ImageResizer.ImageJob imageJob = new ImageResizer.ImageJob(manageNewsModel.File, fileName, instruction);
                    try
                    {
                        imageJob.Build();
                    }
                    catch { }

                    manageNewsModel.File.SaveAs(path);


                    manageNewsModel.ImagePath = "/UploadedImages/NewsImages/" + fileName;
                }
            }
            else//update
            {
                if (manageNewsModel.File != null)
                {
                    string fileName = DateTime.Now.Ticks.ToString() + "_" + manageNewsModel.File.FileName;
                    string path     = System.IO.Path.Combine(
                        HttpContext.Current.Server.MapPath("~/UploadedImages/NewsImages/"), fileName);
                    var instruction = new ImageResizer.Instructions();
                    instruction.Width       = 500;
                    instruction.Height      = 500;
                    instruction.Mode        = ImageResizer.FitMode.Max;
                    instruction.JpegQuality = 80;
                    ImageResizer.ImageJob imageJob = new ImageResizer.ImageJob(manageNewsModel.File, fileName, instruction);
                    try
                    {
                        imageJob.Build();
                    }
                    catch { }
                    manageNewsModel.File.SaveAs(path);
                    manageNewsModel.ImagePath = "/UploadedImages/NewsImages/" + fileName;
                }

                manageNewsModel.GetNewsContent(manageNewsModel.ID);
                content                  = manageNewsModel.NewsContent;
                content.ContentDate      = manageNewsModel.ContentDate.Value.Date;
                content.LastModifiedBy   = TSM.Model.TSMContext.CurrentUser.ID;
                content.LastModifiedDate = DateTime.UtcNow;
                //content.Image = manageNewsModel.ImagePath;
            }
            //content.ID= new Guid();

            content.IsPublic = false;
            content.Type     = ContentType.News;
            content.Image    = manageNewsModel.ImagePath;
            //content.RecordID = manageNewsModel.RecordId;
            //content.RegionID = manageNewsModel.RegionID;
            //content.CountryID = manageNewsModel.CountryID;
            content.HrefLink = manageNewsModel.HrefLink;
            if (content.Content_Languages.Count <= 0) // New
            {
                content.Content_Languages.Add(new Content_Language
                {
                    LanguageID  = manageNewsModel.LanguageID,
                    Content     = content,
                    SubTitle    = manageNewsModel.SubTitle,
                    Summary     = manageNewsModel.Summary,
                    Description = manageNewsModel.Description,
                    Title       = manageNewsModel.Title
                });
            }
            else//Update
            {
                if (content.Content_Languages.Where(z => z.LanguageID == manageNewsModel.LanguageID).Count() > 0)//Update content with current lang id
                {
                    foreach (var item in content.Content_Languages.Where(z => z.LanguageID == manageNewsModel.LanguageID))
                    {
                        item.LanguageID  = manageNewsModel.LanguageID;
                        item.Content     = content;
                        item.SubTitle    = manageNewsModel.SubTitle;
                        item.Summary     = manageNewsModel.Summary;
                        item.Description = manageNewsModel.Description;
                        item.Title       = manageNewsModel.Title;
                        break;
                    }
                }
                else //No content is present with current lang id
                {
                    content.Content_Languages.Add(new Content_Language
                    {
                        LanguageID  = manageNewsModel.LanguageID,
                        Content     = content,
                        SubTitle    = manageNewsModel.SubTitle,
                        Summary     = manageNewsModel.Summary,
                        Description = manageNewsModel.Description,
                        Title       = manageNewsModel.Title
                    });
                }
            }
            content.IsActive   = true;//always active when new created or updated
            manageNewsModel.ID = content.ID;
            NewsService.Save(content);
            return(content.ID);
        }
        public async System.Threading.Tasks.Task <HttpResponseMessage> PostFileAsync()
        {
            var response = new HttpResponseMessage();

            var result = await Request.Content.ReadAsMultipartAsync();

            var isExif      = await result.Contents[1].ReadAsStringAsync();
            var xCord       = await result.Contents[2].ReadAsStringAsync();
            var yCord       = await result.Contents[3].ReadAsStringAsync();
            var filter      = await result.Contents[4].ReadAsStringAsync();
            var description = await result.Contents[5].ReadAsStringAsync();
            var accessToken = await result.Contents[6].ReadAsStringAsync();

            MySession token = new MySession(accessToken);

            if (AccessToken.CheckAccessToken(token).StatusCode != HttpStatusCode.BadRequest)
            {
                string username = AccessToken.searchUserByAccessToken(token.AccessToken);

                var httpRequest = HttpContext.Current.Request;

                foreach (string file in httpRequest.Files)
                {
                    //// get file extension
                    var    postedFile = httpRequest.Files[file];        // Get http request for POST
                    string fileString = postedFile.FileName.ToString(); // get photo name to extract extension
                    string fileExts   = Path.GetExtension(fileString);  // extract file extension (png, jpg, ect...)

                    string ID = generateID();                           // generate random ID for each photo

                    response.StatusCode = HttpStatusCode.OK;

                    //// save file with new ID
                    string localfilepath = HttpContext.Current.Server.MapPath("~//photos//" + ID + fileExts);
                    postedFile.SaveAs(localfilepath);

                    //// save thumbnail with new ID
                    string thumbnailFilepath = HttpContext.Current.Server.MapPath("~//photos//" + "thumbnail_" + ID + fileExts);

                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(postedFile, thumbnailFilepath, new ImageResizer.Instructions("width=100;height=100;format=jpg;mode=max;autorotate=true"));
                    i.Build();

                    int manualGPS = 0;

                    if (isExif != "true")
                    {
                        imageYellowBorder(ID);
                        manualGPS = 1;
                    }

                    savePhotoInServer(ID, username, fileExts, manualGPS, Double.Parse(xCord), Double.Parse(yCord), filter, description);
                }

                return(response);
            }

            //else
            response.StatusCode = HttpStatusCode.BadRequest;
            response.Content    = new StringContent("Please login to upload photos");

            return(response);
        }
Exemple #30
0
        private void ResizeImage(string originalPath, string destinationPath)
        {
            PointInCode("DrinkViewModel: ResizeImage");

            //Crop to square format
            ImageResizer.ImageJob i = new ImageResizer.ImageJob(originalPath, destinationPath, new ImageResizer.ResizeSettings(
               "height=200;format=png;mode=max;"));
            i.CreateParentDirectory = true; //Auto-create the uploads directory.
            i.Build();
            Uri assets = new Uri(BeursfuifPaths.AssetsPath);
            Uri image = new Uri(destinationPath);
            NewEditDrink.ImageString = assets.MakeRelativeUri(image).ToString();
        }
Exemple #31
0
        public async Task<ActionResult> AddPicture(UtilityBuildingModel model)
        {
            //ModelState.Clear();
            if (model.Id == 0)
            {
                ModelState.AddModelError(model.GetPropertyName(() => model.PhotoFile), "hotel missing");
            }

            if (model.PhotoFile == null)
            {
                ModelState.AddModelError(model.GetPropertyName(() => model.PhotoFile), "image missing");
            }

            // take just PhotoFile validation
            var errors = ModelState.Where(s => s.Key != model.GetPropertyName(() => model.PhotoFile));
            errors.ToList().ForEach(e => ModelState.Remove(e.Key));

            if (!ModelState.IsValid)
            {
                return PartialView("_BuildingPhotoes", model);
            }

            using (var db = new Models.OnLeaveContext())
            {
                // add pictures
                                
                //var resizedImage = ImageResizer.ImageBuilder.Current.Build(buffer, rSetting);
                //resizedImage.Save(@"C:\\Temp\" + Path.GetFileName(model.PhotoFile.FileName));

                int count = db.UtilityBuildingPhotoDetails.Count(pDetail => pDetail.UtilityBuildingId == model.Id);
                if (count >= 7 - 1)
                {
                    return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden, "maximum number picture exceeded");
                }
                
                using (var ms = new MemoryStream())
                {
                    var job = new ImageResizer.ImageJob(
                        model.PhotoFile,
                        ms,
                        new ImageResizer.Instructions("mode=crop;format=jpg;width=600;height=472;"));
                    
                    await Task.Run(() =>  job.Build());

                    var imageDb = new Photo
                    {
                        KeyWords = null,
                        Name = Path.GetFileName(model.PhotoFile.FileName),
                        Image = ms.ToArray()
                    };                    
                    db.Photos.Add(imageDb);

                    var imageDetail = new UtilityBuildingPhotoDetail
                    {
                        UtilityBuildingId = model.Id,
                        KeyWords = null,
                        PhotoId = imageDb.PhotoId
                    };

                    db.UtilityBuildingPhotoDetails.Add(imageDetail);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                    }

                    // get images
                    model.PhotoIds = db.UtilityBuildingPhotoDetails
                        .Where(pDetail => pDetail.UtilityBuildingId == model.Id)
                        .Select(pDetail => pDetail.PhotoId)
                        .ToList();
                }
            }

            return PartialView("_BuildingPhotoes", model);
        }