اضافه کردن Watermark به تصاویر یک برنامه ASP.NET MVC در صورت لینک شدن در سایتی دیگر
نویسنده: وحید نصیری
تاریخ: ۱۳۹۲/۰۲/۱۹ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System.IO;
using System.Net.Mime;
using System.Web.Mvc;
namespace MvcWatermark.Controllers
{
public class HomeController : Controller
{
const int ADay = 86400;
public ActionResult Index()
{
return View();
}
[OutputCache(VaryByParam = "fileName", Duration = ADay)]
public ActionResult Image(string fileName)
{
fileName = Path.GetFileName(fileName); // تمیز سازی امنیتی است
var rootPath = Server.MapPath("~/App_Data/Images");
var path = Path.Combine(rootPath, fileName);
if (!System.IO.File.Exists(path))
{
var notFoundImage = "notFound.png";
path = Path.Combine(rootPath, notFoundImage);
return File(path, MediaTypeNames.Image.Gif, notFoundImage);
}
return File(path, MediaTypeNames.Image.Gif, fileName);
}
}
}<img src="@Url.Action(actionName: "Image", controllerName: "Home", routeValues: new { fileName = "EF_Stra_08.gif" })" /> private bool isEmbeddedIntoAnotherDomain
{
get
{
return this.HttpContext.Request.UrlReferrer != null &&
!this.HttpContext.Request.Url.Host.Equals(this.HttpContext.Request.UrlReferrer.Host,
StringComparison.InvariantCultureIgnoreCase);
}
} private byte[] addWaterMark(string filePath, string text)
{
var image = new WebImage(filePath);
image.AddTextWatermark(text);
return image.GetBytes();
}A Graphics object cannot be created from an image that has an indexed pixel format.
PixelFormatUndefined PixelFormatDontCare PixelFormat1bppIndexed PixelFormat4bppIndexed PixelFormat8bppIndexed PixelFormat16bppGrayScale PixelFormat16bppARGB1555
private byte[] addWaterMark(string filePath, string text)
{
using (var img = System.Drawing.Image.FromFile(filePath))
{
using (var memStream = new MemoryStream())
{
using (var bitmap = new Bitmap(img))//avoid gdi+ errors
{
bitmap.Save(memStream, ImageFormat.Png);
var webImage = new WebImage(memStream);
webImage.AddTextWatermark(text, verticalAlign: "Top", horizontalAlign: "Left", fontColor: "Brown");
return webImage.GetBytes();
}
}
}
} if (isEmbeddedIntoAnotherDomain)
{
var text = Url.Action(actionName: "Index", controllerName: "Home", routeValues: null, protocol: "http");
var content = addWaterMark(path, text);
return File(content, MediaTypeNames.Image.Gif, fileName);
}
return File(path, MediaTypeNames.Image.Gif, fileName);