Exemplo n.º 1
0
        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();
        }
Exemplo n.º 2
0
        //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();
        }
Exemplo n.º 3
0
 /// <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);
 }
Exemplo n.º 4
0
        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());
            }
        }
Exemplo n.º 5
0
    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();
                //}
            }
        }
    }
Exemplo n.º 6
0
        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());
            }
        }