Пример #1
0
        public static void MarkWater(string filepath, string waterfile, string watermarkPosition)
        {
            byte[]       barrImgData      = System.IO.File.ReadAllBytes(filepath);
            byte[]       barrWaterImgData = System.IO.File.ReadAllBytes(waterfile);
            MemoryStream msImg            = new MemoryStream(barrImgData);
            MemoryStream msWaterImg       = new MemoryStream(barrWaterImgData);
            Image        img     = null;
            Image        markImg = null;

            try
            {
                img     = Image.FromStream(msImg);
                markImg = Image.FromStream(msWaterImg);
                float[][] ptsArray =
                {
                    new float[] { 1, 0, 0,    0, 0 },
                    new float[] { 0, 1, 0,    0, 0 },
                    new float[] { 0, 0, 1,    0, 0 },
                    new float[] { 0, 0, 0, 1.0f, 0 },                       //注意:此处为0.0f为完全透明,1.0f为完全不透明
                    new float[] { 0, 0, 0,    0, 1 }
                };
                ColorMatrix     colorMatrix     = new ColorMatrix(ptsArray);
                ImageAttributes imageAttributes = new ImageAttributes();
                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.SkipGrays, ColorAdjustType.Bitmap);
                Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format48bppRgb);
                newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                Graphics g = Graphics.FromImage(newBitmap);
                g.SmoothingMode      = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

                Rectangle watermarkRectangle = PicHandle.GetWatermarkRectangle(img.Width, img.Height, markImg.Width, markImg.Height, watermarkPosition);
                g.DrawImage(markImg, watermarkRectangle, 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes);
                g.Dispose();
                ImageFormat igf = img.RawFormat;
                if (img != null)
                {
                    img.Dispose();
                }
                newBitmap.Save(filepath, igf);
                newBitmap.Dispose();
            }
            catch (Exception exp)
            {
                XMS.Core.Container.LogService.Error("水印出错:" + exp.ToString());
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (markImg != null)
                {
                    markImg.Dispose();
                }
            }
        }
Пример #2
0
        /// <summary>
        /// 指定所绘制图像的位置和大小。将图像进行缩放以适合该矩形。
        /// </summary>
        /// <returns></returns>
        private static Rectangle GetWatermarkRectangle(int baseMapWidth, int baseMapHeight, int WatermarkWidth, int WatermarkHeight, string WatermarkPosition)
        {
            if (WatermarkWidth > (baseMapWidth - 5) || WatermarkHeight > (baseMapHeight - 5))
            {
                return(new Rectangle(0, baseMapHeight - WatermarkHeight, WatermarkWidth, WatermarkHeight));
            }
            Rectangle result = new Rectangle();

            switch (WatermarkPosition.ToLower())
            {
            case "righttop":
                result = PicHandle.GetRightTopRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;

            case "rightbottom":
                result = PicHandle.GetRightBottomRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;

            case "lefttop":
                result = PicHandle.GetLeftTopRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;

            case "leftbottom":
                result = PicHandle.GetLeftBottomRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;

            case "center":
                result = PicHandle.GetCenterRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;

            default:
                result = PicHandle.GetRightBottomRectangle(baseMapWidth, baseMapHeight, WatermarkWidth, WatermarkHeight);
                break;
            }
            return(result);
        }
Пример #3
0
        /// <summary>
        /// 上传图片主方法
        /// </summary>
        /// <param name="picData">图片流</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="rootKey">配置文件中Key值</param>
        /// <param name="isThumbnail">是否需要缩略图</param>
        /// <returns></returns>
        public PhotoResult UploadPic(byte[] picData, string filePath, bool autoControl)
        {
            //记录上传阿里云的数据
            List <string> lstPath = new List <string>();

            string rootPath = @"C:\Web\AppWapCoffee\UploadImage";

            PhotoResult ps     = new PhotoResult();
            Regex       rgDisk = new Regex(@"^(.*)[a-zA-Z]:[/\\]", RegexOptions.Compiled);

            filePath = rgDisk.Replace(filePath, "");
            if (picData == null || picData.Length > AppSettingHelper.FileMaxSize)
            {
                throw new ArgumentNullException("上传文件为空或者超过限定大小");
            }
            filePath = "/" + filePath.Replace("\\\\", "/").Replace("\\", "/").Replace("//", "/").TrimStart('/'); //将 双正斜杠,双反斜杠,反斜杠都变成 正斜杠
            if (!_regRegexFilePath.IsMatch(filePath))
            {
                throw new ArgumentNullException("文件路径错误,标准格式为(/[a-z0-9A-Z]+/)*[a-z0-9A-Z]+");
            }
            //if (RealRule[rootKey] == null)
            //{
            //    throw new ArgumentNullException("未存在的上传规则配置项");
            //}
            //Rule objCurrentRule = (Rule)RealRule[rootKey];
            //bool bIsWaterMake = objCurrentRule.IsWaterMark;
            //string sWaterFile = objCurrentRule.WaterFilePath;
            //string watermarkPosition = objCurrentRule.WatermarkPosition;
            string _sDateDir = DateTime.Now.ToString("yyyyMMdd") + "/";
            //传入的文件夹
            string _sFileFoder = (filePath.LastIndexOf('/') >= 0) ? filePath.Substring(0, filePath.LastIndexOf('/')).TrimStart('/').TrimEnd('/') + "/" : String.Empty;
            //传入的文件名
            string _sFileName = (filePath.LastIndexOf('/') >= 0) ? filePath.Substring(filePath.LastIndexOf('/') + 1) : filePath;
            //传入的文件类型
            string _sFileType = (_sFileName.LastIndexOf(".") > 0) ? _sFileName.Substring(_sFileName.LastIndexOf(".")).ToLower() : String.Empty;
            //目标文件夹
            string _sDir = rootPath.TrimEnd('/') + "/" + _sDateDir + _sFileFoder;
            //if (!objCurrentRule.IsAddDateFolder)
            //{
            //    _sDir = objCurrentRule.RootPath.TrimEnd('/') + "/" + _sFileFoder;
            //}

            //png图片不需要打水印,否则会将水印的背景色遮住原有图片
            //if (_sFileType.Equals(".png", StringComparison.CurrentCultureIgnoreCase))
            //{
            //    bIsWaterMake = false;
            //}

            //目标文件名
            string _sNewFileName = _sFileName;

            if (autoControl)
            {
                _sNewFileName = System.Guid.NewGuid().ToString() + _sFileType;
            }

            string _sBigFile      = _sDir + _sNewFileName; //大图地址
            string _sOriginalFile = string.Empty;          //原始图

            if (!Directory.Exists(_sDir))
            {
                Directory.CreateDirectory(_sDir);
            }
            ps.Md5 = PicHandle.GetMd5Hash(picData);
            using (FileStream stream = new FileStream(_sBigFile, FileMode.OpenOrCreate))
            {
                XMS.Core.Container.LogService.Error("_sBigFile:" + _sBigFile);
                lstPath.Add(_sBigFile);
                stream.Write(picData, 0, picData.Length);
                stream.Close();
            }
            //if (".jpg".Equals(_sFileType, StringComparison.CurrentCultureIgnoreCase)
            //    || ".jpeg".Equals(_sFileType, StringComparison.CurrentCultureIgnoreCase)
            //    || ".gif".Equals(_sFileType, StringComparison.CurrentCultureIgnoreCase)
            //    || ".png".Equals(_sFileType, StringComparison.CurrentCultureIgnoreCase)
            // )
            //{
            //    byte[] barrImgData = System.IO.File.ReadAllBytes(_sBigFile);
            //    MemoryStream ms = new MemoryStream(barrImgData);
            //    Image originalImage = null;
            //    try
            //    {
            //        originalImage = Image.FromStream(ms);
            //        ps.Width = originalImage.Width;
            //        ps.Height = originalImage.Height;
            //        //根据图片大小来选择水印图片
            //        if (ps.Width <= 320 || originalImage.Height <= 240)
            //        {
            //            if (System.IO.File.Exists(sWaterFile.Replace(".png", "-small.png")))
            //            {
            //                sWaterFile = sWaterFile.Replace(".png", "-small.png");
            //            }
            //        }
            //        PicGeoHelper.FloatPoint point = PicGeoHelper.GetPoint(originalImage);
            //        if (point != null)
            //        {
            //            ps.Longitude = point.Longitude;
            //            ps.Latitude = point.Latitude;
            //            ps.PhotoTime = point.PhotoTime;
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        if (originalImage != null) { originalImage.Dispose(); }
            //        XMS.Core.Container.LogService.Error("读取图片信息出错:" + e.ToString());
            //    }
            //    finally
            //    {
            //        if (originalImage != null)
            //        {
            //            originalImage.Dispose();
            //        }
            //    }
            //    if (!string.IsNullOrEmpty(objCurrentRule.MaxSize))
            //    {
            //        try
            //        {
            //            string[] MaxSizeFormat = objCurrentRule.MaxSize.Split(',');
            //            if (MaxSizeFormat.Length >= 2)
            //            {
            //                int nMaxWidth = Convert.ToInt32(MaxSizeFormat[0]);
            //                int nMaxHeight = Convert.ToInt32(MaxSizeFormat[1]);
            //                if (nMaxWidth < ps.Width || nMaxHeight < ps.Height)//如果宽或高超过了就截图
            //                {
            //                    string sTempOriginalFile = _sDir + "TempOriginal/" + _sNewFileName;//设置一个临时的目录文件
            //                    if (PicHandle.CreateThumbnailImage(_sBigFile, sTempOriginalFile, nMaxWidth, nMaxHeight))//截成理想大小成功
            //                    {
            //                        if (System.IO.File.Exists(sTempOriginalFile))
            //                        {
            //                            System.IO.File.Delete(_sBigFile);
            //                            System.IO.File.Move(sTempOriginalFile, _sBigFile);
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //        catch (Exception exp)
            //        {
            //            XMS.Core.Container.LogService.Error(exp.ToString());
            //        }
            //    }
            //    //存放原图
            //    if (!Directory.Exists(_sDir + "Original/"))
            //    {
            //        Directory.CreateDirectory(_sDir + "Original/");
            //    }
            //    _sOriginalFile = _sDir + "Original/" + _sNewFileName;          //更改原图地址
            //    using (FileStream stream = new FileStream(_sOriginalFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            //    {
            //        XMS.Core.Container.LogService.Error("_sOriginalFile:" + _sOriginalFile);
            //        lstPath.Add(_sOriginalFile);
            //        stream.Write(picData, 0, picData.Length);
            //        stream.Close();
            //    }

            //    //缩略图
            //    if (isThumbnail)
            //    {
            //        if (!String.IsNullOrEmpty(objCurrentRule.Small))
            //        {
            //            string[] Format = objCurrentRule.Small.Split(',');
            //            PicHandle.CreateThumbnailImage(_sBigFile, _sDir + "Small/" + _sNewFileName, Convert.ToInt32(Format[0]), Convert.ToInt32(Format[1]));
            //            if (Format.Length == 3 && Format[2].ToLower() == "true" && System.IO.File.Exists(sWaterFile))
            //            {
            //                PicHandle.MarkWater(_sDir + "Small/" + _sNewFileName, sWaterFile, watermarkPosition);
            //            }
            //            XMS.Core.Container.LogService.Error("Small:" + _sDir + "Small/" + _sNewFileName);
            //            lstPath.Add(_sDir + "Small/" + _sNewFileName);
            //        }
            //        if (!String.IsNullOrEmpty(objCurrentRule.Middle))
            //        {
            //            string[] Format = objCurrentRule.Middle.Split(',');
            //            PicHandle.CreateThumbnailImage(_sBigFile, _sDir + "Middle/" + _sNewFileName, Convert.ToInt32(Format[0]), Convert.ToInt32(Format[1]));
            //            if (Format.Length == 3 && Format[2].ToLower() == "true" && System.IO.File.Exists(sWaterFile))
            //            {
            //                PicHandle.MarkWater(_sDir + "Middle/" + _sNewFileName, sWaterFile, watermarkPosition);
            //            }
            //            XMS.Core.Container.LogService.Error("Middle:" + _sDir + "Middle/" + _sNewFileName);
            //            lstPath.Add(_sDir + "Middle/" + _sNewFileName);
            //        }
            //        if (!String.IsNullOrEmpty(objCurrentRule.Big))
            //        {
            //            string[] Format = objCurrentRule.Big.Split(',');
            //            PicHandle.CreateThumbnailImage(_sBigFile, _sDir + "Big/" + _sNewFileName, Convert.ToInt32(Format[0]), Convert.ToInt32(Format[1]));
            //            if (Format.Length == 3 && Format[2].ToLower() == "true" && System.IO.File.Exists(sWaterFile))
            //            {
            //                PicHandle.MarkWater(_sDir + "Big/" + _sNewFileName, sWaterFile, watermarkPosition);
            //            }
            //            XMS.Core.Container.LogService.Error("Big:" + _sDir + "Big/" + _sNewFileName);
            //            lstPath.Add(_sDir + "Big/" + _sNewFileName);
            //        }
            //        //其他N种缩略图
            //        if (objCurrentRule.Others != null && objCurrentRule.Others.Count > 0)
            //        {
            //            foreach (Rule.ThumbnailImg objImg in objCurrentRule.Others)
            //            {
            //                if (objImg.Width > 0 || objImg.Height > 0)
            //                {
            //                    string sFolder = string.Format("{0}_{1}", objImg.Width, objImg.IsAutoThumbWhenWidthEqualsHeight ? "x" : objImg.Height.ToString());
            //                    //生成缩略图
            //                    PicHandle.CreateThumbnailImage(_sBigFile, _sDir + sFolder + "/" + _sNewFileName, objImg.Width, objImg.Height, objImg.IsAutoThumbWhenWidthEqualsHeight);
            //                    if (bIsWaterMake && objImg.IsWaterMark && System.IO.File.Exists(sWaterFile))  //需要打水印
            //                    {
            //                        PicHandle.MarkWater(_sDir + sFolder + "/" + _sNewFileName, sWaterFile, watermarkPosition);
            //                    }
            //                    XMS.Core.Container.LogService.Error("sFolder:" + _sDir + sFolder + "/" + _sNewFileName);
            //                    lstPath.Add(_sDir + sFolder + "/" + _sNewFileName);
            //                }
            //            }
            //        }
            //    }
            //    //给大图打水印
            //    if (bIsWaterMake && System.IO.File.Exists(sWaterFile))
            //    {
            //        PicHandle.MarkWater(_sBigFile, sWaterFile, watermarkPosition);   //上传图片加上水印
            //    }

            //    //修改原图名称
            //    if (System.IO.File.Exists(_sDir + "Original/" + _sNewFileName))
            //    {
            //        string sMoveToFile = _sDir + "Original/" + _sNewFileName + ".config";
            //        try
            //        {
            //            if (System.IO.File.Exists(sMoveToFile))
            //            {
            //                System.IO.File.Delete(sMoveToFile);
            //            }
            //            System.IO.File.Move(_sDir + "Original/" + _sNewFileName, sMoveToFile);
            //            System.IO.File.Delete(_sDir + "Original/" + _sNewFileName);
            //        }
            //        catch (Exception exp)
            //        {
            //            XMS.Core.Container.LogService.Error(exp.ToString());
            //        }
            //    }
            //    if (!String.IsNullOrEmpty(objCurrentRule.ReplaceOriginalFile))
            //    {
            //        try
            //        {
            //            string sReplaceFile = _sDir + objCurrentRule.ReplaceOriginalFile + "/" + _sNewFileName;
            //            if (System.IO.File.Exists(sReplaceFile))
            //            {
            //                System.IO.File.Delete(_sDir + "/" + _sNewFileName);
            //                System.IO.File.Move(sReplaceFile, _sDir + "/" + _sNewFileName);
            //            }
            //        }
            //        catch { }
            //    }
            //}
            string _sVirtualPath = "http://waimai.buzztimecoffee.com/AppWapCoffee/UploadImage".TrimStart('/').TrimEnd('/') + "/" + _sDateDir + _sFileFoder;

            //if (!objCurrentRule.IsAddDateFolder)
            //{
            //    _sVirtualPath = objCurrentRule.VirtualPath.TrimStart('/').TrimEnd('/') + "/" + _sFileFoder.TrimStart('/');
            //}
            ps.Path = _sVirtualPath.TrimStart('/').TrimEnd('/') + "/" + _sNewFileName;
            ps.Url  = ps.Path;
            //lstPath.Add(objCurrentRule.RootPath);
            //DoUploadFileToOss(lstPath, objCurrentRule.VirtualPath);
            //Thread t = new Thread(new ParameterizedThreadStart(DoUploadFileToOss));
            //t.IsBackground = true;
            //t.Start(lstPath);
            return(ps);
        }