我有一个用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;
}
}
答案 0 :(得分:2)
您可以将file.InputStream
直接传递给已使用Watermark
方法的Image.FromStream
方法。因此,您将直接从输入流中读取图像。