public void AddWatermark() { // First, add the image watermark Image originImage = Image.FromFile(@"C:\source.jpg"); Image watermark = Image.FromFile(@"C:\clock.png"); ImageWatermarker imgWatermarker = new ImageWatermarker(originImage, watermark); // You can set the watermark size, if you not then the watermark will be its original size by default imgWatermarker.SetWatermarkHeight(80); imgWatermarker.AddWatermark(); // Second, add the text watermark TextWatermarker txtWatermarker = new TextWatermarker(imgWatermarker.WatermarkedImage, "www.zizhujy.com"); txtWatermarker.Position = WatermarkPostion.TopLeft; txtWatermarker.AddWatermark(); // Response and show the watermarked image in the browser Response.ContentType = "image/jpeg"; // Note: save the secondly watermarked image // (txtWatermarker not imgWatermarker because the txtWatermarker comes after than imgWatermarker) txtWatermarker.WatermarkedImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); imgWatermarker.Dispose(); watermark.Dispose(); originImage.Dispose(); }
//Image originImage = Image.FromFile(@"C:\source.jpg"); //Image watermark = Image.FromFile(@"C:\clock.png"); //ImageWatermarker imgWatermarker = new ImageWatermarker(originImage, watermark); //imgWatermarker.Position = WatermarkPostion.BottomRight; //imgWatermarker.SetWatermarkHeight(70); //imgWatermarker.ForegroundOpacity = 0.5; //imgWatermarker.AddWatermark(); //TextWatermarker txtWatermark = new TextWatermarker(imgWatermarker.WatermarkedImage, "www.zizhujy.com"); //txtWatermark.Position = WatermarkPostion.TopLeft; //txtWatermark.AddWatermark(); //Response.ContentType = "image/jpeg"; //txtWatermark.WatermarkedImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //originImage.Dispose(); //watermark.Dispose(); //imgWatermarker.Dispose(); //txtWatermark.Dispose(); //} public void AddWatermark3() { Image originImage = Image.FromFile(@"C:\1305211066-1784_600-0_6-0.jpg"); Image watermark = Image.FromFile(@"C:\logo.png"); ImageWatermarker imgWatermarker = new ImageWatermarker(originImage, watermark); imgWatermarker.Position = WatermarkPostion.TopRight; imgWatermarker.ForegroundOpacity = 0.9; imgWatermarker.AddWatermark(); Response.ContentType = "image/jpeg"; imgWatermarker.WatermarkedImage.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); originImage.Dispose(); watermark.Dispose(); imgWatermarker.Dispose(); }
/// <summary> /// 添加水印 /// </summary> /// <param name="stream"></param> /// <returns></returns> public static Stream AddWatermark(this Stream stream) { if (!string.IsNullOrEmpty(SystemSettings.GetOrAdd("Watermark", string.Empty))) { try { var watermarker = new ImageWatermarker(stream) { SkipWatermarkForSmallImages = true, SmallImagePixelsThreshold = 40000 }; return(watermarker.AddWatermark(SystemSettings["Watermark"], Color.LightGray, WatermarkPosition.BottomRight, 30)); } catch { // } } return(stream); }
public async Task <IActionResult> UploadImageAsync(IFormFile file, [FromServices] IFileNameGenerator fileNameGenerator) { try { if (null == file) { Logger.LogError("file is null."); return(BadRequest()); } if (file.Length <= 0) { return(BadRequest()); } var name = Path.GetFileName(file.FileName); if (name == null) { return(BadRequest()); } var ext = Path.GetExtension(name).ToLower(); var allowedImageFormats = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" }; if (!allowedImageFormats.Contains(ext)) { Logger.LogError($"Invalid file extension: {ext}"); return(BadRequest()); } var primaryFileName = fileNameGenerator.GetFileName(name); var secondaryFieName = fileNameGenerator.GetFileName(name, "origin"); await using var stream = new MemoryStream(); await file.CopyToAsync(stream); // Add watermark MemoryStream watermarkedStream = null; if (_blogConfig.WatermarkSettings.IsEnabled && ext != ".gif") { using var watermarker = new ImageWatermarker(stream, ext) { SkipWatermarkForSmallImages = true, SmallImagePixelsThreshold = Constants.SmallImagePixelsThreshold }; Logger.LogInformation($"Adding watermark onto image '{primaryFileName}'"); watermarkedStream = watermarker.AddWatermark( _blogConfig.WatermarkSettings.WatermarkText, Color.FromArgb(128, 128, 128, 128), WatermarkPosition.BottomRight, 15, _blogConfig.WatermarkSettings.FontSize); } var response = await _imageStorage.InsertAsync(primaryFileName, watermarkedStream != null? watermarkedStream.ToArray() : stream.ToArray()); if (_blogConfig.WatermarkSettings.KeepOriginImage) { var arr = stream.ToArray(); _ = Task.Run(async() => await _imageStorage.InsertAsync(secondaryFieName, arr)); } Logger.LogInformation($"Image '{primaryFileName}' uloaded."); if (response.IsSuccess) { return(Json(new { location = $"/uploads/{response.Item}", filename = response.Item })); } Logger.LogError(response.Message); return(ServerError()); } catch (Exception e) { Logger.LogError(e, "Error uploading image."); return(ServerError()); } }
public ActionResult Uploadimg() { var result = new ResultAdaptDto(); //long size = 0; //当设置了开始水印的时候,可以使用nomark来过滤图片不加水印 int nomark = RequestHelper.GetPostInt("nomark"); var files = Request.Form.Files; if (files.Count == 0) { result.status = false; result.message = "没有文件信息"; return(Content(result.ToJson())); } string url = $"/upfiles/images/{DateTime.Now.ToString("yyyyMMdd")}"; var folder = GlobalContext.WebRootPath + url; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var file = files[0]; var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); int index = filename.LastIndexOf('.'); string extName = filename.Substring(index); string guidstr = Guid.NewGuid().ToString("N"); string guidFileName = guidstr + extName; //这个hostingEnv.WebRootPath就是要存的地址可以改下 filename = $"{folder}/{guidFileName}"; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } var firstFileInfo = new FileInfo(filename); if (firstFileInfo.Length > 200 * 1024) { string compressFileName = IdHelper.ObjectId() + extName; string compressFile = $"{folder}/{compressFileName}"; ImageUtilities.CompressImage(filename, compressFile, 90, 200); guidFileName = compressFileName; } if (nomark == 0) { var imageSet = SiteManagerCache.GetUploadInfo(); if (imageSet.open_watermark == 1) { try { string sourcePath = $"{folder}/{guidFileName}"; if (System.IO.File.Exists(sourcePath)) { FileStream fs = new FileStream(sourcePath, FileMode.Open); //把文件读取到字节数组 byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); fs.Close(); //实例化一个内存流--->把从文件流中读取的内容[字节数组]放到内存流中去 MemoryStream ms = new MemoryStream(data); Image image = Image.FromStream(ms); if (image.Width > imageSet.image_width && image.Height > imageSet.image_height) { ImageWatermarker marker = new ImageWatermarker(); //图片水印 if (imageSet.watermark_type == 1) { string waterMarkIamge = GlobalContext.WebRootPath + imageSet.watermark_image; if (System.IO.File.Exists(waterMarkIamge)) { marker.AddImageSignPic(image, sourcePath, waterMarkIamge, imageSet.water_postion, imageSet.image_quality, imageSet.image_opacity); } } else { marker.AddWatermarkText(image, sourcePath, imageSet.watermark_word, imageSet.water_postion, imageSet.font_size, imageSet.font_color); } } } } catch (Exception ex) { LoggerHelper.Exception(ex); } } } string imgurl = $"{ url}/{guidFileName}"; result.data.Add("url", imgurl); return(Content(result.ToJson())); }
void ImageGuarding(object sender, EventArgs e) { HttpContext context = HttpContext.Current; if (context.Request.UrlReferrer != null) { if (string.Compare(context.Request.Url.Host.Replace("www.", ""), context.Request.UrlReferrer.Host.Replace("www.", ""), true, CultureInfo.InvariantCulture) != 0) { string guardingType = settings.GetSingleValue("guardingType"); if (guardingType.Equals("Reject")) { context.Response.StatusCode = 403; context.Response.End(); } else if (guardingType.Equals("Block")) { string blockImagePath = settings.GetSingleValue("blockImagePath"); var fi = new FileInfo(context.Server.MapPath(blockImagePath)); if (fi.Exists) { //context.Response.Cache.SetCacheability(HttpCacheability.Public); //context.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); string extension = Path.GetExtension(fi.Name); context.Response.ContentType = string.Compare(extension.ToUpper(), "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension); context.Response.TransmitFile(fi.FullName); context.Response.End(); } } else if (guardingType.Equals("Watermark")) { FileInfo originImageFileInfo = GetOriginalImage(); if (originImageFileInfo != null) { TextWatermarker txtWatermarker = null; ImageWatermarker imgWatermarker = null; Image originImage = Bitmap.FromFile(originImageFileInfo.FullName); string watermarkText = settings.GetSingleValue("watermarkText"); if (!string.IsNullOrWhiteSpace(watermarkText)) { txtWatermarker = new TextWatermarker(originImage, watermarkText); txtWatermarker.AddWatermark(); originImage = txtWatermarker.WatermarkedImage; } string watermarkImagePath = settings.GetSingleValue("watermarkImagePath"); if (!string.IsNullOrWhiteSpace(watermarkImagePath)) { FileInfo fi = new FileInfo(context.Server.MapPath(watermarkImagePath)); if (fi.Exists) { Image watermarkImage = Bitmap.FromFile(fi.FullName); imgWatermarker = new ImageWatermarker(originImage, watermarkImage); imgWatermarker.Position = WatermarkPostion.BottomLeft; imgWatermarker.AddWatermark(); originImage = imgWatermarker.WatermarkedImage; } } // Serving the watermarked image //context.Response.Cache.SetCacheability(HttpCacheability.Public); //context.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); string extension = Path.GetExtension(originImageFileInfo.Name); context.Response.ContentType = string.Compare(extension.ToUpper(), "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension); //originImage.Save(context.Response.OutputStream, ImageHelper.GetImageFormatByExtension(extension)); MemoryStream mem = new MemoryStream(); originImage.Save(mem, ImageHelper.GetImageFormatByExtension(extension)); mem.WriteTo(context.Response.OutputStream); mem.Dispose(); originImage.Dispose(); if (txtWatermarker != null) { txtWatermarker.Dispose(); } if (imgWatermarker != null) { imgWatermarker.Dispose(); } context.Response.End(); } else { context.Response.StatusCode = 404; context.Response.End(); } } else { } } else { // string.Compare(context.Request.Url.Host, context.Request.UrlReferrer.Host, true, CultureInfo.InvariantCulture) == 0 // The request host and the referrer host are the same, serve the image normally //FileInfo originImageFileInfo = GetOriginalImage(); //if (originImageFileInfo != null) //{ // TextWatermarker txtWatermarker = null; // Image originImage = Bitmap.FromFile(originImageFileInfo.FullName); // string watermarkText = context.Request.Url.Host; // if (!string.IsNullOrWhiteSpace(watermarkText)) // { // txtWatermarker = new TextWatermarker(originImage, watermarkText); // txtWatermarker.Position = WatermarkPostion.TopLeft; // txtWatermarker.AddWatermark(); // originImage = txtWatermarker.WatermarkedImage; // } // watermarkText = context.Request.UrlReferrer.Host; // if (!string.IsNullOrWhiteSpace(watermarkText)) // { // txtWatermarker = new TextWatermarker(originImage, watermarkText); // txtWatermarker.AddWatermark(); // originImage = txtWatermarker.WatermarkedImage; // } // string extension = Path.GetExtension(originImageFileInfo.Name); // context.Response.ContentType = string.Compare(extension.ToUpper(), "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension); // //originImage.Save(context.Response.OutputStream, ImageHelper.GetImageFormatByExtension(extension)); // MemoryStream mem = new MemoryStream(); // originImage.Save(mem, ImageHelper.GetImageFormatByExtension(extension)); // mem.WriteTo(context.Response.OutputStream); // mem.Dispose(); // originImage.Dispose(); // if (txtWatermarker != null) // txtWatermarker.Dispose(); // context.Response.End(); //} //else //{ // context.Response.StatusCode = 404; // context.Response.End(); //} } } }
public async Task <IActionResult> UploadImageAsync(IFormFile file) { try { if (null == file) { Logger.LogError("file is null."); return(BadRequest()); } if (file.Length > 0) { var name = Path.GetFileName(file.FileName); if (name == null) { return(BadRequest()); } var ext = Path.GetExtension(name).ToLower(); var allowedImageFormats = new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" }; if (!allowedImageFormats.Contains(ext)) { Logger.LogError($"Invalid file extension: {ext}"); return(BadRequest()); } using (var stream = new MemoryStream()) { await file.CopyToAsync(stream); // Add watermark MemoryStream watermarkedStream = null; if (_blogConfig.WatermarkSettings.IsEnabled && ext != ".gif") { var watermarker = new ImageWatermarker(stream, ext) { SkipWatermarkForSmallImages = true, SmallImagePixelsThreshold = Constants.SmallImagePixelsThreshold }; Logger.LogInformation($"Adding watermark onto image {name}"); watermarkedStream = watermarker.AddWatermark( _blogConfig.WatermarkSettings.WatermarkText, Color.FromArgb(128, 128, 128, 128), WatermarkPosition.BottomRight, 15, _blogConfig.WatermarkSettings.FontSize); } var response = await _imageStorageProvider.InsertAsync(name, watermarkedStream != null? watermarkedStream.ToArray() : stream.ToArray()); Logger.LogInformation("Image Uploaded: " + JsonConvert.SerializeObject(response)); if (response.IsSuccess) { return(Json(new { location = $"/uploads/{response.Item}" })); } Logger.LogError(response.Message); return(ServerError()); } } return(BadRequest()); } catch (Exception e) { Logger.LogError(e, "Error uploading image."); return(ServerError()); } }