C# 图片上附加文字水印 并生成新的二维码图片

  1  /// <summary>  
  2         /// 在图片上添加水印文字  
  3         /// </summary>  
  4         /// <param name="sourcePicture">源图片文件  @"H:\数据抓取\BrandCheckData\ConsoleApp1\PDF\Test.pdf"</param>  
  5         /// <param name="keyword">需要添加到图片上的文字</param>  
  6         /// <param name="position">位置</param>  
  7         /// <returns></returns>  
  8         public static UploadResult DrawWords(string sourcePicture, string[] keyword, ImagePosition position)
  9         {
 10             if (!File.Exists(sourcePicture))
 11             {
 12                 throw new DMSFrame.Exception.WarnException("亲!证书原图片不存在,请先上传模板图片!");
 13             }
 14 
 15             //创建一个图片对象用来装载要被添加水印的图片  
 16             Image imgPhoto = Image.FromFile(sourcePicture);
 17 
 18             //获取图片的宽和高  
 19             int phWidth = imgPhoto.Width;
 20             int phHeight = imgPhoto.Height;
 21             //  
 22             //建立一个bitmap,和我们需要加水印的图片一样大小  
 23             Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
 24 
 25             //SetResolution:设置此 Bitmap 的分辨率  
 26             //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap  
 27             bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
 28 
 29             //Graphics:封装一个 GDI+ 绘图图面。  
 30             Graphics grPhoto = Graphics.FromImage(bmPhoto);
 31 
 32             //设置图形的品质  
 33             grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
 34 
 35             //将我们要添加水印的图片按照原始大小描绘(复制)到图形中  
 36             grPhoto.DrawImage(
 37              imgPhoto,                                           //   要添加水印的图片  
 38              new Rectangle(0, 0, phWidth, phHeight), //  根据要添加的水印图片的宽和高  
 39              0,                                                     //  X方向从0点开始描绘  
 40              0,                                                     // Y方向   
 41              phWidth,                                            //  X方向描绘长度  
 42              phHeight,                                           //  Y方向描绘长度  
 43              GraphicsUnit.Pixel);                              // 描绘的单位,这里用的是像素  
 44 
 45 
 46             //字体  
 47             Font crFont = null;
 48             //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空  
 49             SizeF crSize = new SizeF();
 50 
 51             int length = keyword[1].Length - 15;
 52             int companynamesize = Convert.ToInt32(Math.Ceiling(length / 5.0));
 53             int num = 35;
 54             if (companynamesize > 0)
 55                 num = num - companynamesize * 5;
 56 
 57             if (num <= 20)
 58                 num = 20;
 59 
 60             crFont = new Font("微软雅黑", num, FontStyle.Bold);
 61 
 62 
 63             //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。  
 64             crSize = grPhoto.MeasureString(keyword[0], crFont);
 65 
 66             //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)  
 67             int yPixlesFromBottom = (int)(phHeight * .05);
 68 
 69             //定义在图片上文字的位置  
 70             float wmHeight = crSize.Height;
 71             float wmWidth = crSize.Width;
 72 
 73             float xPosOfWm;
 74             float yPosOfWm;
 75 
 76             switch (position)
 77             {
 78                 case ImagePosition.BottomMiddle:
 79                     xPosOfWm = phWidth / 2;
 80                     yPosOfWm = phHeight - wmHeight - 10;
 81                     break;
 82                 case ImagePosition.Center:
 83                     xPosOfWm = phWidth / 2;
 84                     yPosOfWm = phHeight / 2;
 85                     break;
 86                 case ImagePosition.LeftBottom:
 87                     xPosOfWm = wmWidth;
 88                     yPosOfWm = phHeight - wmHeight - 10;
 89                     break;
 90                 case ImagePosition.LeftTop:
 91                     xPosOfWm = wmWidth / 2;
 92                     yPosOfWm = wmHeight / 2;
 93                     break;
 94                 case ImagePosition.RightTop:
 95                     xPosOfWm = phWidth - wmWidth - 10;
 96                     yPosOfWm = wmHeight;
 97                     break;
 98                 case ImagePosition.RigthBottom:
 99                     xPosOfWm = phWidth - wmWidth - 10;
100                     yPosOfWm = phHeight - wmHeight - 10;
101                     break;
102                 case ImagePosition.TopMiddle:
103                     xPosOfWm = phWidth / 2;
104                     yPosOfWm = wmWidth;
105                     break;
106                 default:
107                     xPosOfWm = wmWidth;
108                     yPosOfWm = phHeight - wmHeight - 10;
109                     break;
110             }
111 
112             //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。  
113             StringFormat StrFormat = new StringFormat();
114 
115             //定义需要印的文字居中对齐  
116             StrFormat.Alignment = StringAlignment.Center;
117             Brush whiteBrush = new SolidBrush(Color.Black);
118 
119             grPhoto.DrawString("认证编号:" + keyword[0] + "",
120                                      new Font("微软雅黑", 15),
121                                      whiteBrush,
122                                      new PointF(xPosOfWm, yPosOfWm - 300),
123                                      StrFormat);
124 
125             grPhoto.DrawString(keyword[1],
126                                        crFont,
127                                        whiteBrush,
128                                        new PointF(xPosOfWm, yPosOfWm),
129                                        StrFormat);
130 
131 
132             grPhoto.DrawString("认证时效:" + keyword[2] + "",
133                                      new Font("微软雅黑", 15),
134                                      whiteBrush,
135                                      new PointF(xPosOfWm, yPosOfWm + 250),
136                                      StrFormat);
137 
138             grPhoto.DrawString("认证年限:" + keyword[3] + "",
139                                     new Font("微软雅黑", 15),
140                                     whiteBrush,
141                                     new PointF(xPosOfWm, yPosOfWm + 350),
142                                     StrFormat);
143 
144 
145             //imgPhoto是我们建立的用来装载最终图形的Image对象  
146             //bmPhoto是我们用来制作图形的容器,为Bitmap对象  
147             imgPhoto = bmPhoto;
148             //释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满  
149             grPhoto.Dispose();
150 
151             //也可以将图片保存到本地
152             //string newPath = @"D:\InfinigoImg" + "\\" + 23324233 + ".png";
153             //imgPhoto.Save(newPath, System.Drawing.Imaging.ImageFormat.Png);
154 
155             try
156             {
157                 MemoryStream ms = new MemoryStream();
158                 imgPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
159                 UploadFile file = new UploadFile();
160                 FileM info = new FileM() { FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png", FileStream = ms, FileType = 1 };
161                 var result = file.UploadToFDFS(info);
162                 if (result.IsSuccessed)
163                 {
164                     //合成的文字图片
165                     string imgpath = result.DomainName + result.FileUrl;
166                     if (!string.IsNullOrEmpty(imgpath))
167                     {
168                         //网页图片地址方法 此图片合成为二维码图片,附加到主图上面
169                         return ImgAndCodeSynthetic(imgpath, keyword[0]);
170 
171                         #region
172                         // 从本地读取图片合成方法,此图片合成为二维码图片,附加到主图上面
173                         //QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
174                         //qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
175                         //qrCodeEncoder.QRCodeScale = 4;
176                         //qrCodeEncoder.QRCodeVersion = 0;
177                         //qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
178                         //System.Drawing.Image image = qrCodeEncoder.Encode(imgpath);
179                         //MemoryStream qccodems = new MemoryStream();
180                         //image.Save(qccodems, System.Drawing.Imaging.ImageFormat.Png);
181                         //UploadFile qccodefile = new UploadFile();
182                         //FileM qccodeinfo = new FileM() { FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png", FileStream = qccodems };
183                         //var qccoderesult = qccodefile.UploadToFDFS(qccodeinfo);
184                         //if (qccoderesult.IsSuccessed)
185                         //{
186                         //    //图片生成二维码图片
187                         //    string qccodeimgpath = qccoderesult.DomainName + qccoderesult.FileUrl;
188                         //    if (!string.IsNullOrEmpty(qccodeimgpath))
189                         //    {
190                         //        //二维码和图片合成啦
191                         //        return ImgAndCodeSynthetic(qccodeimgpath, keyword[0]);
192                         //    }
193                         //}
194                         #endregion
195                     }
196 
197                 }
198                 //输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
199                 //Response.Clear();
200                 //Response.ContentType = "image/jpeg";
201                 //Response.BinaryWrite(ms.ToArray());
202             }
203             catch (Exception ex)
204             {
205                 throw new DMSFrame.Exception.WarnException("出错啦!" + ex.Message + "");
206             }
207             return null;
208         }
209 
210 
211         /// <summary>
212         /// 生成二维码图片
213         /// </summary>
214         /// <param name="url">网址</param>
215         /// <returns></returns>
216         public static Image QcCodeCreate(string url)
217         {
218             QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
219             qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
220             qrCodeEncoder.QRCodeScale = 4;
221             qrCodeEncoder.QRCodeVersion = 0;
222             qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
223             System.Drawing.Image image = qrCodeEncoder.Encode(url);
224             return image;
225         }
226 
227         /// <summary>
228         ///  图片和二维码合成
229         /// </summary>
230         /// <param name="originalimg">二维码主图:原图</param>
231         /// <returns></returns>
232         public static UploadResult ImgAndCodeSynthetic(string originalimg, string authnumber)
233         {
234             string url = "http://m.hqew.com/ISCPAuthCenter/Index?keywords=" + authnumber;
235 
236             //测试地址
237             // string url = "http://m.hqenet.com/ISCPAuthCenter/Index?keywords=PPRZ0032020111611";
238 
239             System.Drawing.Image image = QcCodeCreate(url);
240             System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();
241             Image img = CombinImage(image, originalimg);
242 
243             //将图片存为文件流
244             img.Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);
245 
246             //或者直接保存到本地文件夹
247             //string newPath = @"D:\InfinigoImg" + "\\" + 23324233 + ".png";
248             //img.Save(newPath, System.Drawing.Imaging.ImageFormat.Png);
249 
250             //第一种方案:传到服务器中
251             UploadFile syntheticfile = new UploadFile();
252             FileM syntheticinfo = new FileM() { FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png", FileStream = MStream1, FileType = 1 };
253             var syntheticresult = syntheticfile.UploadToFDFS(syntheticinfo);
254 
255             MStream1.Dispose();
256             return syntheticresult;
257         }
258 
259         /// <summary>
260         /// 第二张图片 需要插入第一张图片中,此方法调整二维码图片在主图中的位置
261         /// </summary>
262         /// <param name="imgBack">二维码副图</param>
263         /// <param name="destImg">主图</param>
264         /// <returns></returns>
265         public static Image CombinImage(Image imgBack, string destImg)
266         {
267             Image img = GetPictureImage(destImg);
268             //调整二维码图片大小
269             if (imgBack.Height != 200 || imgBack.Width != 200)
270             {
271                 imgBack = KiResizeImage(imgBack, 150, 150, 0);
272             }
273             Graphics g = Graphics.FromImage(img);
274             g.DrawImage(img, 0, 0, img.Width, img.Height);   //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
275             g.FillRectangle(System.Drawing.Brushes.Black, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1, 1, 1);//相片四周刷一层黑色边框
276             //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
277             g.DrawImage(imgBack, (img.Width / 2 - imgBack.Width / 2) - 150, (img.Height - (img.Height / 6) - imgBack.Height / 2) - 10, imgBack.Width, imgBack.Height);
278             GC.Collect();
279             return img;
280         }
281 
282         /// <summary>
283         /// 通过Url获取到Image
284         /// </summary>
285         /// <param name="Url"></param>
286         /// <returns></returns>
287         public static Image GetPictureImage(string Url)
288         {
289             WebRequest webreq = WebRequest.Create(Url);
290             WebResponse webres = webreq.GetResponse();
291             using (Stream stream = webres.GetResponseStream())
292             {
293                 return System.Drawing.Image.FromStream(stream);
294             }
295         }
296 
297         /// <summary>
298         /// 
299         /// </summary>
300         /// <param name="bmp"></param>
301         /// <param name="newW"></param>
302         /// <param name="newH"></param>
303         /// <param name="Mode"></param>
304         /// <returns></returns>
305         public static Image KiResizeImage(Image bmp, int newW, int newH, int Mode)
306         {
307             try
308             {
309                 Image b = new Bitmap(newW, newH);
310                 Graphics g = Graphics.FromImage(b);
311                 // 插值算法的质量
312                 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
313                 g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
314                 g.Dispose();
315                 return b;
316             }
317             catch
318             {
319                 return null;
320             }
321         }
C# 图片上附加文字水印 并生成新的二维码图片
  1  /// <summary>
  2     /// 文件上传参数
  3     /// </summary>
  4     public class FileM
  5     {
  6         /// <summary>
  7         /// 文件流
  8         /// </summary>
  9         public Stream FileStream { get; set; }
 10 
 11         /// <summary>
 12         /// 文件名称
 13         /// </summary>
 14         public string FileName { get; set; }
 15         /// <summary>
 16         /// 大小限制,单位KB
 17         /// </summary>
 18         public int MaxSize { get; set; }
 19 
 20         /// <summary>
 21         /// 文件类型
 22         /// </summary>
 23         public int FileType { get; set; }
 24 
 25         /// <summary>
 26         /// 是否进行图片识别
 27         /// </summary>
 28         public bool IsOCR { get; set; }
 29 
 30         /// <summary>
 31         /// 保存类型 0-fastdfs 1-共享文件夹
 32         /// </summary>
 33         public short StorageType { get; set; }
 34 
 35         /// <summary>
 36         /// 水印文字
 37         /// </summary>
 38         public string WaterMarkText;
 39         /// <summary>
 40         /// 字号
 41         /// </summary>
 42         public int Fontsize;
 43         /// <summary>
 44         /// 水印位置
 45         /// </summary>
 46         public int Position;
 47         /// <summary>
 48         /// 字体颜色
 49         /// </summary>
 50         public string Color;
 51         /// <summary>
 52         ///  0 没有使用水印(界面没有引用水印) 1 启用水印 2 关闭水印
 53         /// </summary>
 54         public short IsOpenWaterMark;
 55 
 56         /// <summary>
 57         /// 保存共享文件夹路径 在cts后台配置中心-其他配置  设置
 58         /// </summary>
 59         public string FilePathKey { get; set; }
 60     }
 61 
 62     public class UploadResult
 63     {
 64         public bool IsSuccessed { get; set; }
 65 
 66         public string DomainName { get; set; }
 67 
 68         public string FileUrl { get; set; }
 69 
 70         public string ErrorMsg { get; set; }
 71     }
 72 
 73     /// <summary>
 74     /// 文件上传类
 75     /// </summary>
 76     public class UploadFile
 77     {
 78         //图片上传过滤器设置
 79         private int _allowSize = 2 * 1024;
 80         private string _allowType = "|.jpg|.gif|.bmp|.png|.jpeg|";
 81 
 82         //文件上传过滤器设置
 83         private int _fileAllowSize = 10 * 1024;
 84         private string _fileAllowType = "|.jpg|.gif|.bmp|.png|.jpeg|.rar|.zip|.pdf|.txt|.csv|.Csv|.xls|.xlsx|.doc|.docx|.ppt|.pptx|.dmp|";
 85 
 86         /// <summary>
 87         /// 
 88         /// </summary>
 89         /// <param name="fileInfo"></param>
 90         /// <returns></returns>
 91         public UploadResult UploadToFDFS(FileM fileInfo)
 92         {
 93             UploadResult rtnResut = new UploadResult
 94             {
 95                 IsSuccessed = false
 96             };
 97             if (fileInfo.FileStream != null)
 98             {
 99                 int fileCheckFlag = CheckFile(fileInfo);
100                 if (fileCheckFlag == 0)
101                 {
102                     string fileExt = fileInfo.FileName.Substring(fileInfo.FileName.LastIndexOf('.') + 1);
103                     string domainName = FastDFS.Client.FastDFSClient.GetDomains().Split(',')[0];
104                     FastDFS.Client.FDFSResult result = FastDFS.Client.FastDFSClient.UploadFile(fileInfo.FileStream, fileExt);
105 
106                     if (result.StatusCode == "200")
107                     {
108                         rtnResut.IsSuccessed = true;
109                         rtnResut.DomainName = domainName;
110                         rtnResut.FileUrl = result.FileIndex;
111                     }
112                     else
113                     {
114                         rtnResut.ErrorMsg = result.ErrorMsg;
115                     }
116                 }
117                 else
118                 {
119                     switch (fileCheckFlag)
120                     {
121                         case 2:
122                             rtnResut.ErrorMsg = "文件格式不正确";
123                             break;
124                         case 3:
125                             rtnResut.ErrorMsg = "文件大小不正确";
126                             break;
127                         default:
128                             rtnResut.ErrorMsg = "上传失败";
129                             break;
130                     }
131 
132                 }
133             }
134 
135             return rtnResut;
136         }
137 
138 
139 
140         /// <summary>
141         /// 文件上传
142         /// </summary>
143         /// <returns></returns>
144         public string Load(FileM fileInfo)
145         {
146             if (fileInfo.FileStream != null)
147             {
148                 int fileCheckFlag = CheckFile(fileInfo);
149                 if (fileCheckFlag == 0)
150                 {
151                     string fileExt = Path.GetExtension(fileInfo.FileName).ToLower();
152                     string domainName = string.Empty, fileUrl = string.Empty, path = string.Empty;
153                     if (fileInfo.StorageType == 1)
154                     {
155                         //Random rd = new Random();
156                         //DateTime nowTime = DateTime.Now;
157                         //string newFileName =  nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + fileExt;
158                         string newFileName = Guid.NewGuid().ToString("N") + fileExt;
159 
160                         if (!string.IsNullOrEmpty(fileInfo.FilePathKey))
161                         {
162                             if (DMSFrame.ConfigThrift.TClient.Instance.Geting(fileInfo.FilePathKey, ConfigType.Other) is OtherConfig config)
163                             {
164                                 if (!string.IsNullOrEmpty(config.Value1))
165                                     path = config.Value1;
166                                 if (!string.IsNullOrEmpty(config.Value2))
167                                     domainName = config.Value2;
168                                 if (!string.IsNullOrEmpty(config.Value3))
169                                     fileUrl = config.Value3 + newFileName;
170                             }
171                         }
172                         //path 为空 默认取file_hqew_temp路径
173                         if (string.IsNullOrEmpty(path))
174                             path = FileHandler.Instance.GetDirectoryPath("file_hqew_temp");
175                         if (!System.IO.Directory.Exists(path))
176                             System.IO.Directory.CreateDirectory(path);
177                         if (string.IsNullOrEmpty(domainName))
178                             domainName = FileHandler.Instance.ImagePath;
179                         if (string.IsNullOrEmpty(fileUrl))
180                             fileUrl = "/file/temp/" + newFileName;
181 
182                         string saveFile = path + "\\" + newFileName;
183                         FileStream aFile = new FileStream(saveFile, FileMode.CreateNew, FileAccess.ReadWrite);
184                         fileInfo.FileStream.Position = 0;
185                         fileInfo.FileStream.CopyTo(aFile);
186                         fileInfo.FileStream.Close();
187                         fileInfo.FileStream.Dispose();
188                         aFile.Flush();
189                         aFile.Close();
190                         aFile.Dispose();
191                     }
192                     else
193                     {
194                         FastDFS.Client.FDFSResult result = new FastDFS.Client.FDFSResult();
195                         if (!string.IsNullOrEmpty(fileInfo.WaterMarkText) && fileInfo.IsOpenWaterMark == 1)
196                         {
197                             System.Drawing.Image img = System.Drawing.Image.FromStream(fileInfo.FileStream);
198                             System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, img.Width, img.Height);
199                             using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
200                             {
201                                 System.Drawing.Font font = new System.Drawing.Font("微软雅黑", fileInfo.Fontsize);
202                                 //16进制颜色转换为RGB
203                                 var color = System.Drawing.ColorTranslator.FromHtml("#" + fileInfo.Color);
204                                 System.Drawing.Brush br = new System.Drawing.SolidBrush(color);
205                                 System.Drawing.SizeF size = g.MeasureString(fileInfo.WaterMarkText, font);
206                                 float x = (img.Width - size.Width) / 2;
207                                 float y = 0;
208                                 switch (fileInfo.Position)
209                                 {
210                                     case 1://顶部居中
211                                         y = 2;
212                                         break;
213                                     case 2://上下居中
214                                         y = img.Height / 2;
215                                         break;
216                                     case 3://底部居中
217                                         y = img.Height - size.Height + 2;
218                                         break;
219                                     default:
220                                         y = 2;
221                                         break;
222                                 }
223                                 g.DrawString(fileInfo.WaterMarkText, font, br, x, y);
224                                 MemoryStream stream = new MemoryStream();
225                                 switch (fileExt.ToLower())
226                                 {
227                                     case ".png":
228                                         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
229                                         break;
230                                     case ".jpg":
231                                     case ".jpeg":
232                                         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
233                                         break;
234                                     case ".gif":
235                                         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
236                                         break;
237                                     case ".bmp":
238                                         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
239                                         break;
240                                     default:
241                                         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
242                                         break;
243                                 }
244                                 domainName = FastDFS.Client.FastDFSClient.GetDomains().Split(',')[0];
245                                 result = FastDFS.Client.FastDFSClient.UploadFile(stream, fileExt?.Replace(".", string.Empty));
246                                 bitmap.Dispose();
247                             }
248                         }
249                         else
250                         {
251                             domainName = FastDFS.Client.FastDFSClient.GetDomains().Split(',')[0];
252                             result = FastDFS.Client.FastDFSClient.UploadFile(fileInfo.FileStream, fileExt?.Replace(".", string.Empty));
253                         }
254                         fileUrl = string.Empty;
255 
256                         if (result.StatusCode == "200")
257                         {
258                             fileUrl = result.FileIndex;
259                         }
260                         else
261                         {
262                             fileUrl = result.ErrorMsg;
263                         }
264                     }
265 
266                     return domainName + "~" + fileUrl;
267                 }
268                 else
269                     return fileCheckFlag.ToString();
270             }
271 
272             return "1";
273         }
274 
275         /// <summary>
276         /// 检查文件
277         /// </summary>
278         /// <param name="hpf"></param>
279         /// <returns></returns>
280         private int CheckFile(FileM fileInfo)
281         {
282             int flag = 2;//0上传成功 1上传失败 2文件格式不正确 3文件大小不正确 
283             string currentType = "|" + Path.GetExtension(fileInfo.FileName).ToLower() + "|";
284 
285             string allowType = fileInfo.FileType == 0 ? _allowType : _fileAllowType;
286             int allowSize = fileInfo.FileType == 0 ? _allowSize : _fileAllowSize;
287             if (fileInfo.FileType == 0)
288             {
289                 allowType = _allowType;
290                 allowSize = fileInfo.MaxSize > 0 && fileInfo.MaxSize < _allowSize ? fileInfo.MaxSize : _allowSize;
291             }
292             else
293             {
294                 allowType = _fileAllowType;
295                 allowSize = fileInfo.MaxSize > 0 && fileInfo.MaxSize < _fileAllowSize ? fileInfo.MaxSize : _fileAllowSize;
296             }
297 
298             if (allowType.Contains(currentType))
299             {
300                 flag = 0;
301             }
302             if (flag == 0 && fileInfo.FileStream.Length >= allowSize * 1024)
303             {
304                 flag = 3;
305                 //2017年5月17日 李鑫:如果是图片大小超标,在这里进行一次图片压缩
306                 if (fileInfo.FileType == 0)
307                 {
308                     MemoryStream ms = ImageUtil.ZoomAuto(fileInfo.FileStream, 1080, 1080, "", "");
309                     if (ms.Length < allowSize * 1024)
310                     {
311                         ms.Position = 0;
312                         fileInfo.FileStream = new MemoryStream();
313                         ms.WriteTo(fileInfo.FileStream);
314 
315                         string fileExt = fileInfo.FileName.Substring(fileInfo.FileName.LastIndexOf('.'));
316                         fileInfo.FileName = fileInfo.FileName.Replace(fileExt, ".jpg");
317 
318                         flag = 0;
319                     }
320                 }
321             }
322 
323             if (flag == 0 && fileInfo.FileType == 0 && fileInfo.IsOCR)
324             {
325                 int len = (int)fileInfo.FileStream.Length;
326                 byte[] buffer = new byte[fileInfo.FileStream.Length];
327                 fileInfo.FileStream.Read(buffer, 0, len);
328 
329                 /*对图片进行文字识别*/
330                 Hqew.MS.Image.Client.ImageIdentifyAPI api = new Hqew.MS.Image.Client.ImageIdentifyAPI(null, null);
331                 Hqew.MS.Image.Model.ImgIdentifyResult ret = api.IdentifyPic(buffer);
332                 if (ret.StatusCode == 1)
333                 {
334                     flag = 5;//表示 图片不规范有禁词
335                 }
336             }
337             return flag;
338         }
339     }
文件上传类【此处未上传到服务器方法,需自行修改】

 

生成二维码dll 文件

ThoughtWorks.QRCode.dll

 

相关DLL 文件已在百度网盘上,可自行提取

链接:https://pan.baidu.com/s/1inVC4MJnNKgpk04ut-kW_g 
提取码:30j6 
复制这段内容后打开百度网盘手机App,操作更方便哦

 

posted @ 2021-01-15 10:18  情殇メ传说  阅读(126)  评论(0编辑  收藏  举报