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);
        }
Example #2
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));
     }
 }
Example #3
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());
        }
    //-----------------------------------------------------------
    protected void btnInsertImage_Click(object sender, EventArgs e)
    {
        try
        {
            m_Images.ImageId       = 0;
            m_Images.ImageFileSize = uploadImageFile.PostedFile.FileName.Length;
            if (m_Images.ImageFileSize > 0)
            {
                DateTime CrDateTime = System.DateTime.Now;
                m_Images.ImageHeight = 100;
                m_Images.ImageWidth  = 100;
                m_Images.ImageDesc   = txtDescription.Text;
                imageAlign           = cboAligns.SelectedValue;
                m_Aligns             = m_Aligns.Get(LogFilePath, LogFileName, imageAlign);
                m_Images.AlignId     = m_Aligns.AlignId;
                imageTypeName        = cboImageTypes.SelectedValue;
                m_ImageTypes         = m_ImageTypes.Get(LogFilePath, LogFileName, imageTypeName);
                m_Images.ImageTypeId = m_ImageTypes.ImageTypeId;
                m_Images.CrUserId    = ActUserId;
                m_Images.CrDateTime  = CrDateTime;
                string date_path        = DateTimeUtils.Static_yyyymm(CrDateTime, "/") + "/";
                string saveLocation     = "";
                string WorkingDirectory = Server.MapPath("~");
                string ext = System.IO.Path.GetExtension(uploadImageFile.PostedFile.FileName);
                imageFileName          = System.IO.Path.GetFileName(uploadImageFile.PostedFile.FileName).Replace(" ", "_");
                m_Images.ImageFileName = imageFileName;
                m_Images.ImagePath     = "";
                m_Images.InsertNoInform(LogFilePath, LogFileName, MyConstants.DISTRIBUTED_PROCESS, IpAddress, ActUserId);
                if (m_Images.ImageId > 0)
                {
                    string original_path = (WorkingDirectory + MyConstants.ORIGINAL_IMAGE_DIR).Replace("\\\\", "\\");
                    FileUtils.MakeYYYY_MM(LogFilePath, LogFileName, ref original_path, CrDateTime);
                    string thumbnail_path = (WorkingDirectory + MyConstants.THUMBNAIL_IMAGE_DIR).Replace("\\\\", "\\");
                    FileUtils.MakeYYYY_MM(LogFilePath, LogFileName, ref thumbnail_path, CrDateTime);
                    string icon_path = (WorkingDirectory + MyConstants.ICON_IMAGE_DIR).Replace("\\\\", "\\");
                    FileUtils.MakeYYYY_MM(LogFilePath, LogFileName, ref icon_path, CrDateTime);
                    switch (m_Images.ImageTypeId)
                    {
                    case SystemConstants.ImageTypes_SetTopImage:
                    {
                        saveLocation = thumbnail_path;
                        break;
                    }

                    case SystemConstants.ImageTypes_OriginalImage:
                    {
                        saveLocation = original_path;
                        break;
                    }

                    case SystemConstants.ImageTypes_Level2Image:
                    {
                        saveLocation = thumbnail_path;
                        break;
                    }
                    }
                    if (FileUtils.Static_IsImage(ext))
                    {
                        imageFileName          = MyConstants.PREFIX_IMAGE + "_" + m_Images.ImageId.ToString() + "_" + imageFileName;
                        m_Images.ImageFileName = imageFileName;
                        uploadImageFile.PostedFile.SaveAs(saveLocation + "\\" + imageFileName);
                        System.Drawing.Image imgPhotoVert = null;
                        try
                        {
                            switch (m_Images.ImageTypeId)
                            {
                            case SystemConstants.ImageTypes_SetTopImage:
                            {
                                imgPhotoVert = System.Drawing.Image.FromFile(thumbnail_path + "\\" + imageFileName);
                                break;
                            }

                            case SystemConstants.ImageTypes_OriginalImage:
                            {
                                imgPhotoVert = System.Drawing.Image.FromFile(original_path + "\\" + imageFileName);
                                break;
                            }

                            case SystemConstants.ImageTypes_Level2Image:
                            {
                                imgPhotoVert = System.Drawing.Image.FromFile(thumbnail_path + "\\" + imageFileName);
                                break;
                            }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogFiles.WriteLog("03: " + ex.Message, LogFilePath + "\\Exception", LogFileName + "." + this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name);
                        }
                        if (imgPhotoVert != null)
                        {
                            height = (short)imgPhotoVert.Height;
                            width  = (short)imgPhotoVert.Width;
                            if (m_Images.ImageTypeId != SystemConstants.ImageTypes_SetTopImage)
                            {
                                System.Drawing.Image imgPhoto = null;
                                height = (short)imgPhotoVert.Height;
                                width  = (short)imgPhotoVert.Width;
                                if (height > width)
                                {
                                    imgPhoto = ImageResize.Thumbnail(imgPhotoVert, MyConstants.H_IMG_WIDTH, MyConstants.H_IMG_HEIGHT);
                                }
                                else
                                {
                                    if (height < width)
                                    {
                                        imgPhoto = ImageResize.Thumbnail(imgPhotoVert, MyConstants.V_IMG_WIDTH, MyConstants.V_IMG_HEIGHT);
                                    }
                                    else
                                    {
                                        imgPhoto = ImageResize.Thumbnail(imgPhotoVert, MyConstants.V_IMG_HEIGHT, MyConstants.V_IMG_HEIGHT);
                                    }
                                }
                                SaveImage(imgPhoto, thumbnail_path + "\\" + imageFileName, ImageFormat.Jpeg);
                                imgPhoto.Dispose();
                                System.Drawing.Image imgPhotoCrop = ImageResize.Crop(imgPhotoVert, MyConstants.ICON_WIDTH, MyConstants.ICON_HEIGHT, ImageResize.AnchorPosition.Center);
                                SaveImage(imgPhotoCrop, icon_path + "\\" + imageFileName, ImageFormat.Jpeg);
                                imgPhotoCrop.Dispose();
                            }
                            m_Images.ImageFileName = imageFileName;
                            m_Images.ImageHeight   = height;
                            m_Images.ImageWidth    = width;
                            m_Images.ImagePath     = saveLocation;
                            m_Images.UpdateNoInform(LogFilePath, LogFileName, MyConstants.DISTRIBUTED_PROCESS, IpAddress, ActUserId);
                        }
                    }
                }
                string home_url     = MyConstants.HOME_URL;
                string scriptReturn = "<script> \n" +
                                      " function myReturnValue(){\n" +
                                      "    var playerId = \"player_" + m_Images.ImageId.ToString() + "\";\n" +
                                      "    var url_home = \"" + home_url + "\";\n" +
                                      "    var imgtype=document.all('cboImageTypes').value;\n" +
                                      "    var imgDesc=document.all('txtDescription').value;\n" +
                                      "    var imgTag=\"\";\n" +
                                      "    var imageFileName= '" + imageFileName + "';\n" +
                                      "    var imageAlign= '" + imageAlign + "';\n" +
                                      "    var playerpath= \"" + home_url + MyConstants.MEDIA_PATH_DIR + "\";\n" +
                                      "    var flvpath= \"" + home_url + MyConstants.FLV_FLASH_FOLDER + date_path + imageFileName + "\";\n" +
                                      "    var imageThumbPath = \"" + MyConstants.THUMBNAIL_IMAGE_PATH + date_path + "\";\n" +
                                      "    var imageOriginalPath=\"" + MyConstants.ORIGINAL_IMAGE_PATH + date_path + "\";\n" +
                                      "    var url_imageThumb = url_home + imageThumbPath + imageFileName;\n" +
                                      "    var url_imageOriginal = url_home + imageOriginalPath + imageFileName;\n" +
                                      "    var h = '" + m_Images.ImageHeight.ToString() + "';\n" +
                                      "    var w = '" + m_Images.ImageWidth.ToString() + "';\n" +
                                      "    var tmpAlt = '';\n" +
                                      "    if(imgtype==\"level2Image\"){\n" +
                                      "      imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "      imgTag += ' <TBODY><TR><TD>';\n" +
                                      "      if ((w >= 200) || (h >= 200)){\n" +
                                      "        imgTag += '<a onclick=\"return viewOriginalImage(this,'+h+','+w+')\" href=\"'+url_imageOriginal+'\">';\n" +
                                      "        if (h > w){\n" +
                                      "            imgTag += '<img '+tmpAlt+' src=\"'+url_imageThumb+'\" height=\"200\" border=\"1\">';\n" +
                                      "        }\n" +
                                      "        else{\n" +
                                      "            imgTag += '<img '+tmpAlt+' src=\"'+url_imageThumb+'\" width=\"200\" border=\"1\">';\n" +
                                      "        }\n" +
                                      "        imgTag += '</a>';\n" +
                                      "      }else{\n" +
                                      "        if (h > w){\n" +
                                      "            imgTag += '<img '+tmpAlt+' src=\"'+url_imageThumb+'\" height=\"150\" border=\"1\">';\n" +
                                      "        }else{\n" +
                                      "            imgTag += '<img '+tmpAlt+' src=\"'+url_imageThumb+'\" width=\"150\" border=\"1\">';\n" +
                                      "        }\n" +
                                      "      }\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "      }\n" +
                                      "   else if(imgtype==\"originalImage\"){\n" +
                                      "            imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "            imgTag += ' <TBODY><TR><TD>';\n" +
                                      "            imgTag += '<img name=\"imagePhoto\" src=\"'+url_imageOriginal+'\" width=\"' + w + '\" border=\"1\">';\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "          }\n" +
                                      "   else if(imgtype==\"topImage\"){ //anh view cung Lead.\n" +
                                      "            imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "            imgTag += ' <TBODY><TR><TD>';\n" +
                                      "            imgTag += '<img name=\"imagePhoto\" src=\"'+url_imageOriginal+'\" width=\"' + w + '\" border=\"1\">';\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "          }\n" +
                                      "   else if(imgtype==\"setTopImage\"){ // Anh noi bat.\n" +
                                      "            imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "            imgTag += ' <TBODY><TR><TD>';\n" +
                                      "            imgTag += '<img name=\"imagePhoto\" src=\"'+url_imageThumb+'\" width=\"100\" height =\"100\"  border=\"1\">';\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "          }\n" +
                                      "   else if(imgtype==\"LargeImageForLead\"){\n" +
                                      "            imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "            imgTag += ' <TBODY><TR><TD>';\n" +
                                      "            imgTag += '<img name=\"imagePhoto\" src=\"'+url_imageOriginal+'\" width=\"' + w + '\" border=\"1\">';\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "          }\n" +
                                      "  else if(imgtype==\"Clip-FLV\"){\n" +
                                      "            imgTag = '<DIV align=\"'+imageAlign+'\"><TABLE cellspacing=\"0\" cellpadding=\"3\" width=\"1\" align=\"'+imageAlign+'\" border=\"0\">';\n" +
                                      "            imgTag += ' <TBODY><TR><TD>';\n" +
                                      "            imgTag +='<embed flashvars=\"file='+flvpath+'&amp;width=400&amp;height=300&amp;autostart=false&amp;volume=100&amp;repeat=false&amp;bufferlength=10\"';\n" +
                                      "            imgTag +='allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"transparent\" quality=\"hight\"';\n" +
                                      "            imgTag +='name=\"flvplayer\" id=\"flvplayer\" src=\"'+playerpath+'flvplayer.swf\"';\n" +
                                      "            imgTag +='type=\"application/x-shockwave-flash\" width=\"400\" height=\"300\">';\n" +
                                      "            imgTag += ' </TD></TR><TR><TD class=\"Image\" align=\"left\">';\n" +
                                      "            imgTag += '<font style=\"font-size:12px; font-family:arial\"><i>' + imgDesc + '</i></font>';\n" +
                                      "            imgTag += '</TD></TR></TBODY></TABLE></DIV>';\n" +
                                      "          }\n" +
                                      "      oEditor.FCK.InsertHtml(imgTag);\n" +
                                      "      window.parent.Cancel();\n" +
                                      "    }\n" +
                                      " myReturnValue();" +
                                      "</script>";
                imageUploaded = true;
                Page.ClientScript.RegisterStartupScript(this.GetType(), "VoteReturn", scriptReturn);
            }
        }
        catch (Exception ex)
        {
            LogFiles.WriteLog("04: " + ex.Message, LogFilePath + "\\Exception", LogFileName + "." + this.GetType().Name + "." + MethodBase.GetCurrentMethod().Name);
        }
    }
Example #5
0
        public async Task <ActionResult> SetAvatarByAccountId([FromRoute] long accountId,
                                                              [FromBody] SetAvatarInputModel input, CancellationToken cancellationToken)
        {
            if (AccountId != accountId)
            {
                return(Forbidden());
            }

            var account = await _accountManager.GetAsync(accountId, cancellationToken);

            var           selectedAvatarItemIds = input.AvatarItemIds;
            List <Avatar> avatars = new List <Avatar>();

            if (selectedAvatarItemIds.Any())
            {
                var accountItems = await _accountItemManager.GetByAccountIdAsync(account.Id, cancellationToken);

                var imagesToCombine = new List <Stream>();

                foreach (var selectedAvatarItemId in selectedAvatarItemIds)
                {
                    var shopItem = await _shopItemManager.GetAsync(selectedAvatarItemId.Id, cancellationToken);

                    if (shopItem != null)
                    {
                        avatars.Add(selectedAvatarItemId);

                        imagesToCombine.Add(_fileService.GetFile(shopItem.ImageFileId));

                        if (!accountItems.Any(q => q.ShopItemId == selectedAvatarItemId.Id))
                        {
                            if (shopItem.DefaultAvatar == true)
                            {
                                // add item to user's items
                                var newAccountItem = new AccountItem
                                {
                                    AccountId  = account.Id,
                                    ShopItemId = selectedAvatarItemId.Id,
                                    ItemTypeId = shopItem.TypeId,
                                    Quantity   = 1
                                };
                                await _accountItemManager.SaveAsync(newAccountItem, cancellationToken);
                            }
                            else
                            {
                                return(BadRequest("invalid_itemId", "AvatarItem not in AccountItems"));
                            }
                        }
                    }
                }

                using (var avatarImg = _imageProcessingService.Combine(imagesToCombine))
                {
                    var fileId = await _fileService.SaveFileAsync(avatarImg, cancellationToken);

                    var file = await _fileManager.SaveAsync(new UploadedFile
                    {
                        FileId             = fileId,
                        CreatorAccountId   = AccountId,
                        Extension          = "png",
                        MimeType           = "image/png",
                        MimeTypeCategoryId = UploadedFileMimeTypeCategoryIds.Image,
                        Name   = "avatar",
                        Size   = avatarImg.Length,
                        TypeId = UploadedFileTypeIds.AccountAvatarImage
                    }, cancellationToken);

                    var uploadedImage = Image.FromStream(avatarImg);

                    var img = ImageResize.Crop(uploadedImage, 300, 250, TargetSpot.TopMiddle);

                    var filePath = Path.Combine(_options.BaseStoragePath, $"{fileId}-h.png");

                    img.SaveAs($"{filePath}");

                    account.AvatarImageId = file.FileId;
                }
            }

            account.AvatarItemIds = JsonConvert.SerializeObject(selectedAvatarItemIds);
            await _accountManager.SaveAsync(account, cancellationToken);

            return(Ok());
        }
Example #6
0
        private async Task SetDefaultAvatar(Account account, CancellationToken cancellationToken)
        {
            var avatarTypeId       = account.GenderId == GenderIds.Male ? AvatarTypeIds.Male : AvatarTypeIds.Female;
            var defaultAvatarItems = await _dataContext.ShopItems.Where(q =>
                                                                        q.IsArchived == false &&
                                                                        q.TypeId == ShopItemTypeIds.AvatarItem &&
                                                                        q.DefaultAvatar == true &&
                                                                        q.AvatarTypeId == avatarTypeId)
                                     .GroupBy(q => q.AvatarCategoryId).Select(q => q.First())
                                     .OrderBy(q => q.AvatarCategoryId)
                                     .ToListAsync(cancellationToken);

            if (defaultAvatarItems.Any())
            {
                var imagesToCombine = new List <Stream>();
                foreach (var item in defaultAvatarItems)
                {
                    imagesToCombine.Add(_fileService.GetFile(item.ImageFileId));
                    _dataContext.AccountItems.Add(new AccountItem
                    {
                        AccountId  = account.Id,
                        ShopItemId = item.Id,
                        ItemTypeId = item.TypeId,
                        Quantity   = 1,
                    });
                }

                using (var avatarImg = _imageProcessingService.Combine(imagesToCombine))
                {
                    var fileId = await _fileService.SaveFileAsync(avatarImg, cancellationToken);

                    var file = await _fileManager.SaveAsync(new UploadedFile
                    {
                        FileId             = fileId,
                        CreatorAccountId   = AccountId,
                        Extension          = "png",
                        MimeType           = "image/png",
                        MimeTypeCategoryId = UploadedFileMimeTypeCategoryIds.Image,
                        Name   = "avatar",
                        Size   = avatarImg.Length,
                        TypeId = UploadedFileTypeIds.AccountAvatarImage
                    }, cancellationToken);

                    account.AvatarImageId = file.FileId;
                    var uploadedImage = Image.FromStream(avatarImg);

                    var img = ImageResize.Crop(uploadedImage, 300, 250, TargetSpot.TopMiddle);

                    var filePath = Path.Combine(_options.BaseStoragePath, $"{fileId}-h.png");

                    img.SaveAs($"{filePath}");
                }

                List <Avatar> avatars = new List <Avatar>();
                foreach (var item in defaultAvatarItems)
                {
                    avatars.Add(new Avatar {
                        Id = item.Id, AvatarCategoryId = item.AvatarCategoryId.Value
                    });
                }


                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 500
                });
                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 800
                });
                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 900
                });
                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 1200
                });
                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 1300
                });
                avatars.Add(new Avatar {
                    Id = 0, AvatarCategoryId = 1400
                });


                account.AvatarItemIds = JsonConvert.SerializeObject(avatars);
                await _accountManager.SaveAsync(account, cancellationToken);
            }
        }