现在的位置: 首页 > 综合 > 正文

PicWaterMark小工具

2017年08月17日 ⁄ 综合 ⁄ 共 10006字 ⁄ 字号 评论关闭

网上已经有很多的图片做水印的方法。我主要是做这个工具,主要是以前不太会写没有帮她写,现在会写了(哈哈,其实也是网上Copy)人却走了,人生就是这样一回事。

先看运行界面:

其次是上传图片后效果:

这里文字或者图片的缩略图都一起出现。

上传水印图片:

保存后水印图片:

还有文字水印,不过只能选其中的一种(粗体,斜体,下划线)

如图:

这就是我完成的功能。只是尝试,不知道别人用起来效果怎么样,是用vs2010开发,估计装的时候还要注意用netframewor4呢!哈哈~~

问题及其还需要更新的功能:

1.没有提供保存路径,图片都是默认保存在D:/根目录下。
2.粗体,斜体,下划线暂时只能支持一种。
3.没有去验证水印图片大小和实际制作图片的大小。
4.填写了图片名称,保存添加图片水印或者是添加文字时,同名同类型的图片会被覆盖。
5.颜色只是常用的红,橙,黄,绿,蓝,白,黑。
6.缩略图保存到上传文件相同文件夹下,命名比原名多了mini。
7.没有做预览功能。

8.还有CheckBox分组问题。现在是写事件,在印象中好像只要分组就可以实现的,现在还要写代码,郁闷!

有那位大虾可以指导一下。把问题解决的更加完善。

部分代码:其实网上已经很多了

 #region  保存不同类型的格式的图片和路径
        private void SavePicFormat(Image img, int position, string filename, PictureBox pb)
        {
            SavePicFormat(img, position, filename, pb, "");
        }

        private void SavePicFormat(Image img, int position, string filename, PictureBox pb, string picname)
        {
            // 目标图片名称及全路径  
            string savefilename = filename.Substring(filename.Substring(0, filename.LastIndexOf("\\")).Length + 1).Substring(0, filename.Substring(filename.Substring(0, filename.LastIndexOf("\\")).Length + 1).LastIndexOf("."));

            string name = picname != "" ? picname : savefilename;
            string targetImage = "D:\\" + name;
            string houzhui = "";
            // 保存文件到服务器的文件夹里面 
            switch (cobPicFomart.SelectedIndex)
            {
                case 0:
                    img.Save(targetImage + ".bmp", ImageFormat.Bmp);
                    pb.ImageLocation = targetImage + ".bmp";
                    houzhui = ".bmp";
                    break;
                case 1:
                    img.Save(targetImage + ".jpg", ImageFormat.Jpeg);
                    pb.ImageLocation = targetImage + ".jpg";
                    houzhui = ".jpg";
                    break;
                case 2:
                    img.Save(targetImage + ".png", ImageFormat.Png);
                    pb.ImageLocation = targetImage + ".png";
                    houzhui = ".png";

                    break;
                case 3:
                    img.Save(targetImage + ".gif", ImageFormat.Gif);
                    pb.ImageLocation = targetImage + ".gif";
                    houzhui = ".gif";
                    break;
                default:
                    houzhui = "";
                    break;
            }

            //生成缩略图    
            if (houzhui == string.Empty || houzhui == null)
                MessageBox.Show("请选择相应的格式,再进行存档。");
            else
            {
                targetImage = pb.ImageLocation;
                string newPath = targetImage.Substring(0, targetImage.LastIndexOf("\\")) + "\\mini" + name + houzhui;
                GreateMiniImage(targetImage, newPath, pb);
                MessageBox.Show(String.Format("{0}{1}{2}{3}", "您的图片", name, houzhui, "檔已存檔完成!!!"));
            }
        }
        #endregion

 

    #region 图片文字放置位置
        private int[] PicPosition(ImagePosition watermarkPosition, int phWidth, int phHeight, int wmWidth, int wmHeight)
        {
            int[] position = new int[2];
            switch (watermarkPosition)
            {
                case ImagePosition.BottomMiddle:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.Center:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = (phHeight - wmHeight) / 2;
                    break;
                case ImagePosition.LeftBottom:
                    position[0] = 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    position[0] = 10;
                    position[1] = 10;
                    break;
                case ImagePosition.RightTop:
                    position[0] = phWidth - wmWidth - 10;
                    position[1] = 10;
                    break;
                case ImagePosition.RigthBottom:
                    position[0] = phWidth - wmWidth - 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = 10;
                    break;
                default:
                    position[0] = 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
            }
            return position;
        }

        private float[] PicPosition(ImagePosition watermarkPosition, float phWidth, float phHeight, float wmWidth, float wmHeight)
        {
            float[] position = new float[2];
            switch (watermarkPosition)
            {
                case ImagePosition.BottomMiddle:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.Center:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = (phHeight - wmHeight) / 2;
                    break;
                case ImagePosition.LeftBottom:
                    position[0] = 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    position[0] = 10;
                    position[1] = 10;
                    break;
                case ImagePosition.RightTop:
                    position[0] = phWidth - wmWidth - 10;
                    position[1] = 10;
                    break;
                case ImagePosition.RigthBottom:
                    position[0] = phWidth - wmWidth - 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    position[0] = (phWidth - wmWidth) / 2;
                    position[1] = 10;
                    break;
                default:
                    position[0] = 10;
                    position[1] = phHeight - wmHeight - 10;
                    break;
            }
            return position;
        }

        #endregion

 

#region 生成缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="oldpath">原图片地址</param>
        /// <param name="newpath">新图片地址</param>
        /// <param name="tWidth">缩略图的宽</param>
        /// <param name="tHeight">缩略图的高</param>
        private void GreateMiniImage(string oldpath, string newpath, PictureBox pb)
        {
            int tWidth = pb.Width;
            int tHeight = pb.Height;
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);
                double bl = 1d;
                if ((image.Width <= image.Height) && (tWidth >= tHeight))
                    bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);

                else if ((image.Width > image.Height) && (tWidth < tHeight))
                    bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);

                else
                {
                    if ((image.Width <= image.Height) && (tWidth <= tHeight))
                    {
                        if (image.Height / tHeight >= image.Width / tWidth)
                            bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
                        else
                            bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                    }
                    else
                    {
                        if (image.Height / tHeight >= image.Width / tWidth)
                            bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                        else
                            bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
                    }
                }
                Bitmap b = new Bitmap(image, Convert.ToInt32(image.Width / bl), Convert.ToInt32(image.Height / bl));
                b.Save(newpath);
                pb.ImageLocation = newpath;
                b.Dispose();
                image.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        #endregion

 

   #region 处理文字图片
        private void AddTextToImg(string filename, string word, string font, float size, Color col, bool blod, bool italic, bool underline, float alpha, ImagePosition wordposition)
        {
            //原始图片
            Image imgPhoto = Image.FromFile(filename);
            //获取图片的高和宽
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;
            //建立一个位图需要加水印大小的图片
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
            //设置Bitmap分辨率
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            //Graphics:封装一个 GDI+ 绘图图面。 
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            //设置图形的品质   
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //将我们要添加水印的图片按照原始大小描绘(复制)到图形中   
            grPhoto.DrawImage(
             imgPhoto,                                           //   要添加水印的图片   
             new Rectangle(0, 0, phWidth, phHeight),             //  根据要添加的水印图片的宽和高   
             0,                                                  //  X方向从0点开始描绘   
             0,                                                  // Y方向    
             phWidth,                                            //  X方向描绘长度   
             phHeight,                                           //  Y方向描绘长度   
             GraphicsUnit.Pixel);                                // 描绘的单位,这里用的是像素 

            //字体   
            Font crFont = null;
            //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空   
            SizeF crSize = new SizeF();
            //利用一个循环语句来选择我们要添加文字的型号   
            //直到它的长度比图片的宽度小 
            for (int i = 0; i < word.Length - 1; i++)
            {
                if (blod == true)
                    crFont = new Font(font, size, FontStyle.Bold);
                else if (italic == true)
                    crFont = new Font(font, size, FontStyle.Italic);
                else if (underline == true)
                    crFont = new Font(font, size, FontStyle.Underline);
                else
                    crFont = new Font(font, size);

                //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。   
                crSize = grPhoto.MeasureString(word, crFont);
                // ushort 关键字表示一种整数数据类型   
                if ((ushort)crSize.Width < (ushort)phWidth)
                    break;
            }
            //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)   
            int yPixlesFromBottom = (int)(phHeight * .05);
            float[] wordPosition = PicPosition(wordposition, phWidth, phHeight, crSize.Width, crSize.Height);
            float xPosOfWm = float.Parse(wordPosition[0].ToString());
            float yPosOfWm = float.Parse(wordPosition[1].ToString());

            //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。   
            StringFormat StrFormat = new StringFormat();
            //定义需要印的文字居中对齐   
            StrFormat.Alignment = StringAlignment.Center;

            //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。   
            //这个画笔为描绘阴影的画笔,呈灰色   
            int m_alpha = Convert.ToInt32(255 * alpha);
            SolidBrush writeBrush = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));

            //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果   
            //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。   
            grPhoto.DrawString(word,                                    //string of text   
                                       crFont,                                         //font   
                                       writeBrush,                            //Brush   
                                       new PointF(xPosOfWm + 1, yPosOfWm + 1),  //Position   
                                       StrFormat);

            //从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153   
            //这个画笔为描绘正式文字的笔刷,呈白色   
            SolidBrush blackBrush = new SolidBrush(col);

            //第二次绘制这个图形,建立在第一次描绘的基础上   
            grPhoto.DrawString(word,                 //string of text   
                                       crFont,                                   //font   
                                       blackBrush,                           //Brush   
                                       new PointF(xPosOfWm, yPosOfWm),  //Position   
                                       StrFormat);

            grPhoto.Dispose();
            SavePicFormat(bmPhoto, cobPicFomart.SelectedIndex, filename, pbWordWaterMark, txtPicName.Text);
            imgPhoto.Dispose();
        }
         #endregion

 

   #region 处理图片水印
        private void addPicToImg(string filename, string watermarkfilename, ImagePosition watermarkPosition, int width, int height, float alpha)
        {
            //原始图片
            Image imgPhoto = Image.FromFile(filename);

            // 确定其长宽   
            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);

            //水印图片 将水印图片装载到一个绘图画面grWatermark 
            Image imgWatermark = new Bitmap(watermarkfilename);

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

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

            // 第一次描绘,将我们的底图描绘在绘图画面上 
            //grPhoto.Clear(Color.White);
            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 colorMatrix = new ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);


            //上面设置完颜色,下面开始设置位置 
            int[] position = PicPosition(watermarkPosition, phWidth, phHeight, wmWidth, wmHeight);
            int xPosOfWm = position[0];
            int yPosOfWm = position[1];

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

            grPhoto.Dispose();
            grWatermark.Dispose();

            SavePicFormat(imgPhoto, cobPicFomart.SelectedIndex, filename, pbPicWaterMark, txtPicName.Text);

            imgPhoto.Dispose();
            imgWatermark.Dispose();
        }
        #endregion

菜鸟认真的学习,不要笑话哦~~~~~~

 

 

 

抱歉!评论已关闭.