改变图片像素和大小
예제 #1
0
 /// <summary>
 /// 调用扫描的函数
 /// </summary>
 /// <param name="start">开始时间</param>
 /// <param name="stop">结束时间</param>
 public static void callScan(DateTime start, DateTime stop)
 {
     //取出所有的用户信息
     getAllUserInfo();
     try
     {
         //从设备download时段内的图片,保存到本地根目录下
         //以"starttime_stoptime"命名的文件夹下
         String savepath = String.Format("{0}\\{1}_{2}\\",
                                         ImgRootPath_Scan, start.ToString("yyyyMMdd-HHmmss"), stop.ToString("yyyyMMdd-HHmmss"));
         //初始化下载类并开始下载,自动释放资源
         ImgHelper imgHelper = new ImgHelper(IP, Port, Account, PassWord, savepath);
         imgHelper.SearchAndDown(start, stop);
         //开始逐个判断:先判断性别,识别用户状态,再与本地特征值逐个进行比较,
         //明确用户身份,最后结果保存到dictonary中。
         new Task(() => { doScan(savepath); }).Start();
         Console.WriteLine("Start scan {0} to {1} ......",
                           start.ToString(), stop.ToString());
     }
     catch (Exception ex)
     {
         Console.WriteLine("Call scan error! {0}", ex.Message);
         return;
     }
 }
예제 #2
0
        public override void Page_Load(ref NVelocity.VelocityContext context)
        {
            base.Page_Load(ref context);

            #region  加载头部及Title
            NewXzc.Web.templatecs.Head head = new Head();
            head.Init_Head(context, 0);

            context.Put("title", "基础资料_个人中心");
            context.Put("keywords", "红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜");
            context.Put("description", "衣品搭配,专注发掘不一样的红人神咖.衣品搭配是红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜等综合红人报道平台.衣品搭配网络红人聚集平台,跟踪报道红人资讯,最新红人作品等等,第一时间满足粉丝需求.");
            #endregion

            #region  企业基础资料
            Model.RED_USER user_model = new BLL.RED_USER().GetModel(UserID_HongRenHui);
            if (user_model != null)
            {
                string user_head = user_model.USER_HEAD;
                context.Put("comlogo", user_head);
                context.Put("comlogo_small", ImgHelper.Return_User_Head(user_head, 3));
                context.Put("comlogo_middle", ImgHelper.Return_User_Head(user_head, 2));
                context.Put("comlogo_big", ImgHelper.Return_User_Head(user_head, 1));
                context.Put("nickname", user_model.USERNAME);
            }
            else
            {
                context.Put("redirecturl", "/404");
            }
            #endregion
        }
        public ActionResult EditArticle(Article article)
        {
            var imgstr = Request.Form["imgstr"] as string;
            var index  = imgstr.IndexOf(";base64,") + 8;

            imgstr = imgstr.Substring(index, imgstr.Length - index);

            var img      = ImgHelper.Base64StringToImage(imgstr);
            var rootPath = AppDomain.CurrentDomain.BaseDirectory;

            var imgPath = "/Upload/Image/" + Guid.NewGuid() + ".jpg";

            //var articleList = db.ArticleSort.OrderBy(q => q.SortArticleName).ToList();
            //ViewData["HourList"] = new SelectList(articleList, "SortArticleId", "SortArticleName");
            //一些文章内部属性
            var sort = db.ArticleSort.Where(w => w.SortArticleId == article.SortArticleId).FirstOrDefault();

            article.SortArticleName = sort.SortArticleName;
            article.ArticleTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            article.UserId          = User.Identity.GetUserName();
            article.ArticleCover    = imgPath;
            article.ArticleClick    = 0;
            db.Article.Add(article);

            if (db.SaveChanges() > 0)
            {
                if (img != null)
                {
                    img.Save(rootPath + imgPath);
                }
                return(RedirectToAction("Index", "Manage"));
            }

            return(View());
        }
예제 #4
0
        public static EQRInfo UpdateMasterUrlById(EQRInfo qr)
        {
            string fp = HttpContext.Current.Server.MapPath(qr.OrigFilePath);

            System.Drawing.Image qrImg = new Bitmap(HttpContext.Current.Server.MapPath(fp));

            Bitmap bkImg = ImgHelper.CreateBlankImg(qrImg.Width, qrImg.Height + 80, Brushes.White);

            using (Graphics g = Graphics.FromImage(bkImg))
            {
                string     s    = "此邀请码不收费!";
                Font       font = new Font("黑体", 12, FontStyle.Bold);
                SolidBrush b    = new SolidBrush(Color.FromArgb(50, 159, 250));

                g.DrawString(s, font, b, new PointF(20, qrImg.Height + 10));

                s = "平台入驻不收费,请谨防骗子!";
                g.DrawString(s, font, b, new PointF(20, qrImg.Height + 200));
            }
            Bitmap finImg   = ImgHelper.CombineImage(bkImg, qrImg, 80);
            string filePath = "/Content/QR/Invite/QRInvite_" + qr.ID + ".jpg";

            qr.FilePath = filePath;

            string fullPath = HttpContext.Current.Server.MapPath(filePath);

            finImg.Save(fullPath);

            finImg.Dispose();
            bkImg.Dispose();

            return(qr);
        }
예제 #5
0
        protected void Save_Btn_Click(object sender, EventArgs e)
        {
            if (Mid > 0)
            {
                desMod = desBll.SelReturnModel(Mid);
            }
            else
            {
                desMod = new M_Logo_Design();
            }
            desMod.Alias       = Alias_T.Text;
            desMod.LogoContent = StrHelper.CompressString(Save_Hid.Value);
            ImgHelper imghelp = new ImgHelper();

            System.Drawing.Bitmap bmp = imghelp.Base64ToImg(Base64_Hid.Value);
            //用于减小尺寸
            desMod.PreviewImg = "data:image/png;base64," + imghelp.ImgToBase64ByImage(bmp);

            if (desMod.ID > 0)
            {
                desMod.ZType = 1; desBll.UpdateByID(desMod);
            }
            else
            {
                M_AdminInfo adminMod = B_Admin.GetLogin();
                desMod.ZType   = 1;
                desMod.ZStatus = 99;
                desMod.AdminID = adminMod.AdminId;
                desMod.ID      = desBll.Insert(desMod);
            }
            SnsHelper.UpdateModel(desMod.ID
                                  , new string[] { "BackGround" }
                                  , new string[] { BKUrl_T.Text.Trim() });
            function.WriteSuccessMsg("操作成功", "DesTlpList.aspx");
        }
예제 #6
0
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            int sizes = 0;

            if (!FupFile.HasFile)
            {
                ReturnManage("请指定一个上传文件");
                return;
            }
            //if (!SafeSC.IsImage(FupFile.FileName)) { function.WriteErrMsg("只能上传图片文件"); }
            string ext = Path.GetExtension(FupFile.FileName).ToLower();

            m_MaxFileSize = DataConverter.CLng(SiteConfig.SiteOption.UploadPicMaxSize);
            if (((int)FupFile.FileContent.Length) > (m_MaxFileSize * 0x400))
            {
                ReturnManage("上传的文件超过限制的" + m_MaxFileSize + "KB大小");
                return;
            }
            string ranFName   = DataSecurity.MakeFileRndName() + ext;//文件名
            string foldername = base.Request.PhysicalApplicationPath.TrimEnd('\\') + (VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.UploadDir) + FileSavePath()).Replace("/", "\\");
            string fileName   = FileSystemObject.CreateFileFolder(foldername, HttpContext.Current);
            string savePath   = SafeSC.SaveFile(function.PToV(fileName), FupFile, ranFName);

            if (WaterModuleConfig.WaterConfig.IsUsed && SafeSC.IsImage(FupFile.FileName) && RadioButtonList1.SelectedValue == "1")
            {
                savePath = ImgHelper.AddWater(savePath);
            }
            sizes = (int)FupFile.FileContent.Length;
            GetScriptByModuleName(savePath.Replace(SiteConfig.SiteOption.UploadDir, ""), sizes);
            ReturnManage("文件上传成功");
        }
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="FilePath"></param>
        /// <param name="Logo">如何没有Logo填写null</param>
        /// <returns></returns>
        public static Bitmap CreateQR(string Url, string FilePath, Image Logo, string Text = "")
        {
            IQBLog log = new IQBLog();
            Bitmap bt  = null;

            try
            {
                string        enCodeString  = Url;
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                qrCodeEncoder.QRCodeScale        = 4;
                qrCodeEncoder.QRCodeVersion      = 9;
                bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
                //    log.log("CreateQR qrCodeEncoder");
                Bitmap blankBK = null;
                if (!string.IsNullOrEmpty(Text))
                {
                    blankBK = ImgHelper.CreateBlankImg(bt.Width + 20, bt.Height + 60, Brushes.White);
                    bt      = ImgHelper.CombineImage(blankBK, bt, 40);
                    using (Graphics g = Graphics.FromImage(blankBK))
                    {
                        string     s    = Text;
                        Font       font = new Font("宋体", 16);
                        SolidBrush b    = new SolidBrush(Color.Black);
                        g.DrawString(s, font, b, new PointF(45, bt.Height - 45));
                    }
                }
                else
                {
                    blankBK = ImgHelper.CreateBlankImg(bt.Width + 20, bt.Height + 20, Brushes.White);
                    bt      = ImgHelper.CombineImage(blankBK, bt);
                }

                if (Logo != null)
                {
                    Logo = ImgHelper.resizeImage(Logo, new Size(60, 60));
                    if (!string.IsNullOrEmpty(Text))
                    {
                        bt = ImgHelper.CombineImage(bt, Logo, 40);
                    }
                    else
                    {
                        bt = ImgHelper.CombineImage(bt, Logo);
                    }
                }

                //   log.log("CreateQR Combine Log");
                bt.Save(FilePath);
            }
            catch (Exception ex)
            {
                log.log("CreateQR Error:" + ex.Message);
                log.log("CreateQR Error:" + ex.InnerException.Message);
                throw ex;
            }


            return(bt);
        }
예제 #8
0
        public JsonResult AddPdfBypic(string CoANo, string path, string CASNo)
        {
            string serverFilepath = Server.MapPath(string.Format("/Storage/PDF/{0}/ ", base.CurrentUser.Id));

            if (!System.IO.Directory.Exists(serverFilepath))
            {
                System.IO.Directory.CreateDirectory(serverFilepath);
            }
            string serverFileName = "CoAReports" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
            string pdfpath        = serverFilepath + serverFileName;

            string[] list = path.Split(';');
            Result   res  = new Result();

            res.success = ExportDataIntoPDF(pdfpath, list.ToList <string>());
            if (res.success)
            {
                string  str = ImgHelper.PostImg(pdfpath, "coapic");
                COAList cr  = new COAList()
                {
                    Addtime     = DateTime.Now,
                    CoANo       = CoANo,
                    URL         = str,
                    UserId      = base.CurrentUser.Id,
                    AddUserType = 2,
                    CASNo       = CASNo
                };
                ServiceHelper.Create <ICOAListService>().AddCoAReportInfo(cr);
            }

            return(Json(res));
        }
        public ActionResult UploadImg(string fileName, string data)
        {
            //byte[] bytes = ImgHelper.GetBase64String(data).ToBytes_FromBase64Str();
            var url = ImgHelper.GetImgUrl(data);
            //string fileDir = System.Web.HttpContext.Current.Server.MapPath("~/Upload/File");
            //if (!Directory.Exists(fileDir))
            //    Directory.CreateDirectory(fileDir);
            //string filePath = Path.Combine(fileDir, fileName);
            //using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            //{
            //    using (MemoryStream m = new MemoryStream(bytes))
            //    {
            //        m.WriteTo(fileStream);
            //    }
            //}


            var res = new
            {
                success = true,
                src     = url
            };

            return(JsonContent(res.ToJson()));
        }
예제 #10
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="serverId"></param>
        /// <returns></returns>
        public ActionResult UploadImge(string serverId, string companyid)//原图
        {
            log.AppenLog("上传图片");
            companyid = Base64MIMA.JIE(companyid);
            //return Content("222");
            //
            //WriteLog("serverId" + serverId);
            List <string> rsFilePathList = new List <string>();

            try
            {
                string imageFilePath = "";
                string imgServerIds  = serverId; // 微信服务器图片Id
                //WriteLog("imgServerIds微信服务器图片Id" + imgServerIds);
                List <string> imgServerIdList = imgServerIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                //WriteLog("imgServerIdList集合:" + imgServerIdList);
                // WriteLog("imgServerIdList.Count():图片长度" + imgServerIdList.Count());
                foreach (string imgServerId in imgServerIdList)
                {
                    //WriteLog("imgServerId:" + imgServerId);
                    // 1)获取图片
                    ImgHelper imgH = new ImgHelper();
                    Image     img  = imgH.GetImage(imgServerId, companyid);
                    // 2)存放本地
                    imageFilePath = imgH.SaveWeChatAttFileOfImage(img, "Sunpn");
                    rsFilePathList.Add(imageFilePath);
                }
                return(Content(imageFilePath));
            }
            catch (Exception ex)
            {
                log.AppenLog(ex.Message);
                return(Content(ex.Message));
            }
        }
예제 #11
0
        /// <summary>
        /// 专业版接口获取拼团列表
        /// </summary>
        /// <param name="rid"></param>
        /// <param name="name"></param>
        /// <param name="state"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        public List <EntGroupsRelation> GetListEntGroups_api(string ids, int rid, int storeid = 0)
        {
            List <MySqlParameter> parameters = new List <MySqlParameter>();

            List <EntGroupsRelation> list = new List <EntGroupsRelation>();
            string strSql = $@"select eg.`name`,eg.id as goodid,eg.img,eg.price,eg.stock,eg.salesCount,eg.virtualSalesCount,egr.* from entgoods eg left join entgroupsrelation egr on eg.id = egr.entgoodsid where find_in_set(eg.id,@ids) and egr.rid={rid} and egr.state=1 and egr.storeid={storeid} order by find_in_set(eg.id,@ids)";

            parameters.Add(new MySqlParameter("@ids", ids));

            using (MySqlDataReader dr = SqlMySql.ExecuteDataReader(connName, CommandType.Text, strSql, parameters.ToArray()))
            {
                while (dr.Read())
                {
                    EntGroupsRelation model = GetModel(dr);
                    if (model != null)
                    {
                        model.Name = dr["name"].ToString();
                        if (DBNull.Value != dr["price"])
                        {
                            model.SinglePrice = float.Parse(dr["price"].ToString());
                        }
                        if (DBNull.Value != dr["stock"])
                        {
                            model.CreateNum = int.Parse(dr["stock"].ToString());
                        }

                        if (!string.IsNullOrEmpty(dr["img"].ToString()))
                        {
                            model.ImgUrl = ImgHelper.ResizeImg(dr["img"].ToString(), 750, 750);
                        }

                        int           totalcount = 0;
                        List <object> userlist   = EntGroupSponsorBLL.SingleModel.GetGoupsUserImgs(model.Id, ref totalcount, (int)TmpType.小程序专业模板, model.EntGoodsId);

                        //判断是否已结束
                        if (totalcount >= model.CreateNum)
                        {
                            model.State = 2;
                        }
                        else if ((model.ValidDateStart < DateTime.Now))
                        {
                            //判断是否开始
                            model.State = 1;
                        }
                        else
                        {
                            model.State = -1;
                        }

                        //已团数量
                        model.GroupsNum         = totalcount;
                        model.salesCount        = Convert.ToInt32(dr["salesCount"]);
                        model.virtualSalesCount = Convert.ToInt32(dr["virtualSalesCount"]);

                        list.Add(model);
                    }
                }
            }
            return(list);
        }
예제 #12
0
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            if (FType == 1 || FType == 4)
            {
                this.m_FileExtArr = "gif|jpg|png|swf";
            }
            else
            {
                this.m_FileExtArr = "gif|jpg|png|docx|rar|doc";
            }
            string str2 = Path.GetExtension(File_UP.FileName).ToLower();

            if (!this.CheckFilePostfix(str2.Replace(".", "")))
            {
                this.ReturnManage("上传的文件不是符合扩展名" + this.m_FileExtArr + "的文件");
            }
            else
            {
                string fname    = DateTime.Now.ToString("yyyyMMddHHmmss") + function.GetRandomString(4) + Path.GetExtension(File_UP.FileName);
                string savePath = "";
                if (SafeSC.IsImage(File_UP.FileName))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(File_UP.PostedFile.InputStream);
                    img      = ImgHelper.AddWater(img);
                    savePath = ImgHelper.SaveImage(FileSavePath() + fname, img);
                }
                else
                {
                    savePath = SafeSC.SaveFile(savePath, File_UP, fname);
                }
                this.GetScriptByModuleName(savePath);
                this.ReturnManage("文件上传成功");
            }
        }
예제 #13
0
        /// <summary>
        /// 导入收藏夹
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public ContentResult ImportBookmarks(string files)
        {
            IList <UploadedItem> uploads = UploadedManager.Parse(files);

            return(TryAction(r =>
            {
                int count = 0;
                int successCount = 0;
                int errorCount = 0;
                foreach (UploadedItem item in uploads)
                {
                    string path = Server.MapPath(UrlIconPath);
                    var fullFile = Server.MapPath(item.FilePath);
                    string fileContent = FileHelper.GetFileContent(fullFile, Encoding.GetEncoding("utf-8"));
                    List <string> listItems = DataMiningHelper.GetItemsByTab(fileContent, "<A", "</A>");
                    count += listItems.Count;
                    foreach (string listItem in listItems)
                    {
                        try
                        {
                            IDictionary <string, string> attrs = TagHelper.ParseAttributes(listItem);
                            string url = attrs["HREF"];
                            if (urlsRepository.FindAll().Where(o => o.Url == url).Count() <= 0)
                            {
                                //不存在则新增
                                string encoding = "utf-8";
                                // string html = DataMining.GetHtmlAutoEncode(url, out encoding);
                                Uri uri = new Uri(url);
                                if (attrs.ContainsKey("ICON") && !string.IsNullOrEmpty(attrs["ICON"]))
                                {
                                    string base64 = attrs["ICON"].Replace("data:image/png;base64,", "");
                                    ImgHelper.SaveBase64(base64, Path.Combine(path, uri.Host + ".png"));
                                }
                                else if (attrs.ContainsKey("ICON_URI") && !string.IsNullOrEmpty(attrs["ICON_URI"]))
                                {
                                    DownloadUrlIcon(attrs["ICON_URI"], uri.Host);
                                }
                                UrlsEntity entity = new UrlsEntity()
                                {
                                    Url = url,
                                    CreateTime = DateTime.Now,
                                    Encoding = encoding,
                                    IconName = uri.Host,
                                    IconUrl = string.Format("http://{0}/favicon.ico", uri.Host),
                                    Title = attrs["InnerText"],
                                    Remark = attrs["ADD_DATE"]
                                };
                                urlsRepository.Add(entity);
                            }
                            successCount++;
                        }
                        catch (Exception ex)
                        {
                            errorCount++;
                        }
                    }
                }
                r.Msg = string.Format("导出完毕,总共【{0}】项,成功【{1}】,失败【{2}】", count, successCount, errorCount);
            }));
        }
예제 #14
0
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            int sizes = 0;

            if (!File_UP.HasFile)
            {
                ReturnManage("请指定一个上传文件");
                return;
            }
            //if (!SafeSC.IsImage(FupFile.FileName)) { function.WriteErrMsg("只能上传图片文件"); }
            string fname    = DateTime.Now.ToString("yyyyMMddHHmmss") + function.GetRandomString(4) + Path.GetExtension(File_UP.FileName);
            string savePath = "";

            if (SafeSC.IsImage(File_UP.FileName))
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(File_UP.PostedFile.InputStream);
                if (Request.Form["water_rad"].Equals("1"))
                {
                    img = ImgHelper.AddWater(img);
                }
                if (SiteConfig.ThumbsConfig.ThumbsWidth > 0 || SiteConfig.ThumbsConfig.ThumbsHeight > 0)
                {
                    img = imgHelp.ZoomImg(img, SiteConfig.ThumbsConfig.ThumbsHeight, SiteConfig.ThumbsConfig.ThumbsWidth);
                }
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img);
                savePath = imgHelp.SaveImg(FileSavePath() + fname, bmp);
            }
            else
            {
                RepStr("仅允许上传图片文件");
            }
            sizes = (int)File_UP.FileContent.Length;
            GetScriptByModuleName(savePath.Replace(SiteConfig.SiteOption.UploadDir, ""), sizes);
            ReturnManage("文件上传成功");
        }
예제 #15
0
        //心理美文
        public string loadmeiwenNews()
        {
            List <T_Article> list = bll.GetListByContent(4, 5);
            StringBuilder    sb   = new StringBuilder();

            foreach (T_Article model in list)
            {
                //获得文章内容的简介
                T_Article first = new T_Article();
                first = bll.GetArticleById(model.ArticleId);
                string ab = Regex.Replace(first.ArticleContent, @"<.*?>", "");
                //如果文字没有超过100个字
                if (ab.Length > 70)
                {
                    ab = ab.Substring(0, 70);
                }
                ab = ab + "...";
                //girdview,前端代码
                //获得图片的地址
                string imgurl = ImgHelper.getImgUrl(first.ArticleContent, @"<img[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>", "src")[0].ToString();

                sb.AppendFormat("<a href='articleDetail.aspx?articleId={1}' class='grid-block'><figure class='grid-item'><img src='{3}'/><figcaption><h3>{2}</h3></figcaption></figure></a>", model.ArticleContent, model.ArticleId, model.ArticleTitle, imgurl);
            }
            return(sb.ToString());
        }
예제 #16
0
        //心协动态
        public string loadXinxieNews()
        {
            List <T_Article> list = bll.GetListByContent(4, 3);
            StringBuilder    sb   = new StringBuilder();

            foreach (T_Article model in list)
            {
                //获得文章内容的简介
                T_Article first = new T_Article();
                first = bll.GetArticleById(model.ArticleId);
                string ab = Regex.Replace(first.ArticleContent, @"<.*?>", "");
                //如果文字没有超过100个字
                if (ab.Length > 70)
                {
                    ab = ab.Substring(0, 70);
                }
                ab = ab + "...";

                //girdview,前端代码


                //获得图片的地址
                string imgurl = ImgHelper.getImgUrl(first.ArticleContent, @"<img[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>", "src")[0].ToString();


                sb.AppendFormat("<div class='newsbottom'><a href='articleDetail.aspx?articleId={2}' class='imglink'><img src='{4}'></a><a href='articleDetail.aspx?articleId={2}'><p class='newtitle'>{1}</p></a><p class='newtext'>{3}</p></div>", first.ArticleContent, first.ArticleTitle, first.ArticleId, ab, imgurl);
            }

            return(sb.ToString());
        }
        public ActionResult EditBackImage(BackImage b)
        {   //上传图片处理
            var imgstr = Request.Form["imgstr"] as string;
            var index  = imgstr.IndexOf(";base64,") + 8;

            imgstr = imgstr.Substring(index, imgstr.Length - index);

            var img      = ImgHelper.Base64StringToImage(imgstr);
            var rootPath = AppDomain.CurrentDomain.BaseDirectory;

            var imgPath = "/Upload/BackImage/" + Guid.NewGuid() + ".jpg";

            b.BackTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            b.UserId   = User.Identity.GetUserName();
            b.BackImg  = imgPath;

            db.Back.Add(b);
            if (db.SaveChanges() > 0)
            {
                if (img != null)
                {
                    img.Save(rootPath + imgPath);
                }
                return(RedirectToAction("Index", "Manage"));
            }
            return(View());
        }
예제 #18
0
        /// <summary>
        /// 处理图片到文件夹
        /// </summary>
        public void AutoHandle()
        {
            Bitmap bitmap = ImgHelper.GetBitmapForGra(this.FullName);
            //保持图片的比例不变,缩放图片
            int width  = this.Width,
                height = this.Width;

            if (bitmap.Width > bitmap.Height)
            {
                //宽度为大,计算高度
                height = Convert.ToInt32(width * (bitmap.Height * 1.0 / bitmap.Width));
            }
            else
            {
                //高度为大,计算宽度
                width = Convert.ToInt32(height * (bitmap.Width * 1.0 / bitmap.Height));
            }

            Bitmap result = ImgHelper.ResizeImage(bitmap, width, height);

            string bigpath = GetFullName();

            bigpath = bigpath.Substring(0, bigpath.LastIndexOf(".")) + ".jpg";
            //保存图片,指定保存 格式为Jpeg,占用空间会比较小
            result.Save(bigpath, System.Drawing.Imaging.ImageFormat.Jpeg);
            result.Dispose();
            bitmap.Dispose();
        }
예제 #19
0
        protected void Save_Btn_Click(object sender, EventArgs e)
        {
            //B_User.CheckIsLogged(Request.RawUrl);
            mu = SnsHelper.GetLogin();
            //if (Mid > 0)
            //{
            //    desMod = desBll.SelReturnModel(Mid);
            //}
            //else { desMod = new M_Logo_Design(); }
            desMod             = new M_Logo_Design();
            desMod.LogoContent = StrHelper.CompressString(Save_Hid.Value);
            ImgHelper imghelp = new ImgHelper();

            System.Drawing.Bitmap bmp = imghelp.Base64ToImg(Base64_Hid.Value);
            //用于减小尺寸
            desMod.PreviewImg = "data:image/png;base64," + imghelp.ImgToBase64ByImage(bmp);

            //if (desMod.ID > 0) { desBll.UpdateByID(desMod); }
            //else
            //{
            desMod.ZType    = 0;
            desMod.ZStatus  = 99;
            desMod.UserID   = mu.UserID;
            desMod.UserName = mu.UserName;
            desMod.ID       = desBll.Insert(desMod);
            //}
            //CreateOrder(desMod);
            CreateCart(desMod);
        }
예제 #20
0
 public bool SetUserInfo(WXUserInfoRequest req)
 {
     try
     {
         var dto = new UserInfo()
         {
             OpenId     = req.openId,
             NickName   = req.nickName,
             Gender     = (GenderEnum)req.gender,
             City       = req.city,
             Province   = req.province,
             Country    = req.country,
             Language   = req.language,
             CreateTime = DateTime.Now,
             UpdateTime = DateTime.Now,
         };
         string headshotPath = Guid.NewGuid().ToString();
         string path         = ConfigurationHelper.AppSettings["HeadPhoto"] + headshotPath + ConfigurationHelper.AppSettings["HeadshotFormat"];
         bool   save         = ImgHelper.Saveimages(req.avatarUrl, path);
         if (save)
         {
             dto.HeadshotPath = headshotPath;
         }
         return(_userInfoRepository.SetUserInfo(dto));
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
예제 #21
0
        /// <summary>
        /// 根据url 请求获取图片
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPostSaveImg(string Url, string postDataStr, ref string errorMessage)
        {
            string aliTempImgKey = string.Empty;

            try
            {
                HttpWebRequest  request = (HttpWebRequest)WebRequest.Create(Url);
                CookieContainer cookie  = new CookieContainer();
                request.Method          = "POST";
                request.ContentType     = "application/x-www-form-urlencoded";
                request.ContentLength   = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookie;
                using (Stream myRequestStream = request.GetRequestStream())
                {
                    using (StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")))
                    {
                        myStreamWriter.Write(postDataStr);
                    }
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        response.Cookies = cookie.GetCookies(response.ResponseUri);
                        Stream myResponseStream = response.GetResponseStream();

                        //  myResponseStream.Position = 0;//保证流可读
                        byte[] byteData = Utility.IO.StreamHelpers.ReadFully(myResponseStream);
                        myRequestStream.Close();
                        #region 判断是否返回错误
                        string result = Encoding.Default.GetString(byteData);

                        if (result.Contains("errcode"))
                        {
                            errorMessage = result;
                            return(string.Empty);
                        }
                        #endregion

                        string ext = string.Empty;
                        ImgHelper.IsImgageType(byteData, "jpg", out ext);
                        HashSet <string> fileType = new HashSet <string>()
                        {
                            "png", "jpg", "jpeg", "gif", "bmp"
                        };
                        if (fileType.Contains(ext))
                        {
                            SaveImageToAliOSS(byteData, out aliTempImgKey);
                        }
                        else
                        {
                            aliTempImgKey = "";
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(aliTempImgKey);
        }
예제 #22
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            try
            {
                string format          = context.Request["format"];//文件后缀名
                int    sDirectorieType = string.IsNullOrEmpty(context.Request["sDirectorieType"]) ? -1 : Convert.ToInt32(context.Request["sDirectorieType"]);
                string KeyId           = context.Request["KeyId"];
                //文件夹目录
                string sDirectorieName = "other\\";
                switch (sDirectorieType)
                {
                case 0: sDirectorieName = "Promotion\\"; break;

                case 1:
                    sDirectorieName = string.Format("Hall\\Hall_{0}\\", KeyId);
                    break;

                case 2: sDirectorieName = string.Format("Hall\\Hall_{0}\\Waiter\\", KeyId);
                    break;
                }

                if (context.Request.InputStream.Length > 0)
                {
                    /*图片保存路径*/
                    string sPath = System.AppDomain.CurrentDomain.BaseDirectory + "images\\";
                    sPath = sPath + sDirectorieName;
                    if (!Directory.Exists(sPath))
                    {
                        Directory.CreateDirectory(sPath);
                    }
                    string sFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + format;
                    long   length    = context.Request.InputStream.Length;
                    if (length > 100 * 1024)
                    {
                        //超过100kb压缩
                        int flag = (int)Math.Ceiling((double)length / (double)(1024 * 100));
                        ImgHelper.GetPicThumbnail(context.Request.InputStream, sPath + sFileName, flag);
                    }
                    else
                    {
                        Image img = Bitmap.FromStream(context.Request.InputStream);
                        img.Save(sPath + sFileName);
                    }
                    string srcPicture = ConfigurationManager.AppSettings["domin"] + "/images/" + sDirectorieName.Replace(@"\", "/") + sFileName;
                    context.Response.Write(srcPicture);
                }
                else
                {
                    context.Response.Write("parameters error");
                }
            }
            catch (Exception e)
            {
                logger.Info(e.Message);
                logger.Fatal(e.Message, e);
                context.Response.Write("server error");
            }
        }
예제 #23
0
        /// <summary>
        /// 获取图形验证码
        /// </summary>
        public ActionResult GetCheckCodeImg()
        {
            var code = "";

            byte[] imgArr = ImgHelper.CreateImgStream(out code);
            SetSession(ComConst.Session_ImgCode, code);
            return(File(imgArr, "image/jpge"));
        }
예제 #24
0
        public ActionResult UpLoadPDF()
        {
            string             str  = "NoPDF";
            HttpPostedFileBase item = null;

            if (base.Request.Files.Count > 0)
            {
                if (base.Request.Files.Count == 0)
                {
                    return(base.Content("NoFile", "text/html"));
                }
                item = base.Request.Files[0];
                if (item == null || item.ContentLength <= 0 || !IsAllowExt(item))
                {
                    return(base.Content("格式不正确!", "text/html"));
                }
                if (item != null)
                {
                    string serverFilepath = Server.MapPath(string.Format("/Storage/PDF/{0}/ ", base.CurrentUser.Id));
                    string serverFileName = "CoAReports" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
                    string PDF            = serverFilepath + '\\' + serverFileName;
                    if (!System.IO.Directory.Exists(serverFilepath))
                    {
                        System.IO.Directory.CreateDirectory(serverFilepath);
                    }
                    try
                    {
                        object obj = Cache.Get("Cache-UserUploadPDF");
                        if (obj != null)
                        {
                            Cache.Insert("Cache-UserUploadPDF", int.Parse(obj.ToString()) + 1);
                        }
                        else
                        {
                            Cache.Insert("Cache-UserUploadPDF", 1);
                        }
                        item.SaveAs(PDF);
                        str = ImgHelper.PostImg(PDF, "coapic");//文件路径
                    }
                    catch (Exception exception1)
                    {
                        Exception exception = exception1;
                        object    obj1      = Cache.Get("Cache-UserUploadPDF");
                        if (obj1 != null)
                        {
                            Cache.Insert("Cache-UserUploadPDF", int.Parse(obj1.ToString()) - 1);
                        }
                        Log.Error(string.Concat("产品导入上传文件异常:", exception.Message));
                        str = "Error";
                    }
                }
                else
                {
                    str = "文件长度为0,格式异常。";
                }
            }
            return(base.Content(str, "text/html", System.Text.Encoding.UTF8));//将文件名回传给页面的innerHTML
        }
예제 #25
0
        static void Main(string[] args)
        {
            Image image  = Image.FromFile("1.jpg");
            var   newImg = ImgHelper.AddText(image, new Rectangle(0, 0, 50, 50), "测试", Color.White);

            newImg.Save("2.jpg", ImageFormat.Jpeg);

            Console.WriteLine("Hello World!");
        }
예제 #26
0
        /// <summary>
        /// 保存附件
        /// </summary>
        /// <param name="file">要保存的附件</param>
        /// <param name="targetCategory">附件存放的文件夹</param>
        /// <param name="fileAttachOption">附件配置</param>
        /// <returns>返回文件名</returns>
        public string SaveLocalhostImgAttach(HttpPostedFile file, string targetCategory, FileAttachOption fileAttachOption)
        {
            var fileSuffix = Utils.GetUrlSuffix(file.FileName);

            if (fileAttachOption.ImgSuffix == null || fileAttachOption.ImgSuffix.Count() <= 0)
            {
                // 加载配置数据
                if (!string.IsNullOrEmpty(ImgSuffixConfig))
                {
                    fileAttachOption.ImgSuffix = ImgSuffixConfig.Split('|');
                }
            }

            CheckFileSuffix(fileAttachOption, fileSuffix);
            //var fileInfo = new FileInfo(file.FileName);
            // 随机生成图片名并为原图
            string saveFileName = Guid.NewGuid() + "." + fileSuffix;
            string sitePath     = targetCategory;
            string basePath     = HttpContext.Current.Server.MapPath("/") + sitePath;
            // 文件名称
            string fileNameS   = "s_" + saveFileName;                         // 缩略图文件名称
            string fileNameB   = "b_" + saveFileName;                         // 标准图文件名称
            string webFilePath = basePath + saveFileName;                     // 文件原图

            // 保存原始文件
            if (!System.IO.File.Exists(webFilePath))
            {
                // 检查是否有该文件夹,没有则创建
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }

                file.SaveAs(webFilePath);
                // 生成缩略图方法
                if (fileAttachOption.BuildOriginalImg)
                {
                    ImgHelper.MakeThumbnail(webFilePath,
                                            basePath + fileNameS,
                                            fileAttachOption.OriginalImgWidth,
                                            fileAttachOption.OriginalImgHeight,
                                            fileAttachOption.OriginalImgModel.ToString());
                }
                // 生成标准图方法
                if (fileAttachOption.BuildStandardImg)
                {
                    ImgHelper.MakeThumbnail(webFilePath,
                                            basePath + fileNameB,
                                            fileAttachOption.StandardImgWidth,
                                            fileAttachOption.StandardImgHeight,
                                            fileAttachOption.StandardImgModel.ToString());
                }
                //return  sitePath + saveFileName;
                return(saveFileName);
            }
            return("");
        }
예제 #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="httpFile"></param>
        /// <param name="toFilePath">图片存放路径</param>
        /// <returns></returns>
        public ResultModel <ImageInfo> UpLoadFile(HttpPostedFile httpFile, string toFilePath)
        {
            ResultModel <ImageInfo> img = new ResultModel <ImageInfo>()
            {
                Msg = new Result_Msg()
                {
                    IsSuccess = true, Message = string.Empty
                },
                Model = new ImageInfo()
            };

            try
            {
                img.Model.ImageName     = httpFile.FileName;                                //获取要保存的文件信息
                img.Model.ExtensionName = System.IO.Path.GetExtension(img.Model.ImageName); //获得文件扩展名
                if (CheckFileExt(img.Model.ExtensionName))
                {
                    //检查保存的路径 是否有/结尾
                    if (toFilePath.EndsWith("/") == false)
                    {
                        toFilePath = toFilePath + "/";
                    }
                    //按日期归类保存
                    string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
                    if (true)
                    {
                        //toFilePath += datePath;
                        img.Model.PathUrl = toFilePath;
                    }
                    //物理完整路径
                    string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + toFilePath;
                    //检查是否有该路径  没有就创建
                    if (!System.IO.Directory.Exists(toFileFullPath))
                    {
                        Directory.CreateDirectory(toFileFullPath);
                    }
                    //得到服务器文件保存路径
                    string toFile = Server.MapPath("~" + toFilePath);
                    string f_file = getName(img.Model.ImageName);

                    httpFile.SaveAs(toFile + f_file);                               //文件上传到web服务器
                    img.Model.PathUrl = ImgHelper.PostImg(toFile + f_file, "file"); //将文件从web服务器拷贝到文件服务器
                }
                else
                {
                    img.Msg.IsSuccess = false;
                    img.Msg.Message   = "文件不合法";
                }
            }
            catch (Exception e)
            {
                img.Msg.IsSuccess = false;
                img.Msg.Message   = "文件上传失败,错误原因:" + e.Message;
            }
            return(img);
        }
예제 #28
0
        public JsonResult Handle(HttpPostedFileBase fileData)
        {
            string fileName = Path.GetFileName(fileData.FileName);
            var    filePath = Path.Combine(Request.MapPath("~/Upload"), fileName);

            fileData.SaveAs(filePath);
            var thumbnailFile = Path.Combine(Request.MapPath("~/Upload/Thumbnail"), fileName);

            ImgHelper.GetPicThumbnail(filePath, thumbnailFile, 133, 200, 100);
            return(Json(new { Success = true, File = "/Upload/" + fileName, ThumbnailFile = "/Upload/Thumbnail/" + fileName, FileName = fileName }));
        }
        /// <summary>
        /// 相关搜索
        /// </summary>
        /// <param name="context"></param>
        public void Init_Xgss(NVelocity.VelocityContext context)
        {
            StringBuilder sbr = new StringBuilder();
            DataSet       ds  = null;

            try
            {
                string sql = "select top 6 id,title,types,isimg,img_url from hrenh_article where isend=0 and types in(1,3,4,5) and pub_state=0";

                sql += " order by read_cnt desc,id desc";

                ds = DbHelperSQL.Query(sql);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = ds.Tables[0].Rows[i];

                        int    article_id         = String_Manage.Return_Int(dr["id"].ToString(), 0);
                        string article_title      = String_Manage.Return_Str(dr["title"].ToString(), "");
                        string show_article_title = StringHelper.ReturnNumStr(article_title, 1, 10);
                        string article_url        = "href=\"/article_detail_" + article_id + "\" target=\"_blank\" title=\"" + article_title + "\"";

                        article_url = "href=\"/" + ArticleHelper.Get_Nav_Type_Name(Convert.ToInt32(dr["types"].ToString())) + "/detail_" + article_id + ".html\" target=\"_blank\" title=\"" + article_title + "\"";
                        int    isimg       = String_Manage.Return_Int(dr["isimg"].ToString(), 0);
                        string article_img = "/template/img/nocontent.png";

                        if (isimg == 1)
                        {
                            article_img = ImgHelper.Get_UploadImgUrl(dr["img_url"].ToString(), 1);
                        }

                        sbr.AppendFormat("<li>");
                        sbr.AppendFormat("<a {0}>{1}", article_url, show_article_title);
                        //sbr.AppendFormat("<img src=\"{0}\" height=\"80\" width=\"140\" alt=\"{1}\">", article_img, article_title);
                        //sbr.AppendFormat("<p>{0}</p>", show_article_title);
                        //sbr.AppendFormat("<i class=\"vedioIcon\"></i>");
                        sbr.AppendFormat("</a>");
                        sbr.AppendFormat("</li>");
                    }
                }
                else
                {
                    sbr.Append("<div class=\"nodata\">没有找到相关数据</div>");
                }
            }
            catch (Exception ex)
            {
                sbr.AppendFormat(ex.ToString());
            }

            context.Put("xgss", sbr.ToString());
        }
        public ActionResult Test()
        {
            string imgBase64Url = System.IO.File.ReadAllText(Path.Combine(GlobalSwitch.WebRootPath, "img.txt"));

            Console.WriteLine(imgBase64Url);
            var img = ImgHelper.GetImgFromBase64Url(imgBase64Url);

            img.Save(Path.Combine(GlobalSwitch.WebRootPath, "Upload", "1.jpg"));

            return(Success(GlobalSwitch.WebRootPath));
        }