[英]Add watermark to Image when it uploaded
我有一個使用Ajax上傳圖像的功能,以及另一個在圖像上添加水印的功能,它們兩個都正常工作。
我的水印功能從目錄獲取圖像,但是我想在將圖像保存到服務器之前將圖像傳遞給watermark()
。 有什么辦法嗎?
這是我的代碼:
上載功能
[HttpPost]
public ActionResult FileUpload()
{
byte[] ImageData = null;
HttpPostedFileBase file = Request.Files[0];
var input = file.InputStream;
input.Position = 0;
using (var ms = new MemoryStream())
{
var length = Convert.ToInt32(input.Length);
input.CopyTo(ms, length);
ImageData = ms.ToArray();
}
Stream fileContent = file.InputStream;
var filepath = "~/NewFolder/File/";
string targetFolder = Server.MapPath(filepath);
string targetPath = Path.Combine(targetFolder, file.FileName);
//***** Here is place that I want to pass Image has been uploaded to Watermark()
//***** In this case Watermark() get an image from dir : @"D:\cc\image.png"
Watermark(@"D:\cc\image.png", "mohammad", @"D:\cc\w.png", ImageFormat.Png);
file.SaveAs(targetPath);
return Json(new { message = Request.Files.Count });
}
水印功能
public void Watermark(string sourceImage, string text, string targetImage, ImageFormat fmt)
{
try
{
// open source image as stream and create a memorystream for output
var source = new FileStream(sourceImage, FileMode.Open);
Stream output = new MemoryStream();
Image img = Image.FromStream(source);
// choose font for text
Font font = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);
//choose color and transparency
Color color = Color.FromArgb(100, 255, 0, 0);
//location of the watermark text in the parent image
Point pt = new Point(10, 5);
SolidBrush brush = new SolidBrush(color);
//draw text on image
Graphics graphics = Graphics.FromImage(img);
graphics.DrawString(text, font, brush, pt);
graphics.Dispose();
//update image memorystream
img.Save(output, fmt);
Image imgFinal = Image.FromStream(output);
//write modified image to file
Bitmap bmp = new System.Drawing.Bitmap(img.Width, img.Height, img.PixelFormat);
Graphics graphics2 = Graphics.FromImage(bmp);
graphics2.DrawImage(imgFinal, new Point(0, 0));
bmp.Save(targetImage, fmt);
imgFinal.Dispose();
img.Dispose();
}
catch (Exception ex)
{
throw ex;
}
}
您可以將file.InputStream
直接傳遞到已經使用Image.FromStream
方法的Watermark
方法。 因此,您將直接從輸入流中讀取圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.