C#实现水印与图片合成,并利用Graphics压缩图像质量

发布时间:2017-09-22编辑:佚名阅读(2105)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Threading;
namespace FontDemo
{
    public partial class MarkImage : Form
    {
        //使用方法:
        //在软件根目录放水印图片,命名为“ddK.png”
        //在软件根目录下的img文件夹放要添加水印的图片
        //在软件根目录下的imgbak文件夹为合成后输出文件夹
        int i = 0;
        public MarkImage()
        {
            InitializeComponent();
        }
        private void MarkImage_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 保存图片 " 图片水印 " 
        /// </summary>
        /// <param name="InUploadImagePath">原服务器图片路径</param>
        ///<param name="inLogoImagePath">生成的带图片水印的图片路径</param>
        ///<param name="InSavePath">水印图片路径</param>
        ///<param name="strType">原图片文件类型</param>
        public void MarkToImage(string InUploadImagePath, string inLogoImagePath, string InSavePath, string strType)
        {
            //FileStream fs = new FileStream(System.Windows.Forms.Application.StartupPath + @"\Img\" + InUploadImagePath, FileMode.Open, FileAccess.ReadWrite);
            //System.Drawing.Image img = System.Drawing.Image.FromStream(fs, false, false);
            //Bitmap bmp = new Bitmap(img);
            //img.Dispose();
            //fs.Close();
            //System.Drawing.Image Image = bmp;
            //System.Drawing.Image newimage = System.Drawing.Image.FromFile(System.Windows.Forms.Application.StartupPath + @"\" + inLogoImagePath);
            //Graphics g = Graphics.FromImage(Image);
            //g.DrawImage(newimage, new Rectangle(Image.Width - newimage.Width, Image.Height - newimage.Height, newimage.Width, newimage.Height), 0, 0, newimage.Width, newimage.Height, GraphicsUnit.Pixel);
            //System.Drawing.Image Image = System.Drawing.Image.FromFile(System.Windows.Forms.Application.StartupPath + @"\Img\" +InUploadImagePath);
            //System.Drawing.Image newimage = System.Drawing.Image.FromFile(System.Windows.Forms.Application.StartupPath + @"\" +inLogoImagePath);
            //Graphics g = Graphics.FromImage(Image);
            //g.DrawImage(newimage, new Rectangle(Image.Width - newimage.Width, Image.Height - newimage.Height, newimage.Width, newimage.Height), 0, 0, newimage.Width, newimage.Height, GraphicsUnit.Pixel);
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            //Image.Save(System.Windows.Forms.Application.StartupPath + @"\ImgBak\" + InSavePath);
            //string pith = "C:\\Documents and Settings\\Administrator\\桌面\\临时目录\\IMg-09-07-21\\FontDemo\\FontDemo\\bin\\Debug\\ImgBak\\" + InSavePath;
            //Image.Save(pith);
            //System.Windows.Forms.Application.StartupPath = "C:\\Documents and Settings\\Administrator\\桌面\\临时目录\\IMg-09-07-21\\FontDemo\\FontDemo\\bin\\Debug"
            Bitmap imgTemp = new Bitmap(System.Windows.Forms.Application.StartupPath + @"\Img\" + InUploadImagePath);//创建Image对象,大小为200 * 200
            Graphics gType = Graphics.FromImage(imgTemp);//在Image对象上创建Graphics对象g2
            GraphicsPath typePath = new GraphicsPath();
            Bitmap img = new Bitmap(System.Windows.Forms.Application.StartupPath + @"\" + inLogoImagePath);//创建Image对象,大小为200 * 200
            try
            {
                //gType.DrawImage(img, 590, 1100, img.Width, img.Height);
                gType.DrawImage(img, new Rectangle(imgTemp.Width - img.Width, imgTemp.Height - img.Height, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                string ps = System.Windows.Forms.Application.StartupPath + @"\ImgBak\" + InUploadImagePath;
                imgTemp.Save(ps, System.Drawing.Imaging.ImageFormat.Png);
                
                
               
            }
            catch (Exception de)
            {
                MessageBox.Show(de.Message);
            }
            finally
            {
                //MyItem item1 = new MyItem();
                //item1.id = i.ToString();
                //item1.name = InUploadImagePath + " - 已生成..";
                //i++;
                //this.listBox1.Items.Add(item1);
                //this.pictureBox1.Image = imgTemp;
                typePath.Dispose();
                imgTemp.Dispose();
                img.Dispose();
                //newimage.Dispose();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            MethodInvoker mi = new MethodInvoker(Add);
            mi.BeginInvoke(nullnull);   
             
                
         }
        public  class MyItem : object
        {
            public  string name;
            public  string id;
            public override string ToString()
            {
                // TODO:   添加 MyItem.ToString 实现
                return name;
            }
        }
        public delegate void delegateMethod(string fileName, Bitmap imgTem);
        public void Add()
        {
            DelegateChangeButton bu = new DelegateChangeButton(ButtonEnable);
            this.BeginInvoke(bu, new object[] { false });
            
            string sd = AppDomain.CurrentDomain.BaseDirectory + "Img";
            string[] files = Directory.GetFiles(sd);
            foreach (string in files)
            {
                if (f.LastIndexOf("\\") != -1)
                {
                    string strFile = f.Substring(f.LastIndexOf("\\") + 1);
                    string strType = strFile.Substring(strFile.Length - 3, 3);
                    if (strType.ToLower() == "bmp" || strType.ToLower() == "png" || strType.ToLower() == "jpg")
                    {              
                        Bitmap imgTemp = new Bitmap(System.Windows.Forms.Application.StartupPath + @"\Img\" + strFile);//创建Image对象,大小为200 * 200
                        Graphics gType = Graphics.FromImage(imgTemp);//在Image对象上创建Graphics对象g2
                        GraphicsPath typePath = new GraphicsPath();
                        Bitmap img = new Bitmap(System.Windows.Forms.Application.StartupPath + @"\" + "ddK.png");//创建Image对象,大小为200 * 200
                        if (imgTemp.Width >= 400 && imgTemp.Height >= 150)
                        {
                            try
                            {
                                ////EncoderParameter p;
                                ////EncoderParameters ps;
                                ////ps = new EncoderParameters(1);
                                ////p = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.CompressionLZW);
                                ////ps.Param[0] = p;
                                 
                                ////gType.DrawImage(img, new Rectangle(imgTemp.Width - img.Width, imgTemp.Height - img.Height, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                                ////gType.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                ////gType.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                ////gType.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                                ////string pngB = System.Windows.Forms.Application.StartupPath + @"\ImgBak\" + strFile;
                                ////imgTemp.Save(pngB, GetCodecInfo("image/bmp"), ps);
                                //EncoderParameter p;
                                //EncoderParameters ps;
                                //ps = new EncoderParameters(1);
                        
                                ////p = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionRle);
                                //long sdd = (long)EncoderValue.CompressionRle;
                                //p = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.TransformRotate270);
                                //ps.Param[0] = p;
                                gType.DrawImage(img, new Rectangle(imgTemp.Width - img.Width, imgTemp.Height - img.Height, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                                //gType.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                //gType.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                //gType.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                                string pngB = System.Windows.Forms.Application.StartupPath + @"\ImgBak\" + strFile;
                                //imgTemp.Save(pngB, GetCodecInfo("image/jpeg"), ps);
                                //imgTemp.Save(pngB, System.Drawing.Imaging.ImageFormat.Png);
                                EncoderParameters encoderParams = new EncoderParameters();
                                long[] quality = new long[1];
                                quality[0] = 92; //压缩比例,决定图片大小的重要因素。
                                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                                encoderParams.Param[0] = encoderParam;
                                
                                imgTemp.Save(System.Windows.Forms.Application.StartupPath + @"\ImgBak\" + strFile, GetCodecInfo("image/jpeg"), encoderParams);
                                if (listBox1.InvokeRequired)
                                {
                                    delegateMethod m = new delegateMethod(Referesh);
                                    this.BeginInvoke(m, new object[] { strFile, imgTemp });
                                }
                                else
                                {
                                    Referesh(strFile, imgTemp);
                                }
                                Thread.Sleep(100);
                                //EncoderParameters encoderParams = new EncoderParameters();
                                //long[] quality = new long[1];
                                //quality[0] = 90;
                                //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                                //encoderParams.Param[0] = encoderParam;
                                //Bitmap imgLast = new Bitmap(pngB);//创建Image对象
                                //imgLast.Save(System.Windows.Forms.Application.StartupPath + @"\images\" + strFile, GetCodecInfo("image/jpeg"), encoderParams);
                               // SmallPic(pngB, System.Windows.Forms.Application.StartupPath + @"\images\" + strFile, imgTemp.Width, imgTemp.Height);
                            }
                            catch (Exception de)
                            {
                                MessageBox.Show(de.Message);
                            }
                            finally
                            {
                                typePath.Dispose();
                                //imgTemp.Dispose();
                                //img.Dispose();
                            }
                        }
                    }
                }
            }
            delegateMethodEND en = new delegateMethodEND(EndList);
            this.BeginInvoke(en);
            this.BeginInvoke(bu, new object[] { true });
        }
         /**//// <summary>
        /// 保存JPG时用
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns>得到指定mimeType的ImageCodecInfo</returns>
        private  ImageCodecInfo GetCodecInfo(string mimeType)
        {
             ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
             }
            return null;
         }
        public void ButtonEnable(bool flag)
        {
            this.button1.Enabled = flag;
        }
        public void Referesh(string fileName, Bitmap imgTem)
        {
            listBox1.Items.Add(DateTime.Now.ToShortTimeString() + @"分 - ImgBak\" + fileName + "  已生成");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
            this.pictureBox1.Image = imgTem;
            Application.DoEvents();
        }
        public void EndList()
        {
            listBox1.Items.Add(DateTime.Now.ToShortTimeString() + @"分  -网站所有水印图生成结束!");
            listBox1.SelectedIndex = listBox1.Items.Count - 1;     
            
        }
        public delegate void delegateMethodEND();
        public delegate void DelegateChangeButton(bool flag);
        //public delegate void DelegateChangeIMG(Bitmap imgTem); 
        public  bool SmallPic(string strOldPic, string strNewPic, int widthEx, int heightEx)
        {//提供原始图片,目标路径,以及想要生成的缩略图尺寸
            System.Drawing.Bitmap objPic, objNewPic;
            objPic = new System.Drawing.Bitmap(strOldPic);
            int width, height;
            width = objPic.Width;
            height = objPic.Height;
            if ((int)(height / heightEx) >= (int)(width / widthEx))
            {//高度压缩比例大于宽度
                SmallPicW(strOldPic, strNewPic, heightEx, widthEx);
                objPic.Dispose();
                return true;
            }
            else
            {//高度压缩比例小于宽度
                SmallPicH(strOldPic, strNewPic, widthEx, heightEx);
                objPic.Dispose();
                return true;
            }
        }
        ///下面这个函数处理高度压缩比例小于宽度的情况
        private  void SmallPicH(string strOldPic, string strNewPic, int intWidth, int descHeight)
        {
            System.Drawing.Bitmap objPic, smallObjPic, objNewPic;
            objPic = null;
            objNewPic = null;
            smallObjPic = null;
            try
            {
                objPic = new System.Drawing.Bitmap(strOldPic);
                //将原始图片放入到内存里 
                int intHeight = (intWidth * objPic.Height) / objPic.Width;
                smallObjPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);
                objNewPic = new System.Drawing.Bitmap(intWidth, descHeight, PixelFormat.Format64bppPArgb);
                //在内存里生成一张跟缩略图尺寸一样的空图片。
                objNewPic.SetResolution(objPic.HorizontalResolution, objPic.VerticalResolution);
                Graphics grPhoto = Graphics.FromImage(objNewPic);
                if (objPic.Width < intWidth)
                {
                    grPhoto.FillRectangle(System.Drawing.Brushes.White, 0, 0, intWidth, descHeight);
                    grPhoto.DrawImage(smallObjPic, new Rectangle((intWidth - objPic.Width) / 2,
                    (descHeight - objPic.Height) / 2, objPic.Width, objPic.Height));
                }
                else
                {
                    grPhoto.FillRectangle(System.Drawing.Brushes.White, 0, 0, intWidth, descHeight);
                    grPhoto.DrawImage(smallObjPic, new Rectangle(0, (descHeight - intHeight) / 2, intWidth, intHeight)
                    , 0, 0, intWidth, intHeight, System.Drawing.GraphicsUnit.Pixel);
                }
                #region  保存图片
                EncoderParameters encoderParams = new EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 90;
                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                //获得包含对应的图片编解码程序 
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICI = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x];//
                        break;
                    }
                }
                if (jpegICI != null)
                {
                    objNewPic.Save(strNewPic, jpegICI, encoderParams);
                }
                else
                {
                    objNewPic.Save(strNewPic, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                objPic.Dispose();
                objPic = null;
                objNewPic.Dispose();
                objNewPic = null;
                smallObjPic.Dispose();
                smallObjPic = null;
                #endregion
            }
            catch (Exception exp)
            {
            }
            finally
            {
                if (objPic != null)
                    objPic.Dispose();
                if (objNewPic != null)
                    objNewPic.Dispose();
                if (smallObjPic != null)
                    smallObjPic.Dispose();
                objPic = null;
                objNewPic = null;
                smallObjPic = null;
            }
        }
        ///以下函数是处理高度压缩比例大于宽度的情况
        private  void SmallPicW(string strOldPic, string strNewPic, int intHeight, int descWidth)
        {
            System.Drawing.Bitmap objPic, smallObjPic, objNewPic;
            objPic = null;
            objNewPic = null;
            smallObjPic = null;
            try
            {
                objPic = new System.Drawing.Bitmap(strOldPic);
                int intWidth = (intHeight * objPic.Width) / objPic.Height;
                smallObjPic = new System.Drawing.Bitmap(objPic, intWidth, intHeight);
                objNewPic = new System.Drawing.Bitmap(descWidth, intHeight, PixelFormat.Format64bppPArgb);
                objNewPic.SetResolution(objPic.HorizontalResolution, objPic.VerticalResolution);
                Graphics grPhoto = Graphics.FromImage(objNewPic);
                if (objPic.Height < intHeight)
                {//
                    grPhoto.FillRectangle(System.Drawing.Brushes.White, 0, 0, descWidth, intHeight);
                    Rectangle r = new Rectangle((descWidth - objPic.Width) / 2, (intHeight - objPic.Height) / 2,
                    intWidth, objPic.Height);
                    grPhoto.DrawImage(smallObjPic, r);
                }
                else
                {
                    grPhoto.FillRectangle(System.Drawing.Brushes.White, 0, 0, descWidth, intHeight);
                    grPhoto.DrawImage(smallObjPic, new Rectangle((descWidth - intWidth) / 2, 0, intWidth, intHeight),
                    0, 0, intWidth, intHeight, System.Drawing.GraphicsUnit.Pixel);
                }
                #region
                EncoderParameters encoderParams = new EncoderParameters();
                long[] quality = new long[1];
                quality[0] = 90;
                EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                encoderParams.Param[0] = encoderParam;
                // 
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICI = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICI = arrayICI[x];//
                        break;
                    }
                }
                if (jpegICI != null)
                {
                    objNewPic.Save(strNewPic, jpegICI, encoderParams);
                }
                else
                {
                    objNewPic.Save(strNewPic, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                objPic.Dispose();
                objPic = null;
                objNewPic.Dispose();
                objNewPic = null;
                smallObjPic.Dispose();
                smallObjPic = null;
                #endregion
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (objPic != null)
                    objPic.Dispose();
                if (objNewPic != null)
                    objNewPic.Dispose();
                if (smallObjPic != null)
                    smallObjPic.Dispose();
                objPic = null;
                smallObjPic = null;
                objNewPic = null;
            }
        }
    }
}


    关键字: C# 水印 图片 合成 Graphics 压缩 图像质量


鼓掌

0

正能量

0

0

呵呵

0


评论区