Esempio n. 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;
        }
Esempio n. 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()
                });
            }
        }
        private static Bitmap ResizeOrCropImage(Image bitmap, int width, int height, bool isFixed)
        {
            Bitmap result;

            if (width >= bitmap.Width && height >= bitmap.Height && !isFixed)
            {
                result = null;
            }
            else
            {
                Image tmpImage = bitmap;

                // Crop
                if (width > 0 && height > 0)
                {
                    tmpImage = isFixed
                        ? ImageResize.FixedSize(tmpImage, width, height, Color.White)
                        : ImageResize.Crop(tmpImage, width, height, ImageResize.AnchorPosition.Center);
                }

                // Resize
                if (width > 0 && width < bitmap.Width)
                {
                    tmpImage = ImageResize.ConstrainProportions(tmpImage, width, ImageResize.Dimensions.Width);
                }
                else if (height > 0 && height < bitmap.Height)
                {
                    tmpImage = ImageResize.ConstrainProportions(tmpImage, height, ImageResize.Dimensions.Height);
                }

                result = (Bitmap)tmpImage;
            }

            return(result);
        }
Esempio n. 4
0
        private Placemark PlacemarkFromPicture(PictureMetaData pic)
        {
            if (pic.GpsLongitude == null || pic.GpsLatitude == null)
            {
                return(null);
            }

            Placemark p = new Placemark();

            p.Name        = pic.IptcObjectName;
            p.Description = pic.IptcCaption;
            p.Latitude    = (double)pic.GpsLatitude.GetValue(pic.GpsLatitudeRef == "S");
            p.Longitude   = (double)pic.GpsLongitude.GetValue(pic.GpsLongitudeRef == "W");
            p.Tilt        = Settings.Default.KmzTilt;
            p.Heading     = Settings.Default.KmzHeading;
            p.Range       = Settings.Default.KmzRange;

            ImageResize.Dimensions d;
            if (pic.Image.Height > pic.Image.Width)
            {
                d = ImageResize.Dimensions.Height;
            }
            else
            {
                d = ImageResize.Dimensions.Width;
            }

            Image i = ImageResize.ConstrainProportions(pic.Image, Settings.Default.KmzPictureSize, d);

            p.SetImage(new FileInfo(pic.Filename).Name, i);

            return(p);
        }
Esempio n. 5
0
        public string UploadFile(IFormFile _file)
        {
            string _savePath = Path.Combine(_env.WebRootPath, @"images/uploads");

            if (!Directory.Exists(_savePath))
            {
                Directory.CreateDirectory(_savePath);
            }
            string _imgName      = Guid.NewGuid().ToString().Replace("-", string.Empty) + Path.GetExtension(_file.FileName);
            string _fullSavePath = Path.Combine(_savePath, _imgName);

            using (var _stream = _file.OpenReadStream()){
                var    _img  = Image.FromStream(_stream);
                Bitmap _temp = new Bitmap(_img.Width, _img.Height);
                using (Graphics g = Graphics.FromImage(_temp))
                {
                    g.DrawImage(_img, 0, 0);
                }
                _img = ImageResize.ScaleAndCrop(_temp, 500, 500, TargetSpot.Center);
                string _watermarkPath = Path.Combine(_env.WebRootPath, @"images/icons/logoWatermark.png");
                _img.ImageWatermark(_watermarkPath, TargetSpot.BottomRight);
                _img.SaveAs(_fullSavePath);

                _temp.Dispose();
                _img.Dispose();
            }
            return(_imgName);
        }
Esempio n. 6
0
        public async Task <UserPhoto> AddPhoto(IFormFile file)
        {
            if (file.Length > 0)
            {
                var uploadsFolderPath = Path.Combine(host.ContentRootPath, "wwwroot/uploads");
                if (!Directory.Exists(uploadsFolderPath))
                {
                    Directory.CreateDirectory(uploadsFolderPath);
                }

                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                var filePath = Path.Combine(uploadsFolderPath, fileName);

                using (var stream = file.OpenReadStream())
                {
                    var uploadedImage = Image.FromStream(stream);
                    var imageWidth    = uploadedImage.Width < 800?uploadedImage.Width:800;

                    var img = ImageResize.ScaleByWidth(uploadedImage, imageWidth);
                    img.SaveAs(filePath);

                    await stream.DisposeAsync();
                }

                var UserPhoto = new UserPhoto
                {
                    ImageFullPath = filePath,
                    ImageUrl      = fileName
                };

                return(UserPhoto);
            }

            throw new RestException(HttpStatusCode.BadRequest, new { UserPhoto = "Please select an image file" });
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            var formatter = new StringFormat()
            {
                FormatFlags = StringFormatFlags.LineLimit,
                Trimming    = StringTrimming.EllipsisCharacter
            };

            e.Graphics.Clear(Color.BackColor);
            e.Graphics.FillRectangle(new SolidBrush(Color.Tile),
                                     new Rectangle(0, 0, this.Height, this.Height));

            using (var scaledImage = ImageResize.ScaleImage(Icon, this.Width, this.Height))
            {
                var posX = (this.Height - scaledImage.Width) / 2;
                var posY = (this.Height - scaledImage.Height) / 2;

                e.Graphics.DrawImage(scaledImage, posX, posY);
            }

            e.Graphics.DrawString(Title, new Font("Arial", 12, FontStyle.Bold), Color.Body, 100, 10);
            e.Graphics.DrawString(Body, new Font("Arial", 8, FontStyle.Regular), Color.Body,
                                  new RectangleF(100, 40, (this.Width - 100), this.Height));
        }
Esempio n. 8
0
        /// <summary>
        /// Update the information of an answer
        /// </summary>
        /// <param name="id">answer id</param>
        /// <param name="txtanswer">answer text</param>
        /// <param name="fileanswer">answer file</param>
        /// <returns>returns the result to action</returns>
        public ActionResult UpdateAnswer(int id, string txtanswer, HttpPostedFileBase fileanswer)
        {
            AnswerRepository objanswer = new AnswerRepository(SessionCustom);

            objanswer.Entity.AnswerId = id;
            objanswer.LoadByKey();
            string strfile = objanswer.Entity.Image;

            if (fileanswer != null)
            {
                strfile = DateTime.Now.ToString("ddmmyyyyhhmmssFFF") + Path.GetExtension(fileanswer.FileName);
                string filePath = @"Files/" + objanswer.Entity.ContentId.ToString() + "/" + strfile;
                string fullPath = Path.Combine(Server.MapPath("~"), filePath);
                fileanswer.SaveAs(fullPath);

                ImageResize objimage = new ImageResize(Server.MapPath("~"));
                objimage.Prefix = "_";
                objimage.Width  = 255;
                objimage.Height = 130;
                bool resized = objimage.Resize(filePath, ImageResize.TypeResize.CropProportional);
                if (resized)
                {
                    System.IO.File.Delete(fullPath);
                    System.IO.File.Move(Path.Combine(Server.MapPath("~"), @"Files/" + objanswer.Entity.ContentId.ToString() + "/_" + strfile), fullPath);
                }
            }

            objanswer.Entity.Text  = txtanswer;
            objanswer.Entity.Image = strfile;

            objanswer.Update();
            this.InsertAudit("Update", this.Module.Name + " -> Answer" + id);
            return(this.View("AnswerDetail", objanswer.Entity));
        }
        /// <summary>
        /// Creates a resized version of the source image using the default resampler.
        /// </summary>
        public static Image <TPixel> Resize <TPixel, TState>(
            this ReadOnlyPixelRowsContext <TPixel> context,
            Size size,
            TState state = default,
            ProcessingProgressCallback <TState>?onProgress = null)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            //var inputImg = context.Image;
            //var outputImg = new Image<TPixel>(width, height);
            //
            //StbImageResize.stbir_resize(
            //    inputImg, inputImg.Width, inputImg.Height, inputImg.Stride, outputImg,
            //    outputImg.Width, outputImg.Height, outputImg.Stride, )

            var source = context.ToImage <Color>();
            var output = Image <Color> .CreateUninitialized(size);

            var progressCallback = onProgress == null ? (ResizeProgressCallback?)null :
                                   (p, r) => onProgress !.Invoke(state, p, r.ToMGRect());

            ImageResize.Resize(
                MemoryMarshal.AsBytes(source.GetPixelSpan()), source.Width, source.Height, source.ByteStride,
                MemoryMarshal.AsBytes(output.GetPixelSpan()), output.Width, output.Height, output.ByteStride,
                numChannels: 4,
                progressCallback);

            return(Image.LoadPixels <TPixel>(output));
        }
Esempio n. 10
0
        private void SavePoster(HttpPostedFileBase[] files, int filmId)
        {
            if (files == null || filmId == 0)
            {
                return;
            }

            var image = files[0];

            if (image != null)
            {
                DirectoryTools.CheckDirectoryExist(ImageOptions.PATH);

                var posters = posterSrv[filmId];
                DeletePoster(posters);

                var poster = new PosterImageEntity
                {
                    FilmId   = filmId,
                    MaxImage = ImageResize
                               .Resize(image, ImageOptions.PATH, ImageOptions.IMAGE_WIDTH_MAX_VERTICAL, ImageOptions.IMAGE_HEIGHT_MAX_VERTICAL),
                    MinImage = ImageResize
                               .Resize(image, ImageOptions.PATH, ImageOptions.IMAGE_WIDTH_MIN_VERTICAL, ImageOptions.IMAGE_HEIGHT_MIN_VERTICAL)
                };

                posterSrv.Add(poster);
            }
        }
Esempio n. 11
0
        private void NAVI_SETTING_Click(object sender, EventArgs e)
        {
            // 모든 Button의 Image를 Null로 변경 해서 초기화 //
            Navigation_Button_Initialize();

            // 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
            Button button = (Button)sender;

            button.Image = ImageResize.ResizeImage(Properties.Resources.setting_on, button.Width, button.Height);

            //VKeyboardViewer a = new VKeyboardViewer();
            //var password = a.ShowDialogAsync();
            VKeyboardViewer a = new VKeyboardViewer();

            a.ShowDialog();

            //a.Close();
            //await data;

            if (Repository.Instance.user_level == 5)
            {
                this.panel1.Controls.Clear();
                this.panel1.Controls.Add(Repository.Instance.p_setting);
            }
            else
            {
                MessageBox.Show("권한이 없어서 SETTING 화면에 들어갈 수 없습니다");
            }
        }
Esempio n. 12
0
        public ActionResult UpdateProfilePhoto()
        {
            var user              = GetUser();
            var photo             = new UserPhotos();
            var databasePathSmall = "";
            var databasePathBig   = "";
            var flag              = false;
            var resizer           = new ImageResize();
            var tracer            = "";

            try
            {
                if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];

                    if (file != null && file.ContentLength > 0)
                    {
                        Image imgSmall      = resizer.RezizeImage(Image.FromStream(file.InputStream, true, true), 190, 190);
                        Image imgBig        = resizer.RezizeImage(Image.FromStream(file.InputStream, true, true), 640, 640);
                        var   fileName      = Path.GetFileName(file.FileName);
                        var   fileNameSmall = fileName.Replace(".", "-tumbnail.");
                        var   fileNameBig   = fileName.Replace(".", "-big.");
                        var   pathSmall     = Path.Combine(Server.MapPath("~/images/post-images"), fileNameSmall);
                        var   pathBig       = Path.Combine(Server.MapPath("~/images/post-images"), fileNameBig);
                        databasePathSmall = "../../images/post-images/" + fileNameSmall;
                        databasePathBig   = "../../images/post-images/" + fileNameBig;
                        tracer           += pathSmall + " " + pathBig;
                        imgSmall.Save(pathSmall);
                        imgBig.Save(pathBig);
                        flag = true;
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new LoginResult(result: 0, error: ex.Message + " filename=" + tracer)));
            }
            user.UserProfilePhoto = databasePathSmall;
            _db.Users.Attach(user);
            photo.UserId         = user.Id;
            photo.UserPhotoSmall = databasePathSmall;
            photo.UserPhotoBig   = databasePathBig;
            _db.UserPhotos.Add(photo);
            _db.UsersLastMoves.Add(new UsersLastMoves {
                MoveDate = DateTime.Now, UserId = user.Id, UsersLastMoveText = " profil fotoğrafını güncelledi.", UsersMoveLink = "/users/album/" + user.Id
            });
            var entry = _db.Entry(user);

            entry.Property(e => e.UserProfilePhoto).IsModified = flag;
            try
            {
                _db.SaveChanges();
                return(Json(1));
            }
            catch (Exception)
            {
                return(Json(0));
            }
        }
Esempio n. 13
0
 /// <summary>
 /// 裁剪图片
 /// </summary>
 /// <param name="width">宽度</param>
 /// <param name="height">高度</param>
 /// <param name="quality">图片质量</param>
 /// <returns></returns>
 public ImageWrapper Crop(int width, int height, int quality = 100)
 {
     using (var stream = new MemoryStream(this.ImageBytes.ToArray()))
     {
         ImageSize imageSize = new ImageSize(width, height);
         byte[]    bytes     = ImageResize.Crop(stream, imageSize, quality);
         return(new ImageWrapper(bytes));
     }
 }
Esempio n. 14
0
 /// <summary>
 /// 调整图片的尺寸
 /// </summary>
 /// <param name="maxWidth">最大宽度</param>
 /// <param name="maxHeight">最大高度</param>
 /// <param name="isSameRate">是否保持比率</param>
 /// <returns></returns>
 public ImageWrapper Resize(int maxWidth, int maxHeight, bool isSameRate = false)
 {
     using (var stream = new MemoryStream(this.ImageBytes.ToArray()))
     {
         ImageSize imageSize = new ImageSize(maxWidth, maxHeight);
         byte[]    newBytes  = ImageResize.Resize(stream, imageSize, isSameRate);
         return(new ImageWrapper(newBytes));
     }
 }
Esempio n. 15
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,
                }));
            }
        }
Esempio n. 16
0
        public ActionResult CreateProduct(Product product)
        {
            var imageList = Session["imageList"] as List <ImageModel>;

            if (ModelState.IsValid && imageList.Count != 0)
            {
                var newProduct = new Product
                {
                    ProductId     = Guid.NewGuid(),
                    CategoryId    = product.CategoryId,
                    CompanyId     = product.CompanyId,
                    Description   = product.Description,
                    Count         = product.Count,
                    Price         = product.Price,
                    Name          = product.Name,
                    PriceOfBuying = product.PriceOfBuying,
                    ProductNumber = product.ProductNumber,
                };
                _productRepository.Save(newProduct);
                foreach (var image in imageList)
                {
                    var photo = new ProductPhoto
                    {
                        ProductPhotoId = Guid.NewGuid(),
                        ProductId      = newProduct.ProductId
                    };

                    var filename      = String.Format("{0}_{1}", photo.ProductPhotoId, image.ImageName);
                    var thumbfilename = String.Format("{0}_thumb_{1}", photo.ProductPhotoId, image.ImageName);

                    var path      = Path.Combine(Server.MapPath("~/Content/images/admin/ProductImage"), filename);
                    var thumbpath = Path.Combine(Server.MapPath("~/Content/images/admin/ProductImage"), thumbfilename);

                    photo.Photo = filename;


                    Image imagePhotoVert = image.Image;
                    using (var imagePhoto = ImageResize.ScaleByPercent(imagePhotoVert, 70))
                    {
                        imagePhoto.Save(path);
                    }

                    var i = imageList.IndexOf(image);
                    if (i == 0)
                    {
                        using (var thumbimagePhoto = ImageResize.Crop(imagePhotoVert, 70, 70, AnchorPosition.Center))
                        {
                            thumbimagePhoto.Save(thumbpath);
                            photo.ThumbnailPhoto = thumbfilename;
                        }
                    }
                    _productPhotoRepository.Save(photo);
                }
            }
            return(View());
        }
Esempio n. 17
0
        public ActionResult Company(OrgRegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Select(x => x.Value.Errors)
                             .Where(y => y.Count > 0)
                             .ToList();

                ViewBag.ListСlassifikate = new SelectList(classifierService.GetAll.ToList(), "Id", "Name");
                return(View(model));
            }

            AppUser user = new AppUser
            {
                UserName          = model.Email,
                Email             = model.Email,
                LockoutEnabled    = true,
                LockoutEndDateUtc = DateTime.Now.AddHours(7)
            };



            IdentityResult identResult = UserManager.Create(user, model.Password);

            if (!identResult.Succeeded)
            {
                AddErrorsFromResult(identResult);
                ViewBag.ListСlassifikate = new SelectList(classifierService.GetAll.ToList(), "Id", "Name");
                return(View(model));
            }
            model.SmallPathImage = ImageResize.Resize(model.LogoFile, AppConstants.directoryProfileAvatar, 40, 40);
            model.LargePathImage = ImageResize.Resize(model.LogoFile, AppConstants.directoryProfileAvatar, 135, 135);
            model.OwnerId        = user.Id;
            UserManager.AddToRole(user.Id, RoleConstant.RoleCompany);
            orgService.Edit(OrganizationMapper.ToEntity(model));
            profileService.Edit(UserProfileMapper.ToEntity(model));



#if _DEBUG
            SignInManager.SignIn(user, model.RememberMe, false);
            return(Redirect("~/"));
#endif

#if _RELEASE
            string token = UserManager.GenerateEmailConfirmationToken(user.Id);
            SendEmail(new EmailVerify
            {
                CallbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token }),
                cid         = Guid.NewGuid().ToString(),
                UserName    = user.UserName
            }, user.Id);

            return(View("TwoFactorMessage"));
#endif
        }
        public ActionResult Create(CategoriesViewModel model)
        {
            if (ModelState.IsValid)
            {
                var validImageTypes = new string[]
                {
                    "image/gif",
                    "image/jpeg",
                    "image/pjpeg",
                    "image/png"
                };

                if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
                {
                    ModelState.AddModelError("ImageUpload", "This field is required");
                }

                else if (!validImageTypes.Contains(model.ImageUpload.ContentType))
                {
                    ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
                }

                var category = new Category
                {
                    CategoryId          = model.CategoryId,
                    CategoryName        = model.CategoryName,
                    ImageURL            = model.ImageURL,
                    CategoryDescription = model.CategoryDescription
                };

                if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
                {
                    var uploadDir = "/uploads";

                    string finalImageName = "resize-" + model.ImageUpload.FileName.ToString();

                    var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
                    var imageUrl  = Path.Combine(uploadDir, finalImageName);

                    //Resize Image
                    ImageResize.ResizeImage(model.ImageUpload);

                    model.ImageUpload.SaveAs(imagePath);
                    category.ImageURL = imageUrl;
                }

                db.Categories.Add(category);
                db.SaveChanges();

                TempData["SuccessMessage"] = "<div class='alert alert-success w-fade-out'><strong> Success!</strong> New Category Created</div>";
                return(RedirectToAction("Index"));
            }

            return(View());
        }
Esempio n. 19
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("");
            }
        }
Esempio n. 20
0
        private void btn_Scheduling_Mode_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("스케줄모드로 변경 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                System.Windows.Forms.Button button = (System.Windows.Forms.Button)sender;

                btn_Manual_Mode.Image                = null;
                btn_Scheduling_Mode.Image            = ImageResize.ResizeImage(Properties.Resources.RUN_003, button.Width, button.Height);
                Repository.Instance.current_pcs_mode = 3;   // 3 indicates Scheduling Mode
            }
        }
Esempio n. 21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string imgPath;

        if (Request.QueryString["ImageId"] != null)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ImageId"].ToString()))
            {
                imgPath = Request.QueryString["ImageId"].ToString();
                if (!string.IsNullOrEmpty(imgPath))
                {
                    bool grande;
                    try
                    {
                        if (Request.QueryString["img"].ToString() != null)
                        {
                            grande = true;
                        }
                        else
                        {
                            grande = false;
                        }
                    }
                    catch
                    {
                        grande = false;
                    }
                    if (grande)
                    {
                        string aux = "";
                        aux = imgPath.Substring(0, imgPath.IndexOf("_thumb"));
                        aux = aux + imgPath.Substring(imgPath.IndexOf("_thumb") + 6, 4);
                        byte[] imgByte = GetImageByteArr(new Bitmap(aux));
                        Context.Response.ContentType = "image/gif";
                        Context.Response.BinaryWrite(imgByte);
                    }
                    else
                    {
                        byte[]       imgByte      = GetImageByteArr(new Bitmap(imgPath));
                        MemoryStream memoryStream = new MemoryStream();
                        memoryStream.Write(imgByte, 0, imgByte.Length);
                        System.Drawing.Image imagen = System.Drawing.Image.FromStream(memoryStream);
                        Response.ContentType = "image/Jpeg";
                        ImageResize ir = new ImageResize();
                        ir.File   = imagen;
                        ir.Height = imagen.Size.Height;
                        ir.Width  = imagen.Size.Width;
                        ir.GetThumbnail().Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
            }
        }
    }
Esempio n. 22
0
        public ActionResult Detail(int?id, Usuarios model, HttpPostedFileBase userimage, List <int> colrols)
        {
            CustomMemberShipProvider objCustom  = new CustomMemberShipProvider(SessionCustom, HttpContext);
            RolUserRepository        objuserrol = new RolUserRepository(SessionCustom);

            model.UserCustom.LanguageId = 2;

            if (model.UserCustom.Password != null)
            {
                model.UserCustom.Password = Utils.EncriptSHA1(model.UserCustom.Password);
            }

            if (userimage != null && userimage.ContentLength > 0)
            {
                string userImage = Utils.UploadFile(
                    userimage,
                    HttpContext.Server.MapPath("~"),
                    @"resources\imagesuser\",
                    null);

                ImageResize objresize = new ImageResize(HttpContext.Server.MapPath("~"));
                objresize.Width  = 100;
                objresize.Height = 95;
                objresize.Prefix = "_";
                objresize.Resize(@"resources\imagesuser\" + userImage, ImageResize.TypeResize.BackgroundProportional);

                System.IO.File.Delete(System.IO.Path.Combine(HttpContext.Server.MapPath("~"), @"resources\imagesuser\" + userImage));
                model.UserCustom.Image = "_" + userImage;
            }

            if (id != null)
            {
                objuserrol.Entity.UserId = model.UserCustom.UserId = id;
                objCustom.ChangeData(model.UserCustom);
                objuserrol.Delete();
            }
            else
            {
                model.UserCustom.Joindate = DateTime.Now;
                objuserrol.Entity.UserId  = objCustom.CreateUser(model.UserCustom);
            }

            if (colrols != null)
            {
                foreach (int item in colrols)
                {
                    objuserrol.Entity.RolId = item;
                    objuserrol.Insert();
                }
            }

            return(this.RedirectToAction("Index", "Usuarios"));
        }
Esempio n. 23
0
 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);
     }
 }
Esempio n. 24
0
        private void NAVI_TREND_Click(object sender, EventArgs e)
        {
            // 모든 Button의 Image를 Null로 변경 해서 초기화 //
            Navigation_Button_Initialize();

            // 클릭한 버튼에 해당되는 이미지만 On Image로 변경한다 //
            Button button = (Button)sender;

            button.Image = ImageResize.ResizeImage(Properties.Resources.trend_on, button.Width, button.Height);

            panel1.Controls.Clear();
            panel1.Controls.Add(Repository.Instance.p_trend);
        }
Esempio n. 25
0
 private bool DownloadImage(string item, string result)
 {
     try
     {
         this.Log().Info("Downloading image for " + item);
         ImageResize.ResizeImageFixedWidth(result, Path.Combine("images", item + ".jpg"), 512);
         return(true);
     }
     catch (WebException)
     {
         return(false);
     }
 }
        public ActionResult Edit(int id, CategoriesViewModel model)
        {
            var validImageTypes = new string[]
            {
                "image/gif",
                "image/jpeg",
                "image/pjpeg",
                "image/png"
            };

            if ((model.ImageUpload != null || model.ImageUpload.ContentLength > 0) && !validImageTypes.Contains(model.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
            }

            if (ModelState.IsValid)
            {
                var categoryImage = db.Categories.Find(id);
                if (categoryImage == null)
                {
                    return(new HttpNotFoundResult());
                }

                categoryImage.CategoryName        = model.CategoryName;
                categoryImage.CategoryDescription = model.CategoryDescription;

                if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
                {
                    var uploadDir = "/uploads";

                    string finalImageName = "resize-" + model.ImageUpload.FileName.ToString();

                    var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
                    var imageUrl  = Path.Combine(uploadDir, finalImageName);

                    //Resize Image
                    ImageResize.ResizeImage(model.ImageUpload);

                    model.ImageUpload.SaveAs(imagePath);
                    categoryImage.ImageURL = imageUrl;
                }

                db.SaveChanges();

                TempData["UpdateMessage"] = "<div class='alert alert-info w-fade-out'>Category Successfully Updated!</div>";

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string imgPath;
        if (Request.QueryString["ImageId"] != null)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ImageId"].ToString()))
            {
                imgPath = Request.QueryString["ImageId"].ToString();
                if (!string.IsNullOrEmpty(imgPath))
                {

                    bool grande;
                    try
                    {
                        if (Request.QueryString["img"].ToString() != null)
                            grande = true;
                        else
                            grande = false;
                    }
                    catch
                    {
                        grande = false;
                    }
                    if (grande)
                    {
                        string aux = "";
                        aux = imgPath.Substring(0, imgPath.IndexOf("_thumb"));
                        aux = aux + imgPath.Substring(imgPath.IndexOf("_thumb") + 6, 4);
                        byte[] imgByte = GetImageByteArr(new Bitmap(aux));
                        Context.Response.ContentType = "image/gif";
                        Context.Response.BinaryWrite(imgByte);
                    }
                    else
                    {
                        byte[] imgByte = GetImageByteArr(new Bitmap(imgPath));
                        MemoryStream memoryStream = new MemoryStream();
                        memoryStream.Write(imgByte, 0, imgByte.Length);
                        System.Drawing.Image imagen = System.Drawing.Image.FromStream(memoryStream);
                        Response.ContentType = "image/Jpeg";
                        ImageResize ir = new ImageResize();
                        ir.File = imagen;
                        ir.Height = imagen.Size.Height;
                        ir.Width = imagen.Size.Width;
                        ir.GetThumbnail().Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
            }
        }
    }
Esempio n. 28
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;
            }
        }
Esempio n. 29
0
        public async Task <IActionResult> Get(string NewsID, string Size, string ImageName)
        {
            string str    = "";
            bool   isSeek = false;
            var    req    = new ThumbnailRequest();

            //req.RequestedPath = ImageName;
            req.ThumbnailSize   = ParseSize(Size);
            req.SourceImagePath = GetPhysicalPath(NewsID + "/" + ImageName);
            if (IsSourceImageExists(req))
            {
                using (Image img = Image.FromFile(req.SourceImagePath))
                {
                    try
                    {
                        Image file = null;
                        str = "Width: " + req.ThumbnailSize.Value.Width + " Height: " + req.ThumbnailSize.Value.Height;

                        if (req.ThumbnailSize.Value.Height >= req.ThumbnailSize.Value.Width)
                        {
                            file = ImageResize.ScaleByHeight(img, req.ThumbnailSize.Value.Height);
                        }
                        str = "2 Width: " + req.ThumbnailSize.Value.Width + " Height: " + req.ThumbnailSize.Value.Height;

                        if (req.ThumbnailSize.Value.Width > req.ThumbnailSize.Value.Height)
                        {
                            file = ImageResize.ScaleByWidth(img, req.ThumbnailSize.Value.Width);
                        }
                        str = "3 Width: " + req.ThumbnailSize.Value.Width + " Height: " + req.ThumbnailSize.Value.Height;

                        file = ImageResize.ScaleAndCrop(file, req.ThumbnailSize.Value.Width, req.ThumbnailSize.Value.Height, TargetSpot.Center);
                        str  = "4 Width: " + req.ThumbnailSize.Value.Width + " Height: " + req.ThumbnailSize.Value.Height;

                        Stream outputStream = new MemoryStream();

                        file.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        outputStream.Seek(0, SeekOrigin.Begin);
                        str = "5 Width: " + req.ThumbnailSize.Value.Width + " Height: " + req.ThumbnailSize.Value.Height;

                        return(this.File(outputStream, "image/png"));
                    }
                    catch (Exception ex)
                    {
                        return(NotFound(str + " " + ex.Message + " inner " + Convert.ToString(ex.InnerException)));
                    }
                }
            }
            return(NotFound());
        }
Esempio n. 30
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);
        }
Esempio n. 31
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         FileFinder  myProgram = new FileFinder();
         ImageResize IR        = new ImageResize();
         myProgram.GetFile();
         Image QRImage = Image.FromFile(myProgram.ImgPath);
         QRImage           = IR.ResizeImage(QRImage, 128, 128);
         pictureBox1.Image = QRImage;
         ImagePath         = myProgram.ImgPath;
     }
     catch (ArgumentNullException)
     {
     }
 }
Esempio n. 32
0
    /// <summary>
    /// Returns a Image which represents a rezised Image
    /// </summary>
    /// <returns>A Image which represents a rezised Image, using the 
    /// proprerty settings provided</returns>
    public virtual System.Drawing.Image GetThumbnail()
    {
        // Flag whether a new image is required
        bool recalculate = false;
        double new_width = Width;
        double new_height = Height;
        // Load via stream rather than Image.FromFile to release the file
        // handle immediately
        if (m_src_image != null)
            m_src_image.Dispose();
        m_src_image = m_image;
        recalculate = true;
        // If you opted to specify width and height as percentages of the original
        // image's width and height, compute these now
        if (UsePercentages)
        {
            if (Width != 0)
            {
                new_width = (double)m_src_image.Width * Width / 100;

                if (PreserveAspectRatio)
                {
                    new_height = new_width * m_src_image.Height / (double)m_src_image.Width;
                }
            }
            if (Height != 0)
            {
                new_height = (double)m_src_image.Height * Height / 100;

                if (PreserveAspectRatio)
                {
                    new_width = new_height * m_src_image.Width / (double)m_src_image.Height;
                }
            }
        }
        else
        {
            // If you specified an aspect ratio and absolute width or height, then calculate this 
            // now; if you accidentally specified both a width and height, ignore the 
            // PreserveAspectRatio flag
            if (PreserveAspectRatio)
            {
                if (Width != 0 && Height == 0)
                {
                    new_height = (Width / (double)m_src_image.Width) * m_src_image.Height;
                }
                else if (Height != 0 && Width == 0)
                {
                    new_width = (Height / (double)m_src_image.Height) * m_src_image.Width;
                }
            }
        }
        recalculate = true;
        if (recalculate)
        {
            // Calculate the new image
            if (m_dst_image != null)
            {
                m_dst_image.Dispose();
                m_graphics.Dispose();
            }
            Bitmap bitmap = new Bitmap((int)new_width, (int)new_height, m_src_image.PixelFormat);
            m_graphics = Graphics.FromImage(bitmap);
            m_graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            m_graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            m_graphics.DrawImage(m_src_image, 0, 0, bitmap.Width, bitmap.Height);
            m_dst_image = bitmap;
            // Cache the image and its associated settings
            m_cache = this.MemberwiseClone() as ImageResize;
        }

        return m_dst_image;
    }
Esempio n. 33
0
        public override void Sync()
        {
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            // Before we go any further, check to make sure the nfo File isnt malformed.
            try
            {
                XPathDocument docNav = new XPathDocument(this.Directory.ToString());
            }
            catch
            {
                // If its bad looking, meh.
                return;
            }

            DirectoryInfo nfoDirectory = this.Directory.Directory;

            string fullMovieName = this.Directory.Name.Replace(".nfo", "");
            string shortMovieName = fullMovieName.Replace("-", "").Replace(" ", "_").Replace("'", "").Replace("&", "_");
            shortMovieName = shortMovieName.Replace(".", "").Replace("(", "").Replace(")", "").Replace("__", "");
            shortMovieName = shortMovieName.Replace(",", "");

            // Copy the poster JPG if we can.
            if (File.Exists(nfoDirectory + "\\folder.jpg"))
            {

                string newFolderImage = appDataPath + "\\Microsoft\\eHome\\DvdCoverCache\\" + shortMovieName + ".jpg";

                if (File.Exists(newFolderImage))
                {
                    File.Delete(newFolderImage);
                }

                ImageResize imageResize = new ImageResize(nfoDirectory + "\\folder.jpg");
                // imageResize.Resize(newFolderImage, 230, 320, true);
                imageResize.Resize(newFolderImage, 130, 120, true);

            }

            // Delete source XML file if it exists.
            string soureXMLFile = nfoDirectory + "\\" + fullMovieName + ".xml";

            if (File.Exists(soureXMLFile))
            {
                File.Delete(soureXMLFile);
            }

            // Create local source XML file.
            XmlDocument xmlDoc = ConvertNFOToXML(fullMovieName, shortMovieName);
            xmlDoc.Save(soureXMLFile);

            // Delete XML file in DvdInfoCache if it exits.

            string cachedXMLFile = appDataPath + "\\Microsoft\\eHome\\DvdInfoCache\\" + fullMovieName + ".xml";

            if (File.Exists(cachedXMLFile))
            {
                File.Delete(cachedXMLFile);
            }

            // Copy local source XML file to Dvd Info Cache
            File.Copy(soureXMLFile, cachedXMLFile);

            // Delete local .dvdid XML file if it exists.
            string localDvdIDFile = nfoDirectory + "\\" + fullMovieName + ".dvdid.xml";

            if (File.Exists(localDvdIDFile))
            {
                File.Delete(localDvdIDFile);
            }

            // Create local .dvdid XML file if it exists.

            TextWriter dvdIdStream = new StreamWriter(localDvdIDFile);
            dvdIdStream.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            dvdIdStream.WriteLine("<DISC>");
            dvdIdStream.WriteLine("  <NAME>" + fullMovieName + "</NAME>");
            dvdIdStream.WriteLine("  <ID>" + fullMovieName + "</ID>");
            dvdIdStream.WriteLine("</DISC>");
            dvdIdStream.Close();
        }