/// <summary> /// 水印文字预设 /// </summary> /// <returns></returns> private static WaterMark WaterMarkFont() { WaterMark waterMark = new WaterMark(); waterMark.WaterMarkType = WaterMarkTypeEnum.Text; waterMark.Transparency = 0.7f; waterMark.FontStyle = System.Drawing.FontStyle.Bold; waterMark.FontFamily = "Consolas"; waterMark.FontSize = 20f; waterMark.BrushesColor = Brushes.YellowGreen; waterMark.Text = "dnt.dkill.net"; waterMark.WaterMarkLocation = WaterMarkLocationEnum.BottomRight; if (dics.ContainsKey("Text")) { waterMark.Text = dics["Text"]; } if (dics.ContainsKey("WaterMarkLocation")) { WaterMarkLocationEnum resultEnum; if (Enum.TryParse(dics["WaterMarkLocation"], out resultEnum)) { waterMark.WaterMarkLocation = resultEnum; } } return(waterMark); }
public WatermarkOptions() { InitializeComponent(); // Watermark this.watermark = new WaterMark(); // Alignment items var alignmentItems = ContentAlignmentItem.All(); foreach (var item in alignmentItems) { this.cmbAlignment.Items.Add(item); } this.cmbRightToLeft.SelectedItem = alignmentItems[0]; // Right to left items var rtlItems = RightToLeftItem.All(); foreach (var item in rtlItems) { this.cmbRightToLeft.Items.Add(item); } this.cmbRightToLeft.SelectedItem = rtlItems[0]; this.WatermarkAlignment = defaultAlignment; this.WatermarkColor = Color.FromName(defaultColorString); this.WatermarkFont = (Font) new FontConverter().ConvertFromString(defaultFontString); this.WatermarkMargin = (Margins) new MarginsConverter().ConvertFromString(defaultMarginString); this.WatermarkRightToLeft = defaultRightToLeft; this.WatermarkText = "This is a text!"; }
public void GetProductPic(ProductInfo productInfo) { productInfo.ProductPic = this.FileUploadProductPic.FilePath; string oldValue = base.BasePath + SiteConfig.SiteOption.UploadDir; string originalImagePath = productInfo.ProductPic.Replace(oldValue, ""); if (this.ChkThumb.Checked) { if (!string.IsNullOrEmpty(productInfo.ProductPic)) { try { string extension = Path.GetExtension(productInfo.ProductPic); string str4 = productInfo.ProductPic.Replace(extension, "_S" + extension); productInfo.ProductThumb = Thumbs.GetThumbsPath(originalImagePath, str4.Replace(oldValue, "")); } catch (ArgumentException) { BaseUserControl.WriteErrMsg("<li>生成缩略图的路径中具有非法字符!</li>"); } } } else { productInfo.ProductThumb = this.FileUploadProductThumb.FilePath; } if (this.ChkProductPicWatermark.Checked && !string.IsNullOrEmpty(productInfo.ProductPic)) { WaterMark.AddWaterMark(originalImagePath); } if (((this.ChkProductPicWatermark.Checked && this.ChkThumb.Checked) || this.ChkProductThumbWatermark.Checked) && !string.IsNullOrEmpty(productInfo.ProductThumb)) { WaterMark.AddWaterMark(productInfo.ProductThumb.Replace(oldValue, "")); } }
public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater) { try { string fileExt = Utils.GetFileExt(postedFile.FileName); int contentLength = postedFile.ContentLength; string str1 = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("\\") + 1); string str2 = Utils.GetRamCode() + "." + fileExt; string str3 = "thumb_" + str2; string upLoadPath = this.GetUpLoadPath(); string mapPath = Utils.GetMapPath(upLoadPath); string str4 = upLoadPath + str2; string str5 = upLoadPath + str3; if (!this.CheckFileExt(fileExt)) { return("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"); } if (!this.CheckFileSize(fileExt, contentLength)) { return("{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}"); } if (!Directory.Exists(mapPath)) { Directory.CreateDirectory(mapPath); } postedFile.SaveAs(mapPath + str2); if (this.IsImage(fileExt) && (this.siteConfig.imgmaxheight > 0 || this.siteConfig.imgmaxwidth > 0)) { Thumbnail.MakeThumbnailImage(mapPath + str2, mapPath + str2, this.siteConfig.imgmaxwidth, this.siteConfig.imgmaxheight); } if (this.IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0) { Thumbnail.MakeThumbnailImage(mapPath + str2, mapPath + str3, this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, "Cut"); } else { str5 = str4; } if (this.IsWaterMark(fileExt) && isWater) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(str4, str4, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(str4, str4, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } return("{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \"" + str1 + "\", \"path\": \"" + str4 + "\", \"thumb\": \"" + str5 + "\", \"size\": " + (object)contentLength + ", \"ext\": \"" + fileExt + "\"}"); } catch { return("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"); } }
public void SetWaterMarkWithNullImage() { // Arrange var waterMark = new WaterMark(); Bitmap image = null; // Act var result = sut.SetWaterMark(waterMark, image); }
protected void WaterMarkByFile(string filePath, string fileName, string extension) { string str = this.m_CurrentDir + "/" + filePath + "/"; if (this.IsPhoto(extension)) { WaterMark.AddWaterMark(str + fileName); } }
public void SetWaterMarkWithNullWaterMark() { // Arrange WaterMark waterMark = null; Bitmap image = new Bitmap(50, 50); // Act var result = sut.SetWaterMark(waterMark, image); }
/// <summary> /// 保存远程文件到本地 /// </summary> /// <param name="fileUri">URI地址</param> /// <returns>上传后的路径</returns> public string remoteSaveAs(string fileUri) { WebClient client = new WebClient(); string fileExt = string.Empty; //文件扩展名,不含“.” if (fileUri.LastIndexOf(".") == -1) { fileExt = "gif"; } else { fileExt = Utils.GetFileExt(fileUri); } string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名 string upLoadPath = GetUpLoadPath(); //上传目录相对路径 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 Model.files modelNewFile = new Model.files(); //新文件所需实体类 //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } try { client.DownloadFile(fileUri, fullUpLoadPath + newFileName); //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt)) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } //存储文件信息 modelNewFile = new BLL.files().Add(newFilePath, userID); } catch { return(string.Empty); } client.Dispose(); return(Utils.GetAppSettings("FileUrl") + modelNewFile.file_md5); }
/// <summary> /// 水印处理-文字转图片 /// </summary> /// <param name="model"></param> /// <returns></returns> private static Image TextToImager(WaterMark model) { Font f = new Font(model.FontFamily, model.FontSize, model.FontStyle); Bitmap fbitmap = new Bitmap(Encoding.GetEncoding("GBK").GetByteCount(model.Text) / 2 * f.Height, f.Height); Graphics gh = Graphics.FromImage(fbitmap);//创建一个画板; gh.SmoothingMode = SmoothingMode.AntiAlias; gh.DrawString(model.Text, f, model.BrushesColor, 0, 0);//画字符串 return(fbitmap as Image); }
public void TestAddTextWalterMark_Png_Small() { string srcImage = @"C:\Users\suzhong\Desktop\New folder\Untitled.png"; string outPath = @"C:\Users\suzhong\Desktop\New folder"; string srcText = "Chinese American Civic Association"; WaterMark walterMark = new WaterMark(srcImage, srcText, outPath); walterMark.ShortText = "咔咔华人社区"; var outImage = walterMark.AddTextWalterMark(); }
/// <summary> /// 儲存遠端檔到本地 /// </summary> /// <param name="fileUri">URI地址</param> /// <returns>上傳後的路徑</returns> public string remoteSaveAs(string fileUri) { WebClient client = new WebClient(); string fileExt = string.Empty; //文件副檔名,不含“.” if (fileUri.LastIndexOf(".") == -1) { fileExt = "gif"; } else { fileExt = Utils.GetFileExt(fileUri); } string newFileName = Utils.GetRamCode() + "." + fileExt; //隨機生成新的檔案名 string upLoadPath = GetUpLoadPath(); //上傳目錄相對路徑 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上傳目錄的物理路徑 string newFilePath = upLoadPath + newFileName; //上傳後的路徑 //檢查上傳的物理路徑是否存在,不存在則創建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } try { client.DownloadFile(fileUri, fullUpLoadPath + newFileName); //如果是圖片,檢查是否需要打浮水印 if (IsWaterMark(fileExt)) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } } catch { return(string.Empty); } client.Dispose(); return(newFilePath); }
public IActionResult ThumbsConfig() { var thumbsConfig = ConfigHelper.Get <ThumbsConfig>(); string strMsg = "AddBackColor:" + thumbsConfig.AddBackColor + " "; strMsg += "ThumbsMode:" + thumbsConfig.ThumbsMode + " "; strMsg += "ThumbsWidth:" + thumbsConfig.ThumbsWidth + " "; strMsg += "ThumbsHeight:" + thumbsConfig.ThumbsHeight + " "; strMsg += "静态文件目录路径:" + FileHelper.WebRootPath + " "; strMsg += "静态文件目录名称:" + FileHelper.WebRootName + " "; ViewData["Msg"] = strMsg; var thumbUrl = Thumbs.GetThumbUrl(Utility.GetBasePath() + Utility.UploadDirPath() + "test.jpg", true); ViewData["ImageUrl"] = Url.Content(thumbUrl); var thumbPath = Thumbs.GetThumbPath(Utility.UploadDirPath(true) + "test1.jpg", true); ViewData["ImagePath"] = Url.Content(thumbPath); var waterMarkConfig = ConfigHelper.Get <WaterMarkConfig>(); string strWaterMarkMsg = "WaterMarkType:" + waterMarkConfig.WaterMarkType + " "; strWaterMarkMsg += "FoneBorder:" + waterMarkConfig.WaterMarkTextInfo.FoneBorder + " "; strWaterMarkMsg += "FoneBorderColor:" + waterMarkConfig.WaterMarkTextInfo.FoneBorderColor + " "; strWaterMarkMsg += "FoneColor:" + waterMarkConfig.WaterMarkTextInfo.FoneColor + " "; strWaterMarkMsg += "FoneSize:" + waterMarkConfig.WaterMarkTextInfo.FoneSize + " "; strWaterMarkMsg += "FoneStyle:" + waterMarkConfig.WaterMarkTextInfo.FoneStyle + " "; strWaterMarkMsg += "FoneType:" + waterMarkConfig.WaterMarkTextInfo.FoneType + " "; strWaterMarkMsg += "Text:" + waterMarkConfig.WaterMarkTextInfo.Text + " "; strWaterMarkMsg += "WaterMarkPosition:" + waterMarkConfig.WaterMarkTextInfo.WaterMarkPosition + " "; strWaterMarkMsg += "WaterMarkPositionX:" + waterMarkConfig.WaterMarkTextInfo.WaterMarkPositionX + " "; strWaterMarkMsg += "WaterMarkPositionY:" + waterMarkConfig.WaterMarkTextInfo.WaterMarkPositionY + " "; strWaterMarkMsg += "ImagePath:" + waterMarkConfig.WaterMarkImageInfo.ImagePath + " "; strWaterMarkMsg += "Transparence:" + waterMarkConfig.WaterMarkImageInfo.Transparence + " "; strWaterMarkMsg += "WaterMarkPercent:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkPercent + " "; strWaterMarkMsg += "WaterMarkPercentType:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkPercentType + " "; strWaterMarkMsg += "WaterMarkPosition:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkPosition + " "; strWaterMarkMsg += "WaterMarkPositionX:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkPositionX + " "; strWaterMarkMsg += "WaterMarkPositionY:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkPositionY + " "; strWaterMarkMsg += "WaterMarkThumbPercent:" + waterMarkConfig.WaterMarkImageInfo.WaterMarkThumbPercent + " "; ViewData["WaterMarkMsg"] = strWaterMarkMsg; WaterMark.AddWaterMark(FileHelper.WebRootName + FileHelper.DirectorySeparatorChar + Utility.UploadDirPath() + "test.jpg"); ViewData["WaterUrl"] = Url.Content(Utility.GetBasePath() + Utility.UploadDirPath() + "test.jpg"); waterMarkConfig.WaterMarkType = 0; waterMarkConfig.WaterMarkTextInfo.Text = "asp.net core"; ConfigHelper.Save(waterMarkConfig); return(View()); }
/// <summary> /// 水印位置 /// </summary> /// <param name="model"></param> /// <param name="imgSource"></param> /// <param name="markImg"></param> /// <param name="x"></param> /// <param name="y"></param> private static void WaterMarkLocations(WaterMark model, Image imgSource, Image markImg, out int x, out int y) { x = 0; y = 0; switch (model.WaterMarkLocation) { case WaterMarkLocationEnum.TopLeft: x = 0; y = 0; break; case WaterMarkLocationEnum.TopCenter: x = imgSource.Width / 2 - markImg.Width / 2; y = 0; break; case WaterMarkLocationEnum.TopRight: x = imgSource.Width - markImg.Width; y = 0; break; case WaterMarkLocationEnum.CenterLeft: x = 0; y = imgSource.Height / 2 - markImg.Height / 2; break; case WaterMarkLocationEnum.CenterCenter: x = imgSource.Width / 2 - markImg.Width / 2; y = imgSource.Height / 2 - markImg.Height / 2; break; case WaterMarkLocationEnum.CenterRight: x = imgSource.Width - markImg.Width; y = imgSource.Height / 2 - markImg.Height / 2; break; case WaterMarkLocationEnum.BottomLeft: x = 0; y = imgSource.Height - markImg.Height; break; case WaterMarkLocationEnum.BottomCenter: x = imgSource.Width / 2 - markImg.Width / 2; y = imgSource.Height - markImg.Height; break; case WaterMarkLocationEnum.BottomRight: x = imgSource.Width - markImg.Width; y = imgSource.Height - markImg.Height; break; } }
/// <summary> /// Used to place shadow text into a TextBox or ComboBox when control does not have focus /// </summary> /// <param name="control">Name of control</param> /// <param name="text">Shadow text to show when control does not have focus</param> /// <param name="value">show water mark upon entering control or not</param> /// <remarks> /// Some might call this a watermark affect /// </remarks> public static void SetCueText(this Control control, string text, WaterMark value) { if (control is ComboBox) { var editHWnd = FindWindowEx(control.Handle, IntPtr.Zero, "Edit", null); if (!(editHWnd == IntPtr.Zero)) { SendMessage(editHWnd, EM_SETCUEBANNER, (int)value, text); } } else if (control is TextBox) { SendMessage(control.Handle, EM_SETCUEBANNER, (int)value, text); } }
public string Process(byte[] originalBytes, out byte[] markedBytesArray, out byte[] unWaterMarkedBytesArray, out int[] markedIndexes, out int[] unMarkedIndexes) { var processor = new Processor(originalBytes, _mode); markedBytesArray = processor.GetWaterMarkedBytes(_waterMark); unWaterMarkedBytesArray = processor.ExtractWaterMark(markedBytesArray); markedIndexes = processor.InseredWaterMarkIndexes.ToArray(); unMarkedIndexes = processor.ExtractedWaterMarkIndexes.ToArray(); var percentage = CalculateResult(processor.OriginalWaterMarkBits, processor.ExtractedWaterMarkBits); var percentageByIndexes = ResultByIndexes(markedIndexes, unMarkedIndexes); var extractedWaterMark = WaterMark.FromBitArray(processor.ExtractedWaterMarkBits); return(string.Format("Identity: {0}% / {1}% -> {2}", percentage.ToString("F0"), percentageByIndexes.ToString("F0"), extractedWaterMark)); }
public async static Task <byte[]> GetPictureByteArray(this IFormFile formFile, string waterMark) { if (formFile != null) { if (acceptableExt.Contains(Path.GetExtension(formFile?.FileName)?.ToLower())) { MemoryStream stream = new MemoryStream(); await formFile.CopyToAsync(stream); stream.Close(); var outStream = WaterMark.Mark(stream, waterMark, HostingEnvironment.WebRootPath + "/fonts/AdobeHeitiStd-Regular.otf"); return(outStream.ToArray()); } } return(null); }
public virtual IActionResult ImageWaterMarkText(string sf, string u, string t, int s, int q, string fn, int fs) { if (sf.IsNotSet()) { sf = ("/WaterMark/" + u).Replace("//", "/"); } var newPath = MapWebRootPath(sf); var path = MapWebRootPath(u); var bytes = WaterMark.AddImageSignText(path, t, s, q, fn, fs); Directory.CreateDirectory(Path.GetDirectoryName(newPath)); System.IO.File.WriteAllBytes(newPath, bytes); return(Success(sf)); }
/// <summary> /// 图片水印调用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click_1(object sender, RoutedEventArgs e) { //给水印对象赋对应的值 WaterMark waterMark = new WaterMark(); waterMark.WaterMarkType = Enums.WaterMarkTypeEnum.Image; waterMark.ImgPath = "水印.png"; waterMark.WaterMarkLocation = Enums.WaterMarkLocationEnum.CenterCenter; waterMark.Transparency = 0.7f; //调用 Image successImage = WaterMarkHelper.SetWaterMark("text.png", waterMark); //保存 successImage.Save("text2.png", System.Drawing.Imaging.ImageFormat.Png); MessageBox.Show("请查看软件根目录", "成功"); }
public void SetWaterMarkWithValidImage() { // Arrange var waterMark = new WaterMark(); var image = new Bitmap(50, 50); // Act var result = sut.SetWaterMark(waterMark, image); // Assert Assert.IsNotNull(result is Image); mockImageProcessor.Verify(imgProc => imgProc.Load(It.IsAny <Stream>()), Times.Once); mockImageProcessor.Verify(imgProc => imgProc.Watermark(It.IsAny <IWaterMark>()), Times.Once); mockImageProcessor.VerifyGet(imgProc => imgProc.Image); }
public static string ToBase64String(this UserFileItem userFile, string waterMark = null) { if (userFile != null && userFile.Status == StatusType.OK && acceptableExt.Contains(userFile.Type)) { using (var stream = File.OpenRead(Path.Combine(HostingEnvironment.WebRootPath, userFile.ServerPath))) using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); if (string.IsNullOrWhiteSpace(waterMark)) { return(Convert.ToBase64String(ms.ToArray())); } using (var outStream = WaterMark.Mark(ms, waterMark, HostingEnvironment.WebRootPath + "/fonts/AdobeHeitiStd-Regular.otf")) { return(Convert.ToBase64String(outStream.ToArray())); } } } return(""); }
/// <summary> /// 图片水印预设 /// </summary> /// <returns></returns> private static WaterMark WaterMarkImage() { WaterMark waterMark = new WaterMark(); waterMark.WaterMarkType = WaterMarkTypeEnum.Image; waterMark.Transparency = 0.7f; //图片路径 if (dics.ContainsKey("ImgPath")) { waterMark.ImgPath = dics["ImgPath"]; } //水印位置 if (dics.ContainsKey("WaterMarkLocation")) { WaterMarkLocationEnum resultEnum; if (Enum.TryParse(dics["WaterMarkLocation"], out resultEnum)) { waterMark.WaterMarkLocation = resultEnum; } } return(waterMark); }
/// <summary> /// 文字水印调用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { //给水印对象赋对应的值 WaterMark waterMark = new WaterMark(); waterMark.WaterMarkType = Enums.WaterMarkTypeEnum.Text; waterMark.Transparency = 0.7f; waterMark.Text = "dunitian.cnblogs.com"; waterMark.FontStyle = System.Drawing.FontStyle.Bold; waterMark.FontFamily = "Consolas"; waterMark.FontSize = 20f; waterMark.BrushesColor = System.Drawing.Brushes.YellowGreen; waterMark.WaterMarkLocation = Enums.WaterMarkLocationEnum.CenterCenter; //调用 Image successImage = WaterMarkHelper.SetWaterMark("text.png", waterMark); //保存 successImage.Save("text1.png", System.Drawing.Imaging.ImageFormat.Png); MessageBox.Show("请查看软件根目录", "成功"); }
/// <summary> /// 图片水印预设 /// </summary> /// <returns></returns> private static WaterMark WaterMarkImage() { WaterMark waterMark = new WaterMark(); waterMark.WaterMarkType = WaterMarkTypeEnum.Image; waterMark.ImgPath = "Config/水印.png"; waterMark.WaterMarkLocation = WaterMarkLocationEnum.BottomRight; waterMark.Transparency = 0.7f; if (dics.ContainsKey("ImgPath")) { waterMark.ImgPath = dics["ImgPath"]; } if (dics.ContainsKey("WaterMarkLocation")) { WaterMarkLocationEnum resultEnum; if (Enum.TryParse(dics["WaterMarkLocation"], out resultEnum)) { waterMark.WaterMarkLocation = resultEnum; } } return(waterMark); }
public string remoteSaveAs(string fileUri) { WebClient webClient = new WebClient(); string empty = string.Empty; string _fileExt = fileUri.LastIndexOf(".") != -1 ? Utils.GetFileExt(fileUri) : "gif"; string str1 = Utils.GetRamCode() + "." + _fileExt; string upLoadPath = this.GetUpLoadPath(); string mapPath = Utils.GetMapPath(upLoadPath); string str2 = upLoadPath + str1; if (!Directory.Exists(mapPath)) { Directory.CreateDirectory(mapPath); } try { webClient.DownloadFile(fileUri, mapPath + str1); if (this.IsWaterMark(_fileExt)) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(str2, str2, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(str2, str2, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } } catch { return(string.Empty); } webClient.Dispose(); return(str2); }
/// <summary> /// 批量水印操作 /// </summary> /// <param name="waterMark"></param> private void DIVWaterMarks(WaterMark waterMark) { System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog { Description = "选择你要批量水印的图片目录" }; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string[] files = Directory.GetFiles(dialog.SelectedPath); if (files.Length <= 0) { return; } //类型名进行过滤 var listFiles = files.Where(f => f.Contains(".png") || f.Contains(".jpg") || f.Contains(".bmp") || f.Contains(".gif") || f.Contains(".jpeg")); if (listFiles == null || listFiles.Count() < 1) { MessageBox.Show("该目录木有png,jpg,bmp,gif之类的常用图片格式", "逆天友情提醒"); return; } files = listFiles.ToArray(); SaveImages(waterMark, files); } }
/// <summary> /// 保存水印后的图片 /// </summary> /// <param name="waterMark"></param> /// <param name="filePaths"></param> private static void SaveImages(WaterMark waterMark, string[] filePaths) { int num = 0; #region 存储专用 //图片所处目录 string dirPath = Path.GetDirectoryName(filePaths[0]); //存放目录 string savePath = string.Format("{0}\\DNTWaterMark", dirPath); //是否存在,不存在就创建 if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } #endregion foreach (string filePath in filePaths) { //文件名 string fileName = Path.GetFileName(filePath); var successImage = WaterMarkHelper.SetWaterMark(filePath, waterMark); if (successImage != null) { //保存图片 string imgPath = string.Format(@"{0}\{1}", savePath, fileName); successImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png); num++; DisposeImg(successImage);//1.1 释放资源 } } //是否打开目录 MessageBoxResult result = MessageBox.Show("逆天友情提醒:已转换 " + num + " 张图片~是否打开目录?", "转换状态~如果是原图,请检查下水印图片是否有问题", MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { Process.Start("explorer.exe ", savePath);//打开保存后的路径 } }
/// <summary> /// 文件上传方法 /// </summary> /// <param name="postedFile">文件流</param> /// <param name="isThumbnail">是否生成缩略图</param> /// <param name="isWater">是否打水印</param> /// <returns>上传后文件信息</returns> public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater) { try { string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.” int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名 string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名 string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名 string upLoadPath = GetUpLoadPath(); //上传目录相对路径 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 string newThumbnailPath = upLoadPath + newThumbnailFileName; //上传后的缩略图路径 //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { return("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"); } //检查文件大小是否合法 if (!CheckFileSize(fileExt, fileSize)) { return("{\"status\": 0, \"msg\": \"文件超过限制的大小啦!\"}"); } //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } //保存文件 postedFile.SaveAs(fullUpLoadPath + newFileName); //如果是图片,检查图片是否超出最大尺寸,是则裁剪 if (IsImage(fileExt) && (this.siteConfig.imgmaxheight > 0 || this.siteConfig.imgmaxwidth > 0)) { Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newFileName, this.siteConfig.imgmaxwidth, this.siteConfig.imgmaxheight); } //如果是图片,检查是否需要生成缩略图,是则生成 if (IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0) { Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName, this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, "Cut"); } //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt) && isWater) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } //处理完毕,返回JOSN格式的文件信息 return("{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \"" + fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \"" + newThumbnailPath + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}"); } catch { return("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"); } }
public static byte[] GetWaterMarkImageArray(this MemoryStream stream, string waterMark) { var outStream = WaterMark.Mark(stream, waterMark, HostingEnvironment.WebRootPath + "/fonts/AdobeHeitiStd-Regular.otf"); return(outStream.ToArray()); }
/// <summary> /// 文件上传方法 /// </summary> /// <param name="postedFile">文件流</param> /// <param name="isThumbnail">是否生成缩略图</param> /// <param name="isWater">是否生成水印</param> /// <returns>上传后文件信息</returns> private JsonHelper FileSaveAs(HttpPostedFileBase postedFile, bool isThumbnail, bool isWater) { var jsons = new JsonHelper { Status = "n" }; try { string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.” int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名 string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名 string upLoadPath = GetUpLoadPath(fileExt); //上传目录相对路径 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名 //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { jsons.Msg = "不允许上传" + fileExt + "类型的文件!"; return(jsons); } //检查文件大小是否合法 if (!CheckFileSize(fileExt, fileSize)) { jsons.Msg = "文件超过限制的大小啦!"; return(jsons); } //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } //检查文件是否真实合法 //如果文件真实合法 则 保存文件 关闭文件流 //if (!CheckFileTrue(postedFile, fullUpLoadPath + newFileName)) //{ // jsons.Msg = "不允许上传不可识别的文件!"; // return jsons; //} //保存文件 postedFile.SaveAs(fullUpLoadPath + newFileName); string thumbnail = string.Empty; //如果是图片,检查是否需要生成缩略图,是则生成 if (IsImage(fileExt) && isThumbnail && ConfigurationManager.AppSettings["ThumbnailWidth"].ToString() != "0" && ConfigurationManager.AppSettings["ThumbnailHeight"].ToString() != "0") { Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName, int.Parse(ConfigurationManager.AppSettings["ThumbnailWidth"]), int.Parse(ConfigurationManager.AppSettings["ThumbnailHeight"]), "W"); thumbnail = upLoadPath + newThumbnailFileName; } //如果是图片,检查是否需要打水印 if (IsImage(fileExt) && isWater) { switch (ConfigurationManager.AppSettings["WatermarkType"].ToString()) { case "1": WaterMark.AddImageSignText(newFilePath, newFilePath, ConfigurationManager.AppSettings["WatermarkText"], int.Parse(ConfigurationManager.AppSettings["WatermarkPosition"]), int.Parse(ConfigurationManager.AppSettings["WatermarkImgQuality"]), ConfigurationManager.AppSettings["WatermarkFont"], int.Parse(ConfigurationManager.AppSettings["WatermarkFontsize"])); break; case "2": WaterMark.AddImageSignPic(newFilePath, newFilePath, ConfigurationManager.AppSettings["WatermarkPic"], int.Parse(ConfigurationManager.AppSettings["WatermarkPosition"]), int.Parse(ConfigurationManager.AppSettings["WatermarkImgQuality"]), int.Parse(ConfigurationManager.AppSettings["WatermarkTransparency"])); break; } } string unit = string.Empty; //处理完毕,返回JOSN格式的文件信息 jsons.Data = "{\"oldname\": \"" + fileName + "\","; //原始文件名 jsons.Data += " \"newname\":\"" + newFileName + "\","; //文件新名称 jsons.Data += " \"path\": \"" + newFilePath + "\", "; //文件路径 jsons.Data += " \"thumbpath\":\"" + thumbnail + "\","; //缩略图路径 jsons.Data += " \"size\": \"" + fileSize + "\","; //文件大小 jsons.Data += "\"ext\":\"" + fileExt + "\"}"; //文件格式 jsons.Status = "y"; return(jsons); } catch { jsons.Msg = "上传过程中发生意外错误!"; return(jsons); } }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); //try //{ // if (!Directory.Exists(Path.GetDirectoryName(localPath))) // { // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); // } // File.WriteAllBytes(localPath, uploadFileBytes); // Result.Url = savePath; // Result.State = UploadState.Success; //} try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); WaterMark.AddImageSignText(localPath, localPath, "Akic", 9, 80, "Tahoma", 12); WaterMark.AddImageSignPic(localPath, localPath, @"Content/css/images/Akic_Logo.png", 9, 80, 5); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }