示例#1
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="byteData">图片字节数组</param>
        /// <param name="fileExt">图片扩展名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static byte[] AddImageSignPic(byte[] byteData, string fileExt, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            //缩略图
            Image watermark = null;

            //判断是否远程文件
            if (watermarkFilename.ToLower().StartsWith("http://") || watermarkFilename.ToLower().StartsWith("https://"))
            {
                byte[] watermarkData = null;
                try
                {
                    WebClient client = new WebClient();
                    watermarkData = client.DownloadData(watermarkFilename);
                    client.Dispose();
                }
                catch
                {
                    return(byteData);
                }
                using (MemoryStream memoryStream = new MemoryStream(watermarkData))
                {
                    watermark = Image.FromStream(memoryStream);
                }
            }
            else
            {
                if (watermarkFilename.StartsWith("/") == false)
                {
                    watermarkFilename = "/" + watermarkFilename;
                }
                watermarkFilename = Utils.GetMapPath(watermarkFilename);
                if (!File.Exists(watermarkFilename))
                {
                    return(byteData);
                }
                watermark = new Bitmap(watermarkFilename);
            }
            //原图
            Image img = null;

            using (MemoryStream memoryStream = new MemoryStream(byteData))
            {
                img = Image.FromStream(memoryStream);
            }
            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                img.Dispose();
                return(byteData);
            }
            Graphics g = Graphics.FromImage(img);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode   = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (ici != null)
                    {
                        img.Save(ms, ici, encoderParams);
                    }
                    else
                    {
                        img.Save(ms, GetFormat(fileExt));
                    }
                    byte[] buffer = new byte[ms.Length];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(buffer, 0, buffer.Length);
                    return(buffer);
                }
            }
            finally
            {
                g.Dispose();
                img.Dispose();
                watermark.Dispose();
                imageAttributes.Dispose();
            }
        }
示例#2
0
    /// <summary>
    /// 图片水印
    /// </summary>
    /// <param name="imgPath">服务器图片相对路径</param>
    /// <param name="filename">保存文件名</param>
    /// <param name="watermarkFilename">水印文件相对路径</param>
    /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
    /// <param name="quality">附加水印图片质量,0-100</param>
    /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
    public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
    {
        byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
            filename = HttpContext.Current.Server.MapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
                watermarkFilename = "/" + watermarkFilename;
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
                return;
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                return;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;
            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
                transparency = (watermarkTransparency / 10.0F);

            float[][] colorMatrixElements = {
                                                new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
                                                new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 2:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 3:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 4:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 5:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 6:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 7:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 8:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 9:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
    }
示例#3
0
    /// <summary>
    /// 图片等比缩放
    /// </summary>
    /// <remarks>吴剑 2011-01-21</remarks>
    /// <param name="postedFile">原图HttpPostedFile对象</param>
    /// <param name="savePath">缩略图存放地址</param>
    /// <param name="targetWidth">指定的最大宽度</param>
    /// <param name="targetHeight">指定的最大高度</param>
    /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
    /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
    public static void ZoomAuto(System.Web.HttpPostedFileBase postedFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage)
    {
        //创建目录
        string dir = Path.GetDirectoryName(savePath);
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
        System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

        //原图宽高均小于模版,不作处理,直接保存
        if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
        {
            //文字水印
            if (watermarkText != "")
            {
                using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                {
                    System.Drawing.Font fontWater = new Font("黑体", 10);
                    System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                    gWater.Dispose();
                }
            }

            //透明图片水印
            if (watermarkImage != "")
            {
                if (File.Exists(watermarkImage))
                {
                    //获取水印图片
                    using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                    {
                        //水印绘制条件:原始图片宽高均大于或等于水印图片
                        if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                        {
                            Graphics gWater = Graphics.FromImage(initImage);

                            //透明属性
                            ImageAttributes imgAttributes = new ImageAttributes();
                            ColorMap colorMap = new ColorMap();
                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                            ColorMap[] remapTable = { colorMap };
                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                            float[][] colorMatrixElements = {
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                            gWater.Dispose();
                        }
                        wrImage.Dispose();
                    }
                }
            }

            //保存
            initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        else
        {
            //缩略图宽、高计算
            double newWidth = initImage.Width;
            double newHeight = initImage.Height;

            //宽大于高或宽等于高(横图或正方)
            if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
            {
                //如果宽大于模版
                if (initImage.Width > targetWidth)
                {
                    //宽按模版,高按比例缩放
                    newWidth = targetWidth;
                    newHeight = initImage.Height * (targetWidth / initImage.Width);
                }
            }
            //高大于宽(竖图)
            else
            {
                //如果高大于模版
                if (initImage.Height > targetHeight)
                {
                    //高按模版,宽按比例缩放
                    newHeight = targetHeight;
                    newWidth = initImage.Width * (targetHeight / initImage.Height);
                }
            }

            //生成新图
            //新建一个bmp图片
            System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
            //新建一个画板
            System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

            //设置质量
            newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //置背景色
            newG.Clear(Color.White);
            //画图
            newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

            //文字水印
            if (watermarkText != "")
            {
                using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                {
                    System.Drawing.Font fontWater = new Font("宋体", 10);
                    System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                    gWater.Dispose();
                }
            }

            //透明图片水印
            if (watermarkImage != "")
            {
                if (File.Exists(watermarkImage))
                {
                    //获取水印图片
                    using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                    {
                        //水印绘制条件:原始图片宽高均大于或等于水印图片
                        if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                        {
                            Graphics gWater = Graphics.FromImage(newImage);

                            //透明属性
                            ImageAttributes imgAttributes = new ImageAttributes();
                            ColorMap colorMap = new ColorMap();
                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                            ColorMap[] remapTable = { colorMap };
                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                            float[][] colorMatrixElements = {
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                            gWater.Dispose();
                        }
                        wrImage.Dispose();
                    }
                }
            }

            //保存缩略图
            newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //释放资源
            newG.Dispose();
            newImage.Dispose();
            initImage.Dispose();
        }
    }
示例#4
0
        /// <summary>
        /// Creating a Watermarked Photograph with GDI+ for .NET
        /// </summary>
        /// <param name="rSrcImgPath">原始图片的物理路径</param>
        /// <param name="rMarkImgPath">水印图片的物理路径</param>
        /// <param name="rMarkText">水印文字(不显示水印文字设为空串)</param>
        /// <param name="rDstImgPath">输出合成后的图片的物理路径</param>
        public static void BuildWatermark(string rSrcImgPath, string rMarkImgPath, string rMarkText, string rDstImgPath)
        {
            //以下(代码)从一个指定文件创建了一个Image 对象,然后为它的 Width 和 Height定义变量。
            //这些长度待会被用来建立一个以24 bits 每像素的格式作为颜色数据的Bitmap对象。
            Image  imgPhoto = Image.FromFile(rSrcImgPath);
            int    phWidth  = imgPhoto.Width;
            int    phHeight = imgPhoto.Height;
            Bitmap bmPhoto  = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(72, 72);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            //这个代码载入水印图片,水印图片已经被保存为一个BMP文件,以绿色(A=0,R=0,G=255,B=0)作为背景颜色。
            //再一次,会为它的Width 和Height定义一个变量。
            Image imgWatermark = new Bitmap(rMarkImgPath);
            int   wmWidth      = imgWatermark.Width;
            int   wmHeight     = imgWatermark.Height;

            //这个代码以100%它的原始大小绘制imgPhoto 到Graphics 对象的(x=0,y=0)位置。
            //以后所有的绘图都将发生在原来照片的顶部。
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.DrawImage(
                imgPhoto,
                new Rectangle(0, 0, phWidth, phHeight),
                0,
                0,
                phWidth,
                phHeight,
                GraphicsUnit.Pixel);
            //为了最大化版权信息的大小,我们将测试7种不同的字体大小来决定我们能为我们的照片宽度使用的可能的最大大小。
            //为了有效地完成这个,我们将定义一个整型数组,接着遍历这些整型值测量不同大小的版权字符串。
            //一旦我们决定了可能的最大大小,我们就退出循环,绘制文本
            int[] sizes  = new int[] { 92, 62, 42, 32, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4 };
            Font  crFont = null;
            SizeF crSize = new SizeF();

            for (int i = 0; i < sizes.Length; i++)
            {
                crFont = new Font("华文彩云", sizes[i],
                                  FontStyle.Bold);
                crSize = grPhoto.MeasureString(rMarkText,
                                               crFont);
                if ((ushort)crSize.Width < (ushort)phWidth)
                {
                    break;
                }
            }
            //因为所有的照片都有各种各样的高度,所以就决定了从图象底部开始的5%的位置开始。
            //使用rMarkText字符串的高度来决定绘制字符串合适的Y坐标轴。
            //通过计算图像的中心来决定X轴,然后定义一个StringFormat 对象,设置StringAlignment 为Center。
            int   yPixlesFromBottom = (int)(phHeight * .05);
            float yPosFromBottom    = ((phHeight -
                                        yPixlesFromBottom) - (crSize.Height / 2));
            float        xCenterOfImg = (phWidth / 2);
            StringFormat StrFormat    = new StringFormat();

            StrFormat.Alignment = StringAlignment.Center;
            //现在我们已经有了所有所需的位置坐标来使用60%黑色的一个Color(alpha值153)创建一个SolidBrush 。
            //在偏离右边1像素,底部1像素的合适位置绘制版权字符串。
            //这段偏离将用来创建阴影效果。使用Brush重复这样一个过程,在前一个绘制的文本顶部绘制同样的文本。
            SolidBrush semiTransBrush2 =
                new SolidBrush(Color.FromArgb(153, 0, 0, 0));

            grPhoto.DrawString(rMarkText,
                               crFont,
                               semiTransBrush2,
                               new PointF(xCenterOfImg + 1, yPosFromBottom + 1),
                               StrFormat);
            SolidBrush semiTransBrush = new SolidBrush(
                Color.FromArgb(153, 255, 255, 255));

            grPhoto.DrawString(rMarkText,
                               crFont,
                               semiTransBrush,
                               new PointF(xCenterOfImg, yPosFromBottom),
                               StrFormat);
            //根据前面修改后的照片创建一个Bitmap。把这个Bitmap载入到一个新的Graphic对象。
            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(
                imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);
            Graphics grWatermark =
                Graphics.FromImage(bmWatermark);
            //通过定义一个ImageAttributes 对象并设置它的两个属性,我们就是实现了两个颜色的处理,以达到半透明的水印效果。
            //处理水印图象的第一步是把背景图案变为透明的(Alpha=0, R=0, G=0, B=0)。我们使用一个Colormap 和定义一个RemapTable来做这个。
            //就像前面展示的,我的水印被定义为100%绿色背景,我们将搜到这个颜色,然后取代为透明。
            ImageAttributes imageAttributes =
                new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            //第二个颜色处理用来改变水印的不透明性。
            //通过应用包含提供了坐标的RGBA空间的5x5矩阵来做这个。
            //通过设定第三行、第三列为0.3f我们就达到了一个不透明的水平。结果是水印会轻微地显示在图象底下一些。
            imageAttributes.SetRemapTable(remapTable,
                                          ColorAdjustType.Bitmap);
            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new
                                        ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix,
                                           ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);
            //随着两个颜色处理加入到imageAttributes 对象,我们现在就能在照片右手边上绘制水印了。
            //我们会偏离10像素到底部,10像素到左边。
            int markWidth;
            int markHeight;

            //mark比原来的图宽
            if (phWidth <= wmWidth)
            {
                markWidth  = phWidth - 10;
                markHeight = (markWidth * wmHeight) / wmWidth;
            }
            else if (phHeight <= wmHeight)
            {
                markHeight = phHeight - 10;
                markWidth  = (markHeight * wmWidth) / wmHeight;
            }
            else
            {
                markWidth  = wmWidth;
                markHeight = wmHeight;
            }
            int xPosOfWm = ((phWidth - markWidth) - 10);
            int yPosOfWm = 10;

            grWatermark.DrawImage(imgWatermark,
                                  new Rectangle(xPosOfWm, yPosOfWm, markWidth,
                                                markHeight),
                                  0,
                                  0,
                                  wmWidth,
                                  wmHeight,
                                  GraphicsUnit.Pixel,
                                  imageAttributes);
            //最后的步骤将是使用新的Bitmap取代原来的Image。 销毁两个Graphic对象,然后把Image 保存到文件系统。
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();
            imgPhoto.Save(rDstImgPath, ImageFormat.Png);
            imgPhoto.Dispose();
            imgWatermark.Dispose();
        }
        /// <summary>
        /// Raises the RenderItemImage event.
        /// </summary>
        /// <param name="e">An ToolStripItemImageRenderEventArgs containing the event data.</param>
        protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
        {
            // Is this a min/restore/close pendant button
            if (e.Item.GetType().ToString() == "System.Windows.Forms.MdiControlStrip+ControlBoxMenuItem")
            {
                // Get access to the owning form of the mdi control strip
                Form f = e.ToolStrip.Parent.TopLevelControl as Form;
                if (f != null)
                {
                    // Get the mdi control strip instance
                    PropertyInfo piMCS = typeof(Form).GetProperty("MdiControlStrip", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                    if (piMCS != null)
                    {
                        object mcs = piMCS.GetValue(f, null);
                        if (mcs != null)
                        {
                            // Get the min/restore/close internal menu items
                            Type      mcsType = mcs.GetType();
                            FieldInfo fiM     = mcsType.GetField("minimize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiR     = mcsType.GetField("restore", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiC     = mcsType.GetField("close", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            if ((fiM != null) && (fiR != null) && (fiC != null))
                            {
                                ToolStripMenuItem m = fiM.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem r = fiR.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem c = fiC.GetValue(mcs) as ToolStripMenuItem;
                                if ((m != null) && (r != null) && (c != null))
                                {
                                    // Compare the event provided image with the internal cached ones to discover the type of pendant button we are drawing
                                    PaletteButtonSpecStyle specStyle = PaletteButtonSpecStyle.Generic;
                                    if (m.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantMin;
                                    }
                                    else if (r.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantRestore;
                                    }
                                    else if (c.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantClose;
                                    }

                                    // A match, means we have a known pendant button
                                    if (specStyle != PaletteButtonSpecStyle.Generic)
                                    {
                                        // Grab the palette pendant details needed for drawing
                                        Image paletteImage     = KCT.Palette.GetButtonSpecImage(specStyle, PaletteState.Normal);
                                        Color transparentColor = KCT.Palette.GetButtonSpecImageTransparentColor(specStyle);

                                        // Finally we actually have an image to draw!
                                        if (paletteImage != null)
                                        {
                                            using (ImageAttributes attribs = new ImageAttributes())
                                            {
                                                // Setup mapping to make required color transparent
                                                ColorMap remap = new ColorMap();
                                                remap.OldColor = transparentColor;
                                                remap.NewColor = Color.Transparent;
                                                attribs.SetRemapTable(new ColorMap[] { remap });

                                                // Phew, actually draw the darn thing
                                                e.Graphics.DrawImage(paletteImage, e.ImageRectangle,
                                                                     0, 0, e.Image.Width, e.Image.Height,
                                                                     GraphicsUnit.Pixel, attribs);

                                                // Do not let base class draw system defined image
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            base.OnRenderItemImage(e);
        }
        /// <summary>
        /// 生成水印图
        /// </summary>
        /// <param name="originalImagePath">源图绝对路径</param>
        /// <param name="watermarkType">水印类型:文字水印,图片水印</param>
        /// <param name="watermarkImage">水印图绝对路径</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="fontSize">字体大小</param>
        /// <param name="fontColor">字体颜色</param>
        /// <param name="fontFamily">字体</param>
        /// <param name="watermarkPosition">水印位置</param>
        /// <param name="alpha">透明度</param>
        /// <param name="watermarkFilePath">水印图片保存路径,不填写则自动创建</param>
        /// <returns></returns>
        public static string AddWatermark(string originalImagePath, string watermarkType, string watermarkImage
                                          , string watermarkText, int fontSize, string fontColor, string fontFamily, WatermarkPosition watermarkPosition, float alpha, string watermarkFilePath = "")
        {
            Image img = Image.FromFile(originalImagePath);
            // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。
            Bitmap bmPhoto = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppRgb);

            // 设定分辨率
            bmPhoto.SetResolution(72, 72);
            System.Drawing.Graphics g = Graphics.FromImage(bmPhoto);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //消除锯齿
            g.SmoothingMode = SmoothingMode.AntiAlias;
            //g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

            //文件扩展名
            string strExt = Path.GetExtension(originalImagePath);

            //生成的水印图文件名
            if (watermarkFilePath.IsNullOrEmpty())
            {
                watermarkFilePath = originalImagePath.Replace(strExt, "_watermark" + strExt);
            }

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,  0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,  0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,  0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, alpha, 0.0f },                                    //水印透明度
                new float[] { 0.0f, 0.0f, 0.0f,  0.0f, 1.0f }
            };
            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //水印所在位置
            int xpos = 0;
            int ypos = 0;

            int intWatermarkWidth  = 0;
            int intWatermarkHeight = 0;

            Image watermark = null;

            if (watermarkType.Equals("图片水印") && File.Exists(watermarkImage))
            {
                //加载水印图片
                watermark          = new Bitmap(watermarkImage);
                intWatermarkWidth  = watermark.Width;
                intWatermarkHeight = watermark.Height;
            }
            else if (watermarkType.Equals("文字水印") && watermarkText.Trim().Length > 0)
            {
                SizeF size = g.MeasureString(watermarkText, new Font(new FontFamily(fontFamily), fontSize));
                intWatermarkWidth  = (int)size.Width;
                intWatermarkHeight = (int)size.Height;
            }

            switch (watermarkPosition)
            {
            case WatermarkPosition.TopLeft:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case WatermarkPosition.TopCenter:
                xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case WatermarkPosition.TopRight:
                xpos = (int)((img.Width * (float).99) - (intWatermarkWidth));
                ypos = (int)(img.Height * (float).01);
                break;

            case WatermarkPosition.MiddleLeft:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2));
                break;

            case WatermarkPosition.MiddleCenter:
                xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2));
                ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2));
                break;

            case WatermarkPosition.MiddleRight:
                xpos = (int)((img.Width * (float).99) - (intWatermarkWidth));
                ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2));
                break;

            case WatermarkPosition.BottomLeft:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - intWatermarkHeight);
                break;

            case WatermarkPosition.BottomCenter:
                xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2));
                ypos = (int)((img.Height * (float).99) - intWatermarkHeight);
                break;

            case WatermarkPosition.BottomRight:
                xpos = (int)((img.Width * (float).99) - (intWatermarkWidth));
                ypos = (int)((img.Height * (float).99) - intWatermarkHeight);
                break;
            }

            if (watermark != null) //在原图上画图片水印
            {
                g.DrawImage(watermark, new Rectangle(xpos, ypos, intWatermarkWidth, intWatermarkHeight), 0, 0, intWatermarkWidth, intWatermarkHeight, GraphicsUnit.Pixel, imageAttributes);
            }
            else
            {
                //在原图上画文本水印
                Font       font     = new Font(fontFamily, fontSize);                       //文字字体
                Color      fColor   = ColorTranslator.FromHtml(fontColor);
                Color      txtColor = Color.FromArgb(Convert.ToInt32(alpha * 255), fColor); //文字颜色
                SolidBrush brush    = new SolidBrush(txtColor);
                g.DrawString(watermarkText, font, brush, xpos, ypos);
            }

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            qualityParam[0] = 80; //图片质量

            EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                bmPhoto.Save(watermarkFilePath, ici, encoderParams);
            }
            else
            {
                bmPhoto.Save(watermarkFilePath);
            }

            g.Dispose();
            img.Dispose();
            if (watermark != null)
            {
                watermark.Dispose();
            }
            imageAttributes.Dispose();

            return(watermarkFilePath);
        }
示例#7
0
	public static void Main(string[] args)
	{	
		Graphics.DrawImageAbort imageCallback;
		Bitmap outbmp = new Bitmap (600, 600);				
		Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver32bits.bmp");
		Graphics dc = Graphics.FromImage (outbmp);        
		SolidBrush br = new SolidBrush(Color.White);
		Bitmap img = bmp.Clone (new Rectangle (0,0, 60,60) , PixelFormat.Format32bppArgb);									
		
		ImageAttributes imageAttr = new ImageAttributes();
		
		Bitmap	bmpred = new Bitmap (100,100, PixelFormat.Format32bppArgb);		
		Graphics gr = Graphics.FromImage (bmpred);		
		
		/* Sample drawing*/
		Pen cyan = new Pen(Color.Cyan, 0);
		Pen green = new Pen(Color.Green, 0);
		Pen pink = new Pen(Color.Pink, 0);			
		Pen blue = new Pen(Color.Blue, 0);			
		gr.DrawLine(cyan, 10.0F, 10.0F, 90.0F, 90.0F);
		gr.DrawLine(pink, 10.0F, 30.0F, 90.0F, 30.0F);
		gr.DrawLine(green, 10.0F, 50.0F, 90.0F, 50.0F);
		gr.DrawRectangle (blue, 10.0F, 10.0F, 80.0F, 80.0F);				
		
		/* Draw image without any imageattributes*/		
		dc.DrawImage (bmpred, 0,0);				
		dc.DrawString ("Sample drawing", new Font ("Arial", 8), br,  10, 100);				
		
		/* Remmaping colours */
		ColorMap[] clr = new ColorMap[1];	
		clr[0] = new ColorMap(); 
		clr[0].OldColor = Color.Blue;
		clr[0].NewColor = Color.Yellow;	
		
		imageAttr.SetRemapTable (clr, ColorAdjustType.Bitmap);					
		dc.DrawImage (bmpred, new Rectangle (100, 0, 100,100), 0,0, 100,100, GraphicsUnit.Pixel, imageAttr);			
		dc.DrawString ("Remapping colors", new Font ("Arial", 8), br,  110, 100);				
		
		/* Gamma correction on*/
		imageAttr = new ImageAttributes();
		imageAttr.SetGamma (2);		
		dc.DrawImage (bmpred, new Rectangle (200, 0, 100,100), 0,0, 
			100,100, GraphicsUnit.Pixel, imageAttr);
			
		dc.DrawString ("Gamma corrected", new Font ("Arial", 8), br,  210, 100);				
		
		/* WrapMode: TitleX */
		imageAttr = new ImageAttributes();	
		imageAttr.SetWrapMode (WrapMode.TileFlipX);	
		
		dc.DrawImage (bmpred, new Rectangle (0, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);					
			
		dc.DrawString ("WrapMode.TileFlipX", new Font ("Arial", 8), br,  10, 320);								
			
		/* WrapMode: TitleY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipY);	
		
		dc.DrawImage (bmpred, new Rectangle (200, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipY", new Font ("Arial", 8), br,  210, 320);											
			
		/* WrapMode: TitleXY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipXY);	
		
		dc.DrawImage (bmpred, new Rectangle (400, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipXY", new Font ("Arial", 8), br,  410, 320);														
		
		outbmp.Save("imageattributes.bmp", ImageFormat.Bmp);				
		
	}
示例#8
0
        private void DrawArrowForm_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.FillRectangle(Brushes.SkyBlue, ClientRectangle);

            var arrowBitmap = Properties.Resources.arrow;

            e.Graphics.DrawImage(arrowBitmap,
                                 new Rectangle
            {
                X      = 10,
                Y      = 10,
                Width  = 75,
                Height = 100
            }
                                 );

            var colors = new Color[]
            {
                Color.White,
                Color.Red,
                Color.Orange,
                Color.Yellow,
                Color.Green,
                Color.Cyan,
                Color.Blue,
                Color.Purple,
                Color.GreenYellow,
                Color.Goldenrod,
                Color.HotPink,
                Color.IndianRed,
            };

            var rectangle = new Rectangle
            {
                X      = 10,
                Y      = 10,
                Width  = 75,
                Height = 100
            };

            var xOffset = 50;

            var colorMap = new ColorMap[1];

            colorMap[0] = new ColorMap();

            var imageAttribute = new ImageAttributes();

            foreach (var color in colors)
            {
                colorMap[0].OldColor = Color.Black;
                colorMap[0].NewColor = color;

                imageAttribute.SetRemapTable(colorMap);

                rectangle.X += xOffset;

                e.Graphics.DrawImage(arrowBitmap,
                                     rectangle, 0, 0, arrowBitmap.Width, arrowBitmap.Height,
                                     GraphicsUnit.Pixel, imageAttribute
                                     );
            }
        }
        /// <summary>
        /// Executes this filter on the input image and returns the image with the WaterMark
        /// </summary>
        /// <param name="rawImage">input image</param>
        /// <returns>transformed image</returns>
        /// <example>
        /// <code>
        /// Image transformed;
        /// ImageWatermarkFilter imageWaterMark = new ImageWatermarkFilter();
        /// imageWaterMark.Valign = ImageWatermarkFilter.VAlign.Right;
        /// imageWaterMark.Halign = ImageWatermarkFilter.HAlign.Bottom;
        /// imageWaterMark.WaterMarkImage = Image.FromFile("Images/pacman.gif");
        /// transformed = imageWaterMark.ExecuteFilter(myImg);
        /// </code>
        /// </example>
        public override Image ExecuteFilter(Image rawImage)
        {
            _height = rawImage.Height;
            _width  = rawImage.Width;
            Bitmap bmWatermark = new Bitmap(rawImage);

            bmWatermark.SetResolution(rawImage.HorizontalResolution, rawImage.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color
            //manipulations by defineing a ImageAttributes object and
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = _transparentColor;
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the
            //watermark.  This is done by applying a 5x5 matrix that contains the
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
            //to 0.3f we achive a level of opacity
            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,   0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,   0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,   0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, _alpha, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,   0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);

            //For this example we will place the watermark in the upper right
            //hand corner of the photograph. offset down 10 pixels and to the
            //left 10 pixles


            float xPosOfWm;// = ((rawImage.Width - _waterMarkImage.Width) - 2);
            float yPosOfWm;

            CalcDrawPosition((int)_waterMarkImage.Width, (int)_waterMarkImage.Height, 0, out yPosOfWm, out xPosOfWm);

            grWatermark.DrawImage(_waterMarkImage,
                                  new Rectangle((int)xPosOfWm, (int)yPosOfWm, _waterMarkImage.Width, _waterMarkImage.Height), //Set the detination Position
                                  0,                                                                                          // x-coordinate of the portion of the source image to draw.
                                  0,                                                                                          // y-coordinate of the portion of the source image to draw.
                                  _waterMarkImage.Width,                                                                      // Watermark Width
                                  _waterMarkImage.Height,                                                                     // Watermark Height
                                  GraphicsUnit.Pixel,                                                                         // Unit of measurment
                                  imageAttributes);                                                                           //ImageAttributes Object

            //Replace the original photgraphs bitmap with the new Bitmap
            //imgPhoto = bmWatermark;
            //grWatermark.Dispose();

            //save new image to file system.
            return(bmWatermark); // bmPhoto;
        }
示例#10
0
        public void MarkImage(string srcPic, string dstPic)
        {
            m_ImgPhoto = Image.FromFile(srcPic);

            int phWidth  = m_ImgPhoto.Width;
            int phHeight = m_ImgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(m_ImgPhoto.HorizontalResolution, m_ImgPhoto.VerticalResolution);

            //load the Bitmap into a Graphics object
            Graphics grPhoto = Graphics.FromImage(bmPhoto);


            //------------------------------------------------------------
            //Step #1 - Insert m_Copyright message
            //------------------------------------------------------------

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                m_ImgPhoto,                             // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw.
                0,                                      // y-coordinate of the portion of the source image to draw.
                phWidth,                                // Width of the portion of the source image to draw.
                phHeight,                               // Height of the portion of the source image to draw.
                GraphicsUnit.Pixel);                    // Units of measure

            //-------------------------------------------------------
            //to maximize the size of the m_Copyright message we will
            //test multiple Font sizes to determine the largest posible
            //font we can use for the width of the Photograph
            //define an array of point sizes you would like to consider as possiblities
            //-------------------------------------------------------
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            Font  crFont = null;
            SizeF crSize = new SizeF();

            //Loop through the defined sizes checking the length of the m_Copyright string
            //If its length in pixles is less then the image width choose this Font size.
            for (int i = 0; i < 7; i++)
            {
                //set a Font object to our font object, size we will decide...
                crFont = new Font(m_CopyrightFont.Name, sizes[i], m_CopyrightFont.Style);

                //Measure the m_Copyright string in this Font
                crSize = grPhoto.MeasureString(m_Copyright, crFont);

                if ((ushort)crSize.Width < (ushort)phWidth)
                {
                    break;
                }
            }

            int   yPixlesFromBottom = 0;
            float yPosFromBottom    = 0;
            float xCenterOfImg      = 0;

            switch (m_CopyrightPosition)
            {
            case ContentAlignment.BottomCenter:
                //Since all photographs will have varying heights, determine a
                //position 5% from the bottom of the image
                yPixlesFromBottom = (int)(phHeight * .05);

                //Now that we have a point size use the m_Copyrights string height
                //to determine a y-coordinate to draw the string of the photograph
                yPosFromBottom = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));

                //Determine its x-coordinate by calculating the center of the width of the image
                xCenterOfImg = (phWidth / 2);
                break;

            case ContentAlignment.BottomLeft:
                yPixlesFromBottom = (int)(phHeight * .05);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (crSize.Width / 2) + 10;
                break;

            case ContentAlignment.BottomRight:
                yPixlesFromBottom = (int)(phHeight * .05);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (phWidth - (crSize.Width / 2)) - 10;
                break;

            case ContentAlignment.MiddleCenter:
                yPixlesFromBottom = (int)(phHeight * .50);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (phWidth / 2);
                break;

            case ContentAlignment.MiddleLeft:
                yPixlesFromBottom = (int)(phHeight * .50);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (crSize.Width / 2) + 10;
                break;

            case ContentAlignment.MiddleRight:
                yPixlesFromBottom = (int)(phHeight * .50);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (phWidth - (crSize.Width / 2)) - 10;
                break;

            case ContentAlignment.TopCenter:
                yPixlesFromBottom = (int)(phHeight * .95);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (phWidth / 2);
                break;

            case ContentAlignment.TopLeft:
                yPixlesFromBottom = (int)(phHeight * .95);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (crSize.Width / 2) + 10;
                break;

            case ContentAlignment.TopRight:
                yPixlesFromBottom = (int)(phHeight * .95);
                yPosFromBottom    = ((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
                xCenterOfImg      = (phWidth - (crSize.Width / 2)) - 10;
                break;
            }

            //Define the text layout by setting the text alignment to centered
            StringFormat StrFormat = new StringFormat();

            StrFormat.Alignment = StringAlignment.Center;

            //define a Brush which is semi trasparent black (Alpha set to 153)
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));

            //Draw the m_Copyright string
            grPhoto.DrawString(m_Copyright,                                      //string of text
                               crFont,                                           //font
                               semiTransBrush2,                                  //Brush
                               new PointF(xCenterOfImg + 1, yPosFromBottom + 1), //Position
                               StrFormat);

            //define a Brush which is semi trasparent white (Alpha set to 153)
            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            //Draw the m_Copyright string a second time to create a shadow effect
            //Make sure to move this text 1 pixel to the right and down 1 pixel
            grPhoto.DrawString(m_Copyright,                              //string of text
                               crFont,                                   //font
                               semiTransBrush,                           //Brush
                               new PointF(xCenterOfImg, yPosFromBottom), //Position
                               StrFormat);                               //Text alignment



            //------------------------------------------------------------
            //Step #2 - Insert Watermark image
            //------------------------------------------------------------

            //Create a Bitmap based on the previously modified photograph Bitmap
            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(m_ImgPhoto.HorizontalResolution, m_ImgPhoto.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color
            //manipulations by defineing a ImageAttributes object and
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the
            //watermark.  This is done by applying a 5x5 matrix that contains the
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
            //to 0.3f we achive a level of opacity
            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);


            //create a image object containing the watermark
            if (m_ImgWatermark != null)
            {
                int wmWidth  = m_ImgWatermark.Width;
                int wmHeight = m_ImgWatermark.Height;

                //For this example we will place the watermark in the upper right
                //hand corner of the photograph. offset down 10 pixels and to the
                //left 10 pixles

                int xPosOfWm = 0;
                int yPosOfWm = 0;

                switch (m_ImagePosition)
                {
                case ContentAlignment.BottomCenter:
                    xPosOfWm = (phWidth / 2) - (wmWidth / 2);
                    yPosOfWm = (phHeight - wmHeight) - 10;
                    break;

                case ContentAlignment.BottomLeft:
                    xPosOfWm = 10;
                    yPosOfWm = (phHeight - wmHeight) - 10;
                    break;

                case ContentAlignment.BottomRight:
                    xPosOfWm = ((phWidth - wmWidth) - 10);
                    yPosOfWm = (phHeight - wmHeight) - 10;
                    break;

                case ContentAlignment.MiddleCenter:
                    xPosOfWm = (phWidth / 2) - (wmWidth / 2);
                    yPosOfWm = (phHeight / 2) - (wmHeight / 2);
                    break;

                case ContentAlignment.MiddleLeft:
                    xPosOfWm = 10;
                    yPosOfWm = (phHeight / 2) - (wmHeight / 2);
                    break;

                case ContentAlignment.MiddleRight:
                    xPosOfWm = ((phWidth - wmWidth) - 10);
                    yPosOfWm = (phHeight / 2) - (wmHeight / 2);
                    break;

                case ContentAlignment.TopCenter:
                    xPosOfWm = (phWidth / 2) - (wmWidth / 2);
                    yPosOfWm = 10;
                    break;

                case ContentAlignment.TopLeft:
                    xPosOfWm = 10;
                    yPosOfWm = 10;
                    break;

                case ContentAlignment.TopRight:
                    //For this example we will place the watermark in the upper right
                    //hand corner of the photograph. offset down 10 pixels and to the
                    //left 10 pixles

                    xPosOfWm = ((phWidth - wmWidth) - 10);
                    yPosOfWm = 10;
                    break;
                }

                grWatermark.DrawImage(m_ImgWatermark,
                                      new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), //Set the detination Position
                                      0,                                                    // x-coordinate of the portion of the source image to draw.
                                      0,                                                    // y-coordinate of the portion of the source image to draw.
                                      wmWidth,                                              // Watermark Width
                                      wmHeight,                                             // Watermark Height
                                      GraphicsUnit.Pixel,                                   // Unit of measurment
                                      imageAttributes);                                     //ImageAttributes Object
            }
            //Replace the original photgraphs bitmap with the new Bitmap
            m_ImgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //check file existence

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

            //save new image to file system.
            m_ImgPhoto.Save(dstPic, GetImageFormat(srcPic));
            m_ImgPhoto.Dispose();
            //if (m_ImgWatermark != null) m_ImgWatermark.Dispose();
        }
示例#11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceImage"></param>
        /// <param name="waterImage"></param>
        /// <param name="dissolve"></param>
        /// <param name="imagePosition"></param>
        /// <param name="distanceX"></param>
        /// <param name="distanceY"></param>
        /// <param name="watermarkScale"></param>
        /// <param name="watermarkScaleType"></param>
        /// <returns></returns>
        private Image SetWaterMarkByImg(Image sourceImage, Image waterImage, float dissolve = 100, ImagePosition imagePosition = ImagePosition.RigthBottom, int distanceX = 10, int distanceY = 10, int watermarkScale = 0, int watermarkScaleType = 0)
        {
            Image imgPhoto = sourceImage;
            int   sWidth   = imgPhoto.Width;
            int   sHeight  = imgPhoto.Height;

            using (Bitmap bmPhoto = new Bitmap(sWidth, sHeight, PixelFormat.Format24bppRgb))
            {
                bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                Graphics grPhoto      = Graphics.FromImage(bmPhoto);
                Image    imgWatermark = new Bitmap(waterImage);
                int      wmWidth      = imgWatermark.Width;
                int      wmHeight     = imgWatermark.Height;
                grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
                grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, sWidth, sHeight), 0, 0, sWidth, sHeight, GraphicsUnit.Pixel);
                Bitmap bmWatermark = new Bitmap(bmPhoto);
                bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                Graphics        grWatermark     = Graphics.FromImage(bmWatermark);
                ImageAttributes imageAttributes = new ImageAttributes();
                ColorMap        colorMap        = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };
                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                float[][] colorMatrixElements =
                {
                    new float[] { 1.0f, 0.0f, 0.0f,                    0.0f, 0.0f }, // red红色
                    new float[] { 0.0f, 1.0f, 0.0f,                    0.0f, 0.0f }, //green绿色
                    new float[] { 0.0f, 0.0f, 1.0f,                    0.0f, 0.0f }, //blue蓝色
                    new float[] { 0.0f, 0.0f, 0.0f, (float)(dissolve / 100), 0.0f }, //透明度
                    new float[] { 0.0f, 0.0f, 0.0f,                    0.0f, 1.0f }
                };
                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                               ColorAdjustType.Bitmap);
                int xPosOfWm;
                int yPosOfWm;
                switch (imagePosition)
                {
                case ImagePosition.BottomMiddle:
                    xPosOfWm = ((sWidth - wmWidth) / 2) - distanceX;
                    yPosOfWm = sHeight - wmHeight - distanceY;
                    break;

                case ImagePosition.Center:
                    xPosOfWm = (sWidth - wmWidth) / 2;
                    yPosOfWm = (sHeight - wmHeight) / 2;
                    break;

                case ImagePosition.LeftBottom:
                    xPosOfWm = distanceX;
                    yPosOfWm = sHeight - wmHeight - distanceY;
                    break;

                case ImagePosition.LeftTop:
                    xPosOfWm = distanceX;
                    yPosOfWm = distanceY;
                    break;

                case ImagePosition.RightTop:
                    xPosOfWm = sWidth - wmWidth - distanceX;
                    yPosOfWm = distanceY;
                    break;

                case ImagePosition.RigthBottom:
                    xPosOfWm = sWidth - wmWidth - distanceX;
                    yPosOfWm = sHeight - wmHeight - distanceY;
                    break;

                case ImagePosition.TopMiddle:
                    xPosOfWm = (sWidth - wmWidth) / 2;
                    yPosOfWm = distanceY;
                    break;

                default:
                    xPosOfWm = distanceX;
                    yPosOfWm = sHeight - wmHeight - distanceY;
                    break;
                }

                grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), 0, 0, wmWidth, wmHeight, GraphicsUnit.Pixel, imageAttributes);

                imgPhoto = bmWatermark;
                grPhoto.Dispose();
                grWatermark.Dispose();

                return(imgPhoto);
            }
        }
示例#12
0
    /// <summary>
    /// 添加图片水印
    /// </summary>
    /// <param name="oldFilePath">原始图片路径</param>
    /// <param name="newFilePath">将要添加水印图片路径</param>
    /// <param name="waterPosition">水印位置</param>
    /// <param name="waterImagePath">水印图片路径</param>
    /// <param name="transparency">透明度</param>
    /// <param name="quality">质量</param>
    public static void CreateWaterImage(string oldFilePath, string newFilePath, int waterPosition, string waterImagePath, int watermarkTransparency, int quality)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(oldFilePath);

        Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);

        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);

        g.DrawImage(image, 0, 0, image.Width, image.Height);

        //设置透明度
        System.Drawing.Image watermark = new Bitmap(waterImagePath);
        ImageAttributes imageAttributes = new ImageAttributes();
        ColorMap colorMap = new ColorMap();
        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
        ColorMap[] remapTable = { colorMap };
        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        float transparency = 0.5F;
        if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
        {
            transparency = (watermarkTransparency / 10.0F);
        }

        float[][] colorMatrixElements = {
                                                    new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                                    new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f}, //注意:倒数第二处为0.0f为完全透明,1.0f为完全不透明
                                                    new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                                };
        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        int _width = image.Width;
        int _height = image.Height;
        int xpos = 0;
        int ypos = 0;
        int WatermarkWidth = 0;
        int WatermarkHeight = 0;
        double bl = 1d;
        //计算水印图片的比率
        //取背景的1/4宽度来比较
        if ((_width > watermark.Width * 2) && (_height > watermark.Height * 2))
        {
            bl = 1;
        }
        else if ((_width > watermark.Width * 2) && (_height < watermark.Height * 2))
        {
            bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);

        }
        else if ((_width < watermark.Width * 2) && (_height > watermark.Height * 2))
        {
            bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
        }
        else
        {
            if ((_width * watermark.Height) > (_height * watermark.Width))
            {
                bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);
            }
            else
            {
                bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
            }
        }
        WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
        WatermarkHeight = Convert.ToInt32(watermark.Height * bl);
        switch (waterPosition)
        {
            case 3:
                xpos = _width - WatermarkWidth - 10;
                ypos = 10;
                break;
            case 2:
                xpos = 10;
                ypos = _height - WatermarkHeight - 10;
                break;
            case 5:
                xpos = _width / 2 - WatermarkWidth / 2;
                ypos = _height / 2 - WatermarkHeight / 2;
                break;
            case 1:
                xpos = 10;
                ypos = 10;
                break;
            case 4:
            default:
                xpos = _width - WatermarkWidth - 10;
                ypos = _height - WatermarkHeight - 10;
                break;
        }
        g.DrawImage(watermark, new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
        try
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];

            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                bmp.Save(newFilePath, ici, encoderParams);
            }
            else
            {
                bmp.Save(newFilePath);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            watermark.Dispose();
            imageAttributes.Dispose();
            image.Dispose();
            bmp.Dispose();
        }
    }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="oldFile"></param>
        /// <param name="newFile"></param>
        public static void ImageMark(string oldFile, string newFile)
        {
            string ImgMarkPath = System.Configuration.ConfigurationManager.AppSettings["ImgMark"];

            if (string.IsNullOrEmpty(ImgMarkPath))
            {
                throw new Exception("image mark path is null");
            }

            ImgMarkPath = System.Web.HttpContext.Current.Server.MapPath(ImgMarkPath);
            if (!File.Exists(ImgMarkPath))
            {
                throw new Exception("Can not find the image mark with path:" + ImgMarkPath);
            }


            Image imgWatermark = new Bitmap(ImgMarkPath);
            int   wmWidth      = imgWatermark.Width;
            int   wmHeight     = imgWatermark.Height;

            //create a image object containing the photograph to watermark
            Image imgPhoto = Image.FromFile(oldFile);
            int   phWidth  = imgPhoto.Width;
            int   phHeight = imgPhoto.Height;

            //create a Bitmap the Size of the original photograph
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //load the Bitmap into a Graphics object
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //Set the rendering quality for this Graphics object
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //Draws the photo Image object at original size to the graphics object.
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw.
                0,                                      // y-coordinate of the portion of the source image to draw.
                phWidth,                                // Width of the portion of the source image to draw.
                phHeight,                               // Height of the portion of the source image to draw.
                GraphicsUnit.Pixel);                    // Units of measure

            //Create a Bitmap based on the previously modified photograph Bitmap
            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color
            //manipulations by defineing a ImageAttributes object and
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the
            //watermark.  This is done by applying a 5x5 matrix that contains the
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
            //to 0.3f we achive a level of opacity
            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);

            //For this example we will place the watermark in the upper right
            //hand corner of the photograph. offset down 10 pixels and to the
            //left 10 pixles

            int xPosOfWm = Convert.ToInt32(phWidth - (phWidth / 2));
            int yPosOfWm = Convert.ToInt32(phHeight - (phHeight / 4));

            grWatermark.DrawImage(imgWatermark,
                                  new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), //Set the detination Position
                                  0,                                                    // x-coordinate of the portion of the source image to draw.
                                  0,                                                    // y-coordinate of the portion of the source image to draw.
                                  wmWidth,                                              // Watermark Width
                                  wmHeight,                                             // Watermark Height
                                  GraphicsUnit.Pixel,                                   // Unit of measurment
                                  imageAttributes);                                     //ImageAttributes Object

            //Replace the original photgraphs bitmap with the new Bitmap
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //save new image to file system.
            imgPhoto.Save(newFile, imgPhoto.RawFormat);
            imgPhoto.Dispose();
            imgWatermark.Dispose();
        }
示例#14
0
        /// <summary>
        /// 图片按等比缩放生成缩略图
        /// </summary>
        /// <param name="originImage">原图对象</param>
        /// <param name="saveDirectory">缩略图保存目录</param>
        /// <param name="saveFileName">缩略图保存名称</param>
        /// <param name="targetWidth">指定的最大宽度</param>
        /// <param name="targetHeight">指定的最大高度</param>
        /// <param name="watermarkText">水印文字(为空表示不使用水印)</param>
        /// <param name="watermarkImage">水印图片路径(为空表示不使用水印)</param>
        public static void ThumbnailsOfIsometricZoom(Image originImage, string saveDirectory, string saveFileName, double targetWidth, double targetHeight, string watermarkText, string watermarkImage)
        {
            // 创建目录
            if (!Directory.Exists(saveDirectory))
            {
                Directory.CreateDirectory(saveDirectory);
            }
            var filePath = Path.Combine(saveDirectory, saveFileName);

            //原图宽高均小于模版,不作处理,直接保存
            if (originImage.Width <= targetWidth && originImage.Height <= targetHeight)
            {
                //文字水印
                if (watermarkText != "")
                {
                    using (Graphics gWater = Graphics.FromImage(originImage))
                    {
                        Font  fontWater  = new Font("黑体", 10);
                        Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }
                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (Image wrImage = Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (originImage.Width >= wrImage.Width && originImage.Height >= wrImage.Height)
                            {
                                using (var gWater = Graphics.FromImage(originImage))
                                {
                                    //透明属性
                                    ImageAttributes imgAttributes = new ImageAttributes();
                                    ColorMap        colorMap      = new ColorMap();
                                    colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                    colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                    ColorMap[] remapTable = { colorMap };
                                    imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
                                    float[][] colorMatrixElements =
                                    {
                                        new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                        new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                        new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                        new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                        new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                    };
                                    ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                    imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                    gWater.DrawImage(wrImage, new Rectangle(originImage.Width - wrImage.Width, originImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                    gWater.Dispose();
                                }
                            }
                            wrImage.Dispose();
                        }
                    }
                }
                //保存
                originImage.Save(filePath, ImageFormat.Jpeg);
            }
            else
            {
                //缩略图宽、高计算
                double newWidth  = originImage.Width;
                double newHeight = originImage.Height;
                //宽大于高或宽等于高(横图或正方)
                if (originImage.Width > originImage.Height || originImage.Width == originImage.Height)
                {
                    //如果宽大于模版
                    if (originImage.Width > targetWidth)
                    {
                        //宽按模版,高按比例缩放
                        newWidth  = targetWidth;
                        newHeight = originImage.Height * (targetWidth / originImage.Width);
                    }
                }
                //高大于宽(竖图)
                else
                {
                    //如果高大于模版
                    if (originImage.Height > targetHeight)
                    {
                        //高按模版,宽按比例缩放
                        newHeight = targetHeight;
                        newWidth  = originImage.Width * (targetHeight / originImage.Height);
                    }
                }
                //生成新图
                using (var newImage = new Bitmap((int)newWidth, (int)newHeight))
                    using (var newG = Graphics.FromImage(newImage))
                    {
                        //设置质量
                        newG.CompositingQuality = CompositingQuality.HighQuality;
                        newG.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        newG.SmoothingMode      = SmoothingMode.HighQuality;
                        //置背景色
                        newG.Clear(Color.White);
                        //画图
                        newG.DrawImage(originImage, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, originImage.Width, originImage.Height), GraphicsUnit.Pixel);
                        //文字水印
                        if (watermarkText != "")
                        {
                            using (Graphics gWater = Graphics.FromImage(newImage))
                            {
                                Font  fontWater  = new Font("宋体", 10);
                                Brush brushWater = new SolidBrush(Color.White);
                                gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                                gWater.Dispose();
                            }
                        }
                        //透明图片水印
                        if (watermarkImage != "")
                        {
                            if (File.Exists(watermarkImage))
                            {
                                //获取水印图片
                                using (Image wrImage = Image.FromFile(watermarkImage))
                                {
                                    //水印绘制条件:原始图片宽高均大于或等于水印图片
                                    if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                                    {
                                        using (var gWater = Graphics.FromImage(newImage))
                                        {
                                            //透明属性
                                            ImageAttributes imgAttributes = new ImageAttributes();
                                            ColorMap        colorMap      = new ColorMap();
                                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                            ColorMap[] remapTable = { colorMap };
                                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
                                            float[][] colorMatrixElements =
                                            {
                                                new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                                new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                                new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                                new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                                new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                            };
                                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                            gWater.Dispose();
                                        }
                                    }
                                    wrImage.Dispose();
                                }
                            }
                        }
                        //保存缩略图
                        newImage.Save(filePath, ImageFormat.Jpeg);
                        //释放资源
                        newG.Dispose();
                        newImage.Dispose();
                        originImage.Dispose();
                    }
            }
        }
示例#15
0
        protected override void OnPaint(PaintEventArgs e)
        {
            RectangleF srcRect = new RectangleF(0, y, this.Width, this.Height);

            float scrollY = this.Height / 2; /*( ( y + this.Height ) / ( img.Height + this.Height ) ) * this.Height;*/

            int widSet      = 8;
            int rightSet    = this.Width - widSet - 4;
            int leftSet     = widSet;
            int guideBarLen = 20;
            int guideBarWid = 1;
            int mainLen     = 3;
            int mainWid     = 3;

            int spectrumAccuracy = 64 * 1;

            float[]     spectrum = new float[spectrumAccuracy];
            FMOD.RESULT result   = soundChannel.getSpectrum(spectrum, spectrumAccuracy, 0, FMOD.DSP_FFT_WINDOW.BLACKMAN);

            float avg = spectrum.Average();

            avg *= 100;

            float[] bassSpec = spectrum.Take(spectrumAccuracy / 8).ToArray();

            float bassAvg = bassSpec.Average();

            bassAvg *= 25;

            Color baseColor = Color.LightBlue;

            int colorRange = 40;
            int rOff       = rnd.Next(-colorRange, colorRange + 1);
            int gOff       = rnd.Next(-colorRange, colorRange + 1);
            int bOff       = rnd.Next(-colorRange, colorRange + 1);

            int newRed   = Math.Min(baseColor.R + rOff, 255);
            int newGreen = Math.Min(baseColor.G + gOff, 255);
            int newBlue  = Math.Min(baseColor.B + bOff, 255);

            baseColor = Color.FromArgb(newRed, newGreen, newBlue);

            Pen basePen = new Pen(baseColor, bassAvg);

            RectangleF scrollRect = new RectangleF(rightSet, scrollY, mainWid, mainLen);
            RectangleF topRect    = new RectangleF(rightSet + ((scrollRect.Width / 2.0f) - (guideBarWid / 2.0f)), scrollY - guideBarLen, guideBarWid, guideBarLen);
            RectangleF bottomRect = new RectangleF(rightSet + ((scrollRect.Width / 2.0f) - (guideBarWid / 2.0f)), scrollY + scrollRect.Height, guideBarWid, guideBarLen);


            RectangleF scrollRect2 = new RectangleF(leftSet, scrollY, mainWid, mainLen);
            RectangleF topRect2    = new RectangleF(leftSet + ((scrollRect.Width / 2.0f) - (guideBarWid / 2.0f)), scrollY - guideBarLen, guideBarWid, guideBarLen);
            RectangleF bottomRect2 = new RectangleF(leftSet + ((scrollRect.Width / 2.0f) - (guideBarWid / 2.0f)), scrollY + scrollRect.Height, guideBarWid, guideBarLen);

            Color textColor = customSpectrum[specValue];

            ColorMap[] map = new ColorMap[1];
            map[0]          = new ColorMap();
            map[0].OldColor = Color.Magenta;
            map[0].NewColor = textColor;

            ImageAttributes attr = new ImageAttributes();

            attr.SetRemapTable(map);

            e.Graphics.DrawImage(img, new Rectangle(0, 0, this.Width, this.Height), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel, attr);

            PointF midRight = new PointF((scrollRect.X + (scrollRect.Width / 2.0f)), (scrollRect.Y + (scrollRect.Height / 2.0f)));

            e.Graphics.FillRectangle(Brushes.White, scrollRect);
            e.Graphics.FillRectangle(Brushes.WhiteSmoke, topRect);
            e.Graphics.FillRectangle(Brushes.WhiteSmoke, bottomRect);


            PointF midLeft = new PointF((scrollRect2.X + (scrollRect2.Width / 2.0f)), (scrollRect2.Y + (scrollRect2.Height / 2.0f)));

            e.Graphics.FillRectangle(Brushes.White, scrollRect2);
            e.Graphics.FillRectangle(Brushes.WhiteSmoke, topRect2);
            e.Graphics.FillRectangle(Brushes.WhiteSmoke, bottomRect2);

            if (avg > 1.4)
            {
                // lightning
                int   subDivs = rnd.Next(2, 10);
                float subWid  = this.Width / ( float )subDivs;
                float range   = 20; // +-30 pixels from the origin

                if (rnd.Next(0, 2) != 0)
                {
                    return;
                }

                lightningPoints.Clear();

                lightningPoints.Add(midLeft);
                for (int i = 1; i < subDivs; i++)
                {
                    float currX = midLeft.X;
                    float currY = midLeft.Y;

                    float yMin = currY - (range * avg);
                    float yMax = currY + (range * avg);

                    float pointY = rnd.Next(( int )yMin, ( int )yMax + 1);

                    float xOffset = rnd.Next(-25, 26);

                    PointF lightPoint = new PointF((subWid * i) + xOffset, pointY);
                    lightningPoints.Add(lightPoint);
                }
                lightningPoints.Add(midRight);

                e.Graphics.DrawLines(basePen, lightningPoints.ToArray());
            }
            else
            {
                if (rnd.Next(0, 3) != 0)
                {
                    return;
                }

                // no connection, lets just spark

                int   numSparks = rnd.Next(1, 4);
                float maxDist   = rnd.Next(20, this.Width / 6);
                int   direction = rnd.Next(-115, 116);

                maxDist *= avg;

                sparks.Clear();

                for (int i = 0; i < numSparks; i++)
                {
                    var spark = new List <PointF>();

                    float origX = midLeft.X;
                    float origY = midLeft.Y;

                    spark.Add(new PointF(origX, origY));

                    origX += maxDist * ( float )Math.Cos(DegreeToRadian(direction));
                    origY += maxDist * ( float )Math.Sin(DegreeToRadian(direction));

                    spark.Add(new PointF(origX, origY));

                    maxDist  = rnd.Next(20, this.Width / 6);
                    maxDist *= avg;

                    direction = rnd.Next(-90, 91);

                    origX += maxDist * ( float )Math.Cos(DegreeToRadian(direction));
                    origY += maxDist * ( float )Math.Sin(DegreeToRadian(direction));

                    spark.Add(new PointF(origX, origY));

                    sparks.Add(spark);
                }

                foreach (var spark in sparks)
                {
                    e.Graphics.DrawLines(basePen, spark.ToArray());
                }


                sparks.Clear();

                for (int i = 0; i < numSparks; i++)
                {
                    var spark = new List <PointF>();

                    float origX = midRight.X;
                    float origY = midRight.Y;

                    spark.Add(new PointF(origX, origY));

                    origX -= maxDist * ( float )Math.Cos(DegreeToRadian(direction));
                    origY -= maxDist * ( float )Math.Sin(DegreeToRadian(direction));

                    spark.Add(new PointF(origX, origY));

                    maxDist  = rnd.Next(20, this.Width / 6);
                    maxDist *= avg;

                    direction = rnd.Next(-90, 91);

                    origX -= maxDist * ( float )Math.Cos(DegreeToRadian(direction));
                    origY -= maxDist * ( float )Math.Sin(DegreeToRadian(direction));

                    spark.Add(new PointF(origX, origY));

                    sparks.Add(spark);
                }

                foreach (var spark in sparks)
                {
                    e.Graphics.DrawLines(basePen, spark.ToArray());
                }
            }
        }
            private void Captions_Paint(object sender, PaintEventArgs e)
            {
                Rectangle rct = e.ClipRectangle;

                rct.Inflate(-8, -8);
                rct.Height = 23;
                rct.Width -= 1;

                // Draw Border Lines
                using (Pen captionBorderPen = new Pen(contextInstance.BorderColor))
                    e.Graphics.DrawRectangle(captionBorderPen, rct);

                // Create two new empty image for manipulations. If you use this constructor, you get a new Bitmap object that represents a bitmap in memory with a PixelFormat of Format32bppARGB.
                using (Bitmap overlay = new Bitmap(rct.Width + 1, rct.Height + 1),
                       overlay2 = new Bitmap(rct.Width + 1, rct.Height + 1))
                {
                    // Make an associated Graphics object.
                    using (Graphics gr = Graphics.FromImage(overlay), gr2 = Graphics.FromImage(overlay2))
                    {
                        gr.SmoothingMode = SmoothingMode.HighQuality;

                        // Fill Active Caption.
                        using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, overlay.Width, overlay.Height),
                                                                                   contextInstance.GradientCaption.ActiveCaptionColorStart, contextInstance.GradientCaption.ActiveCaptionColorEnd, contextInstance.GradientCaption.CaptionGradientStyle))
                        {
                            Blend bl = new Blend(2);
                            bl.Factors   = new float[] { 0.1F, 1.0F };
                            bl.Positions = new float[] { 0.0F, 1.0F };
                            brush.Blend  = bl;
                            gr.FillRectangle(brush, 0, 0, overlay.Width, overlay.Height);
                        }

                        gr2.SmoothingMode = SmoothingMode.HighQuality;

                        // Fill Inactive Caption.
                        using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, overlay2.Width, overlay2.Height),
                                                                                   contextInstance.GradientCaption.InactiveCaptionColorStart, contextInstance.GradientCaption.InactiveCaptionColorEnd, contextInstance.GradientCaption.CaptionGradientStyle))
                        {
                            Blend bl = new Blend(2);
                            bl.Factors   = new float[] { 0.1F, 1.0F };
                            bl.Positions = new float[] { 0.0F, 1.0F };
                            brush.Blend  = bl;
                            gr2.FillRectangle(brush, 0, 0, overlay2.Width, overlay2.Height);
                        }
                    }

                    /* Create a new color matrix,
                     * The value prgAlpha in row 4, column 4 specifies the alpha value */
                    float[][] jaggedMatrix = new float[][]
                    {
                        // Red component   [from 0.0 to 1.0 increase red color component.]
                        new float[] { (byte)nmrRed.Value / 255f, 0.0f, 0.0f, 0.0f, 0.0f },
                        // Green component [from 0.0 to 1.0 increase green color component.]
                        new float[] { 0.0f, (byte)nmrGreen.Value / 255f, 0.0f, 0.0f, 0.0f },
                        // Blue component  [from 0.0 to 1.0 increase blue color component.]
                        new float[] { 0.0f, 0.0f, (byte)nmrBlue.Value / 255f, 0.0f, 0.0f },
                        // Alpha component [from 1.0 to 0.0 increase transparency bitmap.]
                        new float[] { 0.0f, 0.0f, 0.0f, (byte)nmrAlpha.Value / 255f, 0.0f },
                        // White component [0.0: goes to Original color, 1.0: goes to white for all color component(Red, Green, Blue.)]
                        new float[] { 0.2f, 0.2f, 0.2f, 0.0f, 1.0f }
                    };

                    ColorMatrix colorMatrix = new ColorMatrix(jaggedMatrix);

                    // Create an ImageAttributes object and set its color matrix
                    using (ImageAttributes attributes = new ImageAttributes())
                    {
                        attributes.SetColorMatrix(
                            colorMatrix,
                            ColorMatrixFlag.Default,
                            ColorAdjustType.Bitmap);

                        using (Bitmap closeIcon = new Bitmap(Resources.CaptionClose), dropDownIcon = new Bitmap(Resources.DropDown))
                        {
                            using (ImageAttributes attributes2 = new ImageAttributes())
                            {
                                ColorMap[] map = new ColorMap[2];
                                map[0]          = new ColorMap();
                                map[0].OldColor = Color.White;
                                map[0].NewColor = Color.Transparent;
                                map[1]          = new ColorMap();
                                map[1].OldColor = Color.Black;
                                map[1].NewColor = contextInstance.CaptionButtons.ActiveCaptionButtonsColor;

                                attributes2.SetRemapTable(map);

                                // Shrink rectangle for drawing caption background.
                                rct.Inflate(-1, -1);
                                rct.Width  += 1;
                                rct.Height += 1;
                                e.Graphics.DrawImage(overlay, rct, 1, 1, overlay.Width - 1, overlay.Height - 1, GraphicsUnit.Pixel, attributes);

                                Rectangle closeIconRct    = new Rectangle(rct.Right - (3 + closeIcon.Width), rct.Y + 4, closeIcon.Width, closeIcon.Height);
                                Rectangle dropDownIconRct = new Rectangle(closeIconRct.Left - (3 + dropDownIcon.Width), rct.Y + 4, dropDownIcon.Width, dropDownIcon.Height);

                                e.Graphics.DrawImage(closeIcon, closeIconRct, 0, 0, closeIcon.Width, closeIcon.Height, GraphicsUnit.Pixel, attributes2);
                                e.Graphics.DrawImage(dropDownIcon, dropDownIconRct, 0, 0, dropDownIcon.Width, dropDownIcon.Height, GraphicsUnit.Pixel, attributes2);

                                using (Font captionFont = new System.Drawing.Font("Arial", 12, contextInstance.GradientCaption.ActiveCaptionFontStyle, GraphicsUnit.Pixel))
                                    using (SolidBrush captionTextBrush = new SolidBrush(contextInstance.GradientCaption.ActiveCaptionTextColor))
                                    {
                                        e.Graphics.DrawString("Active Caption", captionFont,
                                                              captionTextBrush, new Point(rct.X + 3, rct.Y + 3));
                                    }

                                rct.Y      = rct.Bottom + 8;
                                rct.X     -= 1;
                                rct.Width += 1;

                                // Draw Border Lines
                                using (Pen captionBorderPen = new Pen(contextInstance.BorderColor))
                                    e.Graphics.DrawRectangle(captionBorderPen, rct);

                                rct.Inflate(-1, -1);
                                rct.Width  += 1;
                                rct.Height += 1;
                                e.Graphics.DrawImage(overlay2, rct, 1, 1, overlay2.Width - 1, overlay2.Height - 1, GraphicsUnit.Pixel, attributes);

                                map[1].NewColor = contextInstance.CaptionButtons.InactiveCaptionButtonsColor;
                                attributes2.SetRemapTable(map);

                                closeIconRct    = new Rectangle(rct.Right - (3 + closeIcon.Width), rct.Y + 3, closeIcon.Width, closeIcon.Height);
                                dropDownIconRct = new Rectangle(closeIconRct.Left - (3 + dropDownIcon.Width), rct.Y + 3, dropDownIcon.Width, dropDownIcon.Height);

                                e.Graphics.DrawImage(closeIcon, closeIconRct, 0, 0, closeIcon.Width, closeIcon.Height, GraphicsUnit.Pixel, attributes2);
                                e.Graphics.DrawImage(dropDownIcon, dropDownIconRct, 0, 0, dropDownIcon.Width, dropDownIcon.Height, GraphicsUnit.Pixel, attributes2);

                                using (Font captionFont = new System.Drawing.Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel))
                                    using (SolidBrush captionTextBrush = new SolidBrush(contextInstance.GradientCaption.InactiveCaptionTextColor))
                                    {
                                        e.Graphics.DrawString("Inactive Caption", captionFont,
                                                              captionTextBrush, new Point(rct.X + 3, rct.Y + 3));
                                    }
                            }
                        }
                    }
                }
            }
示例#17
0
        /// <summary>
        /// 图片等比缩放
        /// </summary>
        /// <remarks>谭光洪 2015-05-09</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="savePath">缩略图存放地址</param>
        /// <param name="targetWidth">指定的最大宽度</param>
        /// <param name="targetHeight">指定的最大高度</param>
        /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
        /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
        public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage)
        {
            //创建目录
            string dir = Path.GetDirectoryName(savePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
            {
                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("黑体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(initImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存
                initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //缩略图宽、高计算
                double newWidth  = initImage.Width;
                double newHeight = initImage.Height;

                //宽大于高或宽等于高(横图或正方)
                if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
                {
                    //如果宽大于模版
                    if (initImage.Width > targetWidth)
                    {
                        //宽按模版,高按比例缩放
                        newWidth  = targetWidth;
                        newHeight = initImage.Height * (targetWidth / initImage.Width);
                    }
                }
                //高大于宽(竖图)
                else
                {
                    //如果高大于模版
                    if (initImage.Height > targetHeight)
                    {
                        //高按模版,宽按比例缩放
                        newHeight = targetHeight;
                        newWidth  = initImage.Width * (targetHeight / initImage.Height);
                    }
                }

                //生成新图
                //新建一个bmp图片
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一个画板
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

                //设置质量
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色
                newG.Clear(Color.White);
                //画图
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("宋体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(newImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存缩略图
                newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                //释放资源
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
            }
        }
示例#18
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="sourcePicture">源图片文件名</param>
        /// <param name="waterImage">水印图片文件名</param>
        /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
        /// <param name="position">位置</param>
        /// <param name="PicturePath" >图片的路径</param>
        /// <returns>返回生成于指定文件夹下的水印文件名</returns>
        public string DrawImage(string sourcePicture,
                                string waterImage,
                                float alpha,
                                ImagePosition position,
                                string PicturePath)
        {
            //
            // 判断参数是否有效
            //
            if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
            {
                return(sourcePicture);
            }

            //
            // 源图片,水印图片全路径
            //
            string sourcePictureName   = PicturePath + sourcePicture;
            string waterPictureName    = PicturePath + waterImage;
            string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
            string fileWaterExtension  = System.IO.Path.GetExtension(waterPictureName).ToLower();

            //
            // 判断文件是否存在,以及类型是否正确
            //
            if (System.IO.File.Exists(sourcePictureName) == false ||
                System.IO.File.Exists(waterPictureName) == false || (
                    fileSourceExtension != ".gif" &&
                    fileSourceExtension != ".jpg" &&
                    fileSourceExtension != ".png") || (
                    fileWaterExtension != ".gif" &&
                    fileWaterExtension != ".jpg" &&
                    fileWaterExtension != ".png")
                )
            {
                return(sourcePicture);
            }

            //
            // 目标图片名称及全路径
            //
            string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg";

            //
            // 将需要加上水印的图片装载到Image对象中
            //
            Image imgPhoto = Image.FromFile(sourcePictureName);
            //
            // 确定其长宽
            //
            int phWidth  = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //
            // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。
            //
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //
            // 设定分辨率
            //
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 定义一个绘图画面用来装载位图
            //
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //
            //同样,由于水印是图片,我们也需要定义一个Image来装载它
            //
            Image imgWatermark = new Bitmap(waterPictureName);

            //
            // 获取水印图片的高度和宽度
            //
            int wmWidth  = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
            // 成员名称   说明
            // AntiAlias      指定消除锯齿的呈现。
            // Default        指定不消除锯齿。
            // HighQuality  指定高质量、低速度呈现。
            // HighSpeed   指定高速度、低质量呈现。
            // Invalid        指定一个无效模式。
            // None          指定不消除锯齿。
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //
            // 第一次描绘,将我们的底图描绘在绘图画面上
            //
            grPhoto.DrawImage(imgPhoto,
                              new Rectangle(0, 0, phWidth, phHeight),
                              0,
                              0,
                              phWidth,
                              phHeight,
                              GraphicsUnit.Pixel);

            //
            // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
            //
            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 继续,将水印图片装载到一个绘图画面grWatermark
            //
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //
            //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
            //
            ImageAttributes imageAttributes = new ImageAttributes();

            //
            //Colormap: 定义转换颜色的映射
            //
            ColorMap colorMap = new ColorMap();

            //
            //我的水印图被定义成拥有绿色背景色的图片被替换成透明
            //
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,  0.0f, 0.0f }, // red红色
                new float[] { 0.0f, 1.0f, 0.0f,  0.0f, 0.0f }, //green绿色
                new float[] { 0.0f, 0.0f, 1.0f,  0.0f, 0.0f }, //blue蓝色
                new float[] { 0.0f, 0.0f, 0.0f, alpha, 0.0f }, //透明度
                new float[] { 0.0f, 0.0f, 0.0f,  0.0f, 1.0f }
            };                                                 //

            //  ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。
            //  ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);

            //
            //上面设置完颜色,下面开始设置位置
            //
            int xPosOfWm;
            int yPosOfWm;

            switch (position)
            {
            case ImagePosition.BottomMiddle:
                xPosOfWm = (phWidth - wmWidth) / 2;
                yPosOfWm = phHeight - wmHeight - 10;
                break;

            case ImagePosition.Center:
                xPosOfWm = (phWidth - wmWidth) / 2;
                yPosOfWm = (phHeight - wmHeight) / 2;
                break;

            case ImagePosition.LeftBottom:
                xPosOfWm = 10;
                yPosOfWm = phHeight - wmHeight - 10;
                break;

            case ImagePosition.LeftTop:
                xPosOfWm = 10;
                yPosOfWm = 10;
                break;

            case ImagePosition.RightTop:
                xPosOfWm = phWidth - wmWidth - 10;
                yPosOfWm = 10;
                break;

            case ImagePosition.RigthBottom:
                xPosOfWm = phWidth - wmWidth - 10;
                yPosOfWm = phHeight - wmHeight - 10;
                break;

            case ImagePosition.TopMiddle:
                xPosOfWm = (phWidth - wmWidth) / 2;
                yPosOfWm = 10;
                break;

            case ImagePosition.RightMiddle:
                xPosOfWm = 10;
                yPosOfWm = (phHeight - wmHeight) / 2;
                break;

            case ImagePosition.LeftMiddle:
                xPosOfWm = phWidth - wmWidth - 10;
                yPosOfWm = (phHeight - wmHeight) / 2;
                break;

            default:
                xPosOfWm = 10;
                yPosOfWm = phHeight - wmHeight - 10;
                break;
            }

            //
            // 第二次绘图,把水印印上去
            //
            grWatermark.DrawImage(imgWatermark,
                                  new Rectangle(xPosOfWm,
                                                yPosOfWm,
                                                wmWidth,
                                                wmHeight),
                                  0,
                                  0,
                                  wmWidth,
                                  wmHeight,
                                  GraphicsUnit.Pixel,
                                  imageAttributes);


            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //
            // 保存文件到服务器的文件夹里面
            //
            imgPhoto.Save(targetImage, ImageFormat.Jpeg);
            imgPhoto.Dispose();
            imgWatermark.Dispose();
            return(targetImage.Replace(PicturePath, ""));
        }
示例#19
0
        private void GetBitmaps()
        {
            if (myBitmap == null ||
                myAlphaBitmap == null ||
                myBitmap.Width != Width ||
                myBitmap.Height != Height ||
                myAlphaBitmap.Width != Width ||
                myAlphaBitmap.Height != Height)
            {
                myBitmap      = null;
                myAlphaBitmap = null;
            }



            if (myBitmap == null)
            {
                myBitmap   = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(Width,Height);
                myUpToDate = false;
            }


            if (!myUpToDate)
            {
                //Capture the TextBox control window

                this.SetStyle(ControlStyles.UserPaint, false);

                Win32.CaptureWindow(this, ref myBitmap);

//                this.SetStyle(ControlStyles.UserPaint, true);
                this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
                this.BackColor = Color.FromArgb(myBackAlpha, myBackColor);
            }
            //--



            Rectangle       r2            = new Rectangle(0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height);
            ImageAttributes tempImageAttr = new ImageAttributes();


            //Found the color map code in the MS Help

            ColorMap[] tempColorMap = new ColorMap[1];
            tempColorMap[0]          = new ColorMap();
            tempColorMap[0].OldColor = Color.FromArgb(255, myBackColor);
            tempColorMap[0].NewColor = Color.FromArgb(myBackAlpha, myBackColor);

            tempImageAttr.SetRemapTable(tempColorMap);

            if (myAlphaBitmap != null)
            {
                myAlphaBitmap.Dispose();
            }


            myAlphaBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);//(Width,Height);

            Graphics tempGraphics1 = Graphics.FromImage(myAlphaBitmap);

            tempGraphics1.DrawImage(myBitmap, r2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, GraphicsUnit.Pixel, tempImageAttr);

            tempGraphics1.Dispose();

            //----

            if (this.Focused && (this.SelectionLength == 0))
            {
                Graphics tempGraphics2 = Graphics.FromImage(myAlphaBitmap);
                if (myCaretState)
                {
                    //Draw the caret
                    Point caret = this.findCaret();
                    Pen   p     = new Pen(this.ForeColor, 3);
                    tempGraphics2.DrawLine(p, caret.X, caret.Y + 0, caret.X, caret.Y + myFontHeight);
                    tempGraphics2.Dispose();
                }
            }
        }
        private string DrawImageAddWater(Image imgPhoto, string waterImagePath_Name, string SavePath, int position, float alpha, int quality, bool IsMulti)
        {
            string a = Path.GetExtension(waterImagePath_Name).ToLower();

            if (!File.Exists(waterImagePath_Name) || (a != ".gif" && a != ".jpg" && a != ".png" && a != ".bmp"))
            {
                return(string.Format("水印路径:{0}中未找到相关图片.或水印图片格式不支持!", waterImagePath_Name));
            }
            int    arg_5A_0 = imgPhoto.Width;
            int    arg_61_0 = imgPhoto.Height;
            Image  image    = new Bitmap(waterImagePath_Name);
            int    width    = image.Width;
            int    height   = image.Height;
            Bitmap bitmap   = new Bitmap(imgPhoto);

            bitmap.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics        graphics        = Graphics.FromImage(bitmap);
            ImageAttributes imageAttributes = new ImageAttributes();

            ColorMap[] map = new ColorMap[]
            {
                new ColorMap
                {
                    OldColor = Color.FromArgb(255, 0, 255, 0),
                    NewColor = Color.FromArgb(0, 0, 0, 0)
                }
            };
            imageAttributes.SetRemapTable(map, ColorAdjustType.Bitmap);
            float[][] array     = new float[5][];
            float[][] arg_10B_0 = array;
            int       arg_10B_1 = 0;

            float[] array2 = new float[5];
            array2[0]            = 1f;
            arg_10B_0[arg_10B_1] = array2;
            float[][] arg_122_0 = array;
            int       arg_122_1 = 1;

            float[] array3 = new float[5];
            array3[1]            = 1f;
            arg_122_0[arg_122_1] = array3;
            float[][] arg_139_0 = array;
            int       arg_139_1 = 2;

            float[] array4 = new float[5];
            array4[2]            = 1f;
            arg_139_0[arg_139_1] = array4;
            float[][] arg_14D_0 = array;
            int       arg_14D_1 = 3;

            float[] array5 = new float[5];
            array5[3]            = alpha;
            arg_14D_0[arg_14D_1] = array5;
            array[4]             = new float[]
            {
                0f,
                0f,
                0f,
                0f,
                1f
            };
            float[][]   newColorMatrix  = array;
            ColorMatrix newColorMatrix2 = new ColorMatrix(newColorMatrix);

            imageAttributes.SetColorMatrix(newColorMatrix2, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            int num = 0;
            int y   = 0;

            switch (position)
            {
            case 1:
                num = (int)((float)imgPhoto.Width * 0.01f);
                y   = (int)((float)imgPhoto.Height * 0.01f);
                break;

            case 2:
                num = (int)((float)imgPhoto.Width * 0.5f - (float)(image.Width / 2));
                y   = (int)((float)imgPhoto.Height * 0.01f);
                break;

            case 3:
                num = (int)((float)imgPhoto.Width * 0.99f - (float)image.Width);
                y   = (int)((float)imgPhoto.Height * 0.01f);
                break;

            case 4:
                num = (int)((float)imgPhoto.Width * 0.005f);
                y   = (int)((float)imgPhoto.Height * 0.5f - (float)(image.Height / 2));
                break;

            case 5:
                num = (int)((float)imgPhoto.Width * 0.5f - (float)(image.Width / 2));
                y   = (int)((float)imgPhoto.Height * 0.5f - (float)(image.Height / 2));
                break;

            case 6:
                num = (int)((float)imgPhoto.Width * 0.99f - (float)image.Width);
                y   = (int)((float)imgPhoto.Height * 0.5f - (float)(image.Height / 2));
                break;

            case 7:
                num = (int)((float)imgPhoto.Width * 0.01f);
                y   = (int)((float)imgPhoto.Height * 0.99f - (float)image.Height);
                break;

            case 8:
                num = (int)((float)imgPhoto.Width * 0.5f - (float)(image.Width / 2));
                y   = (int)((float)imgPhoto.Height * 0.99f - (float)image.Height);
                break;

            case 9:
                num = (int)((float)imgPhoto.Width * 0.99f - (float)image.Width);
                y   = (int)((float)imgPhoto.Height * 0.99f - (float)image.Height);
                break;
            }
            if (IsMulti)
            {
                for (int i = num; i < imgPhoto.Width + image.Width; i += image.Width + 5)
                {
                    graphics.DrawImage(image, new Rectangle(i, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes);
                }
            }
            else
            {
                graphics.DrawImage(image, new Rectangle(num, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes);
            }
            imgPhoto = bitmap;
            graphics.Dispose();
            ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   encoder       = null;

            ImageCodecInfo[] array6 = imageEncoders;
            for (int j = 0; j < array6.Length; j++)
            {
                ImageCodecInfo imageCodecInfo = array6[j];
                if (imageCodecInfo.MimeType.IndexOf("jpeg") > -1)
                {
                    encoder = imageCodecInfo;
                }
            }
            EncoderParameters encoderParameters = new EncoderParameters();

            long[] array7 = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            array7[0] = (long)quality;
            EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, array7);

            encoderParameters.Param[0] = encoderParameter;
            imgPhoto.Save(SavePath, encoder, encoderParameters);
            imgPhoto.Dispose();
            image.Dispose();
            return(string.Empty);
        }
示例#21
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(Utils.GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = Utils.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
示例#22
0
        private void DrawImage(Graphics g)
        {
            Image           image     = this.Enabled ? ImageEnabled : ((ImageDisabled != null) ? ImageDisabled : ImageEnabled);
            ImageAttributes imageAttr = null;

            if (null == image)
            {
                return;
            }

            if (m_monochrom)
            {
                imageAttr = new ImageAttributes();

                // transform the monochrom image
                // white -> BackColor
                // black -> ForeColor
                ColorMap[] colorMap = new ColorMap[2];
                colorMap[0]          = new ColorMap();
                colorMap[0].OldColor = Color.White;
                colorMap[0].NewColor = this.BackColor;
                colorMap[1]          = new ColorMap();
                colorMap[1].OldColor = Color.Black;
                colorMap[1].NewColor = this.ForeColor;
                imageAttr.SetRemapTable(colorMap);
            }

            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

            if ((!Enabled) && (null == ImageDisabled))
            {
                using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
                {
                    if (imageAttr != null)
                    {
                        using (Graphics gMono = Graphics.FromImage(bitmapMono))
                        {
                            gMono.DrawImage(image, new Point[3] {
                                new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1)
                            }, rect, GraphicsUnit.Pixel, imageAttr);
                        }
                    }
                    ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
                }
            }
            else
            {
                // Three points provided are upper-left, upper-right and
                // lower-left of the destination parallelogram.
                Point[] pts = new Point[3];
                pts[0].X = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
                pts[0].Y = (Enabled && m_mouseOver && m_mouseCapture) ? 1 : 0;
                pts[1].X = pts[0].X + ClientRectangle.Width;
                pts[1].Y = pts[0].Y;
                pts[2].X = pts[0].X;
                pts[2].Y = pts[1].Y + ClientRectangle.Height;

                if (imageAttr == null)
                {
                    g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
                }
                else
                {
                    g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
                }
            }
        }
示例#23
0
        /// <summary>
        /// 生成图片水印
        /// </summary>
        /// <param name="originalPath">源图路径</param>
        /// <param name="watermarkPath">水印图片路径</param>
        /// <param name="targetPath">保存路径</param>
        /// <param name="position">位置</param>
        /// <param name="opacity">透明度</param>
        /// <param name="quality">质量</param>
        public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality)
        {
            Image originalImage  = null;
            Image watermarkImage = null;
            //图片属性
            ImageAttributes attributes = null;
            //画板
            Graphics g = null;

            try
            {
                originalImage  = Image.FromFile(originalPath);
                watermarkImage = new Bitmap(watermarkPath);

                if (watermarkImage.Height >= originalImage.Height || watermarkImage.Width >= originalImage.Width)
                {
                    originalImage.Save(targetPath);
                    return;
                }

                if (quality < 0 || quality > 100)
                {
                    quality = 80;
                }

                //水印透明度
                float iii;
                if (opacity > 0 && opacity <= 10)
                {
                    iii = (float)(opacity / 10.0F);
                }
                else
                {
                    iii = 0.5F;
                }

                //水印位置
                int x = 0;
                int y = 0;
                switch (position)
                {
                case 1:
                    x = (int)(originalImage.Width * (float).01);
                    y = (int)(originalImage.Height * (float).01);
                    break;

                case 2:
                    x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2));
                    y = (int)(originalImage.Height * (float).01);
                    break;

                case 3:
                    x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width));
                    y = (int)(originalImage.Height * (float).01);
                    break;

                case 4:
                    x = (int)(originalImage.Width * (float).01);
                    y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2));
                    break;

                case 5:
                    x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2));
                    y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2));
                    break;

                case 6:
                    x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width));
                    y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2));
                    break;

                case 7:
                    x = (int)(originalImage.Width * (float).01);
                    y = (int)((originalImage.Height * (float).99) - watermarkImage.Height);
                    break;

                case 8:
                    x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2));
                    y = (int)((originalImage.Height * (float).99) - watermarkImage.Height);
                    break;

                case 9:
                    x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width));
                    y = (int)((originalImage.Height * (float).99) - watermarkImage.Height);
                    break;
                }

                //颜色映射表
                ColorMap colorMap = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] newColorMap = { colorMap };

                //颜色变换矩阵,iii是设置透明度的范围0到1中的单精度类型
                float[][] newColorMatrix =
                {
                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 0.0f, 0.0f, iii,  0.0f },
                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                };
                //定义一个 5 x 5 矩阵
                ColorMatrix matrix = new ColorMatrix(newColorMatrix);

                //图片属性
                attributes = new ImageAttributes();
                attributes.SetRemapTable(newColorMap, ColorAdjustType.Bitmap);
                attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                //画板
                g = Graphics.FromImage(originalImage);
                //绘制水印
                g.DrawImage(watermarkImage, new Rectangle(x, y, watermarkImage.Width, watermarkImage.Height), 0, 0, watermarkImage.Width, watermarkImage.Height, GraphicsUnit.Pixel, attributes);
                //保存图片
                EncoderParameters encoderParams = new EncoderParameters();
                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { quality });
                if (GetJPEGCodec() != null)
                {
                    originalImage.Save(targetPath, _jpegcodec, encoderParams);
                }
                else
                {
                    originalImage.Save(targetPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }
                if (attributes != null)
                {
                    attributes.Dispose();
                }
                if (watermarkImage != null)
                {
                    watermarkImage.Dispose();
                }
                if (originalImage != null)
                {
                    originalImage.Dispose();
                }
            }
        }
示例#24
0
        /// <summary>
        /// Draws the button on the specified graphics.
        /// <seealso cref="Graphics"/>
        /// </summary>
        /// <param name="graphics">Button graphics object.</param>
        protected virtual void DrawButton(Graphics graphics)
        {
            // Cleat the background with the Back color
            graphics.Clear(this.BackColor);

            // Draw background
            if (this.Vertical)
            {
                DrawVerticalButtonBack(graphics);
            }
            else
            {
                DrawHorizontalButtonBack(graphics);
            }

            // Draw image
            Rectangle imageRect = Rectangle.Empty;

            if (this.Image != null)
            {
                // Calculate image rectangle position
                imageRect.X      = this.ClientRectangle.X + this.offset;
                imageRect.Y      = this.ClientRectangle.Y + (this.ClientRectangle.Height - this.Image.Height) / 2;
                imageRect.Width  = this.Image.Width;
                imageRect.Height = this.Image.Height;

                // Shift image by 1 pixel when in pressed state
                if (this.pressed && this.Vertical)
                {
                    ++imageRect.X;
                    ++imageRect.Y;
                }

                // Replace transparent color (White) with button back color
                ColorMap[] myColorMap = new ColorMap[1];
                myColorMap[0]          = new ColorMap();
                myColorMap[0].OldColor = Color.White;
                myColorMap[0].NewColor = this.BackColor;

                // Create an ImageAttributes object
                ImageAttributes imageAttr = new ImageAttributes();
                imageAttr.SetRemapTable(myColorMap);

                // Draw image
                graphics.DrawImage(
                    this.Image,
                    imageRect,
                    0,
                    0,
                    this.Image.Width,
                    this.Image.Height,
                    GraphicsUnit.Pixel,
                    imageAttr);

                imageAttr.Dispose();
            }

            // Draw button text
            if (this.Text.Length > 0)
            {
                Rectangle textRect = new Rectangle(this.ClientRectangle.Location, this.ClientRectangle.Size);
                textRect.X     += this.offset - 2;
                textRect.Width -= 2 * this.offset;
                if (this.Image != null)
                {
                    textRect.X     += this.offset + this.Image.Width;
                    textRect.Width -= this.offset + this.Image.Width;
                }

                // Shift image by 1 pixel when in pressed state
                if (this.pressed && this.Vertical)
                {
                    ++textRect.X;
                    ++textRect.Y;
                }

                StringFormat format = new StringFormat();
                format.LineAlignment = StringAlignment.Center;
                format.Alignment     = StringAlignment.Center;
                format.Trimming      = StringTrimming.EllipsisCharacter;
                format.FormatFlags   = StringFormatFlags.LineLimit;
                using (SolidBrush brush = new SolidBrush((this.SelectedTab) ? textColorSelected : textColorUnSelected))
                {
                    graphics.DrawString(this.Text, this.Font, brush, textRect, format);
                }

                format.Dispose();
            }
        }
示例#25
0
    /// <summary>

    ///   加水印图片

    /// </summary>

    /// <param name="picture">imge 对象</param>

    /// <param name="iTheImage">Image对象(以此图片为水印)</param>

    /// <param name="_watermarkPosition">水印位置</param>

    /// <param name="_width">被加水印图片的宽</param>

    /// <param name="_height">被加水印图片的高</param>

    private void addWatermarkImage(Graphics picture, Image iTheImage,

        string _watermarkPosition, int _width, int _height)
    {

        Image watermark = new Bitmap(iTheImage);

        var imageAttributes = new ImageAttributes();

        var colorMap = new ColorMap();

        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);

        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

        ColorMap[] remapTable = { colorMap };

        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        float[][] colorMatrixElements = {
 
                                            new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
 
                                            new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
 
                                            new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
 
                                            new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
 
                                            new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
 
                                        };

        var colorMatrix = new ColorMatrix(colorMatrixElements);

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        var xpos = 0;

        var ypos = 0;

        var WatermarkWidth = 0;

        var WatermarkHeight = 0;

        var bl = 1d;

        //计算水印图片的比率

        //取背景的1/4宽度来比较

        if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
        {

            bl = 1;

        }

        else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))
        {

            bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);



        }

        else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
        {

            bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);

        }

        else
        {

            if ((_width * watermark.Height) > (_height * watermark.Width))
            {

                bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);



            }

            else
            {

                bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);



            }



        }

        WatermarkWidth = Convert.ToInt32(watermark.Width * bl);

        WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

        switch (_watermarkPosition)
        {

            case "WM_TOP_LEFT":

                xpos = 10;

                ypos = 10;

                break;

            case "WM_TOP_RIGHT":

                xpos = _width - WatermarkWidth - 10;

                ypos = 10;

                break;

            case "WM_BOTTOM_RIGHT":

                xpos = _width - WatermarkWidth - 10;

                ypos = _height - WatermarkHeight - 10;

                break;

            case "WM_BOTTOM_LEFT":

                xpos = 10;

                ypos = _height - WatermarkHeight - 10;

                break;

        }

        picture.DrawImage(

            watermark,

            new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),

            0,

            0,

            watermark.Width,

            watermark.Height,

            GraphicsUnit.Pixel,

            imageAttributes);

        watermark.Dispose();

        imageAttributes.Dispose();

    }
示例#26
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片绝对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(HttpContext context, string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            byte[] _ImageBytes = File.ReadAllBytes(imgPath);
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = Utils.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = null;

            if (IsPixelFormatIndexed(img.PixelFormat))
            {
                Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
                using (Graphics g2 = Graphics.FromImage(bmp))
                {
                    g2.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g2.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g2.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g2.DrawImage(img, 0, 0);
                }

                img = bmp;
            }



            g = Graphics.FromImage(img);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode   = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            Image watermark = new Bitmap(watermarkFilename);

            //if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            //    return;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;


            context.Response.ContentType = "image/jpeg";
            //将叠加后的图片以指定的格式保存到Response的输出流中。
            if (ici != null)
            {
                img.Save(context.Response.OutputStream, ici, encoderParams);
            }
            else
            {
                img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            }
            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();

            context.Response.End();
        }
示例#27
0
    /// <summary>
    /// 加图片水印
    /// </summary>
    /// <param name="imgPath">原图文件名物理路径</param>
    /// <param name="filename">生成文件名物理路径</param>
    /// <param name="watermarkFilename">水印文件名物理路径</param>
    /// <param name="positon">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
    /// <param name="quality">附加图片质量,0--100之间,值大质量高</param>
    /// <param name="watermarkTransparency">水印的透明度 1--100 100为不透明</param>

    public static bool AddImageSignPic(string imgPath, string filename, string watermarkFilename, Enums.Position positon, int quality, int watermarkTransparency, int minWidth, int minHeight)
    {
        using (Bitmap img = new Bitmap(imgPath))
        {
            Graphics g ;
                //如果原图片是索引像素格式之列的,则需要转换
                if (IsPixelFormatIndexed(img.PixelFormat))
                {
                    using (Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb))
                    {
                        g = Graphics.FromImage(bmp);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(img, 0, 0);
                    }

                }
                else
                {
                    g = Graphics.FromImage(img);
                    //设置高质量插值法
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                }
                int watermarkStatus = (int)positon;


                using (System.Drawing.Image watermark = new Bitmap(watermarkFilename))
                {

                    if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                    {
                        return false;
                    }
                    if (img.Width < minWidth || img.Height < minHeight)
                    {
                        return false;
                    }


                    using (ImageAttributes imageAttributes = new ImageAttributes())
                    {
                        ColorMap colorMap = new ColorMap();

                        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                        ColorMap[] remapTable = { colorMap };

                        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                        float transparency = 0.5F;
                        if (watermarkTransparency >= 1 && watermarkTransparency <= 100)
                        {
                            transparency = (watermarkTransparency / 100.0F);
                        }

                        float[][] colorMatrixElements = {
                                                new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f},
                                                new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
                                            };

                        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

                        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                        int xpos = 0;
                        int ypos = 0;

                        switch (watermarkStatus)
                        {
                            case 1:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 2:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 3:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)(img.Height * (float).01);
                                break;
                            case 4:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 5:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 6:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                                break;
                            case 7:
                                xpos = (int)(img.Width * (float).01);
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                            case 8:
                                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                            case 9:
                                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                                ypos = (int)((img.Height * (float).99) - watermark.Height);
                                break;
                        }

                        g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
                        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo ici = null;
                        foreach (ImageCodecInfo codec in codecs)
                        {
                            if (codec.MimeType.ToLower().IndexOf("jpeg") > -1 || codec.MimeType.ToLower().IndexOf("jpg") > -1)
                            {
                                ici = codec;
                            }
                        }
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[] qualityParam = new long[1];
                        if (quality < 0 || quality > 100)
                        {
                            quality = 80;
                        }
                        qualityParam[0] = quality;

                        EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
                        encoderParams.Param[0] = encoderParam;

                        if (ici != null)
                        {
                            img.Save(filename, ici, encoderParams);
                        }
                        else
                        {
                            img.Save(filename);
                        }

                        g.Dispose();
                        img.Dispose();
                        watermark.Dispose();
                        imageAttributes.Dispose();
                    }
                
            }
        }
        return true;
    }
示例#28
0
    /// <summary>

    ///   加水印图片

    /// </summary>

    /// <param name="picture">imge 对象</param>

    /// <param name="iTheImage">Image对象(以此图片为水印)</param>

    /// <param name="_watermarkPosition">水印位置</param>

    /// <param name="_width">被加水印图片的宽</param>

    /// <param name="_height">被加水印图片的高</param>

    private void addWatermarkImage(Graphics picture, Image iTheImage,

                                   string _watermarkPosition, int _width, int _height)
    {
        Image watermark = new Bitmap(iTheImage);

        var imageAttributes = new ImageAttributes();

        var colorMap = new ColorMap();

        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);

        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

        ColorMap[] remapTable = { colorMap };

        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

        float[][] colorMatrixElements =
        {
             
            new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
             
            new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
             
            new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
             
            new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
             
            new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
             
        };

        var colorMatrix = new ColorMatrix(colorMatrixElements);

        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        var xpos = 0;

        var ypos = 0;

        var WatermarkWidth = 0;

        var WatermarkHeight = 0;

        var bl = 1d;

        //计算水印图片的比率

        //取背景的1/4宽度来比较

        if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
        {
            bl = 1;
        }

        else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))
        {
            bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);
        }

        else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
        {
            bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
        }

        else
        {
            if ((_width * watermark.Height) > (_height * watermark.Width))
            {
                bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);
            }

            else
            {
                bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
            }
        }

        WatermarkWidth = Convert.ToInt32(watermark.Width * bl);

        WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

        switch (_watermarkPosition)
        {
        case "WM_TOP_LEFT":

            xpos = 10;

            ypos = 10;

            break;

        case "WM_TOP_RIGHT":

            xpos = _width - WatermarkWidth - 10;

            ypos = 10;

            break;

        case "WM_BOTTOM_RIGHT":

            xpos = _width - WatermarkWidth - 10;

            ypos = _height - WatermarkHeight - 10;

            break;

        case "WM_BOTTOM_LEFT":

            xpos = 10;

            ypos = _height - WatermarkHeight - 10;

            break;
        }

        picture.DrawImage(

            watermark,

            new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),

            0,

            0,

            watermark.Width,

            watermark.Height,

            GraphicsUnit.Pixel,

            imageAttributes);

        watermark.Dispose();

        imageAttributes.Dispose();
    }
示例#29
0
                private void DrawImage(Graphics g)
                {
                    Image image;
                    if (this.Enabled)
                    {
                        image = this.ImageEnabled;
                    }
                    else
                    {
                        if (ImageDisabled != null)
                        {
                            image = this.ImageDisabled;
                        }
                        else
                        {
                            image = this.ImageEnabled;
                        }
                    }
                    ImageAttributes imageAttr = null;
                    if (image == null)
                    {
                        return;
                    }
                    if (m_monochrom)
                    {
                        imageAttr = new ImageAttributes();
                        // transform the monochrom image
                        // white -> BackColor
                        // black -> ForeColor
                        ColorMap[] myColorMap = new ColorMap[2];
                        myColorMap[0] = new ColorMap();
                        myColorMap[0].OldColor = Color.White;
                        myColorMap[0].NewColor = Color.Transparent;
                        myColorMap[1] = new ColorMap();
                        myColorMap[1].OldColor = Color.Black;
                        myColorMap[1].NewColor = this.ForeColor;
                        imageAttr.SetRemapTable(myColorMap);
                    }
                    Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
                    if ((! Enabled) && (ImageDisabled == null))
                    {
                        using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
                        {
                            if (imageAttr != null)
                            {
                                using (Graphics gMono = Graphics.FromImage(bitmapMono))
                                {
                                    gMono.DrawImage(image, new Point[3] {new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1)}, rect, GraphicsUnit.Pixel, imageAttr);
                                }

                            }
                            ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
                        }

                    }
                    else
                    {
                        // Three points provided are upper-left, upper-right and
                        // lower-left of the destination parallelogram.
                        Point[] pts = new Point[3]();
                        if (Enabled && m_mouseOver && m_mouseCapture)
                        {
                            pts[0].X = 1;
                            pts[0].Y = 1;
                        }
                        else
                        {
                            pts[0].X = 0;
                            pts[0].Y = 0;
                        }
                        pts[1].X = pts[0].X + ClientRectangle.Width;
                        pts[1].Y = pts[0].Y;
                        pts[2].X = pts[0].X;
                        pts[2].Y = pts[1].Y + ClientRectangle.Height;
                        if (imageAttr == null)
                        {
                            g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
                        }
                        else
                        {
                            g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
                        }
                    }
                }
示例#30
0
        public static Image WatermarkImage(Image originalImage, Image watermarkImage, WatermarkPosition position)
        {
            Image           image     = (Image)originalImage.Clone();
            ImageAttributes imageAttr = new ImageAttributes();
            ColorMap        map       = new ColorMap {
                OldColor = Color.FromArgb(0xff, 0, 0xff, 0),
                NewColor = Color.FromArgb(0, 0, 0, 0)
            };

            ColorMap[] mapArray2 = new ColorMap[] { map };
            imageAttr.SetRemapTable(mapArray2, ColorAdjustType.Bitmap);
            float[][] numArray  = new float[5][];
            float[]   numArray2 = new float[5];
            numArray2[0] = 1f;
            numArray[0]  = numArray2;
            numArray2    = new float[5];
            numArray2[1] = 1f;
            numArray[1]  = numArray2;
            numArray2    = new float[5];
            numArray2[2] = 1f;
            numArray[2]  = numArray2;
            numArray2    = new float[5];
            numArray2[3] = 0.3f;
            numArray[3]  = numArray2;
            numArray2    = new float[5];
            numArray2[4] = 1f;
            numArray[4]  = numArray2;
            float[][]   newColorMatrix = numArray;
            ColorMatrix matrix         = new ColorMatrix(newColorMatrix);

            imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            int    x      = 0;
            int    y      = 0;
            int    width  = 0;
            int    height = 0;
            double num5   = 1.0;

            if ((image.Width > (watermarkImage.Width * 4)) && (image.Height > (watermarkImage.Height * 4)))
            {
                num5 = 1.0;
            }
            else if ((image.Width > (watermarkImage.Width * 4)) && (image.Height < (watermarkImage.Height * 4)))
            {
                num5 = Convert.ToDouble((int)(image.Height / 4)) / Convert.ToDouble(watermarkImage.Height);
            }
            else if ((image.Width < (watermarkImage.Width * 4)) && (image.Height > (watermarkImage.Height * 4)))
            {
                num5 = Convert.ToDouble((int)(image.Width / 4)) / Convert.ToDouble(watermarkImage.Width);
            }
            else if ((image.Width * watermarkImage.Height) > (image.Height * watermarkImage.Width))
            {
                num5 = Convert.ToDouble((int)(image.Height / 4)) / Convert.ToDouble(watermarkImage.Height);
            }
            else
            {
                num5 = Convert.ToDouble((int)(image.Width / 4)) / Convert.ToDouble(watermarkImage.Width);
            }
            width  = Convert.ToInt32((double)(watermarkImage.Width * num5));
            height = Convert.ToInt32((double)(watermarkImage.Height * num5));
            switch (position)
            {
            case WatermarkPosition.TopLeft:
                x = 10;
                y = 10;
                break;

            case WatermarkPosition.TopRight:
                y = 10;
                x = (image.Width - width) - 10;
                break;

            case WatermarkPosition.BottomLeft:
                x = 10;
                y = (image.Height - height) - 10;
                break;

            case WatermarkPosition.BottomRight:
                x = (image.Width - width) - 10;
                y = (image.Height - height) - 10;
                break;

            case WatermarkPosition.Center:
                x = (image.Width / 2) - (width / 2);
                y = (image.Height / 2) - (height / 2);
                break;
            }
            using (Graphics graphics = Graphics.FromImage(image))
            {
                graphics.DrawImage(watermarkImage, new Rectangle(x, y, width, height), 0, 0, watermarkImage.Width, watermarkImage.Height, GraphicsUnit.Pixel, imageAttr);
            }
            return(image);
        }