I have a function to upload image with Ajax and and another function for add watermark on image and both of them worked correctly.
My watermark function get image from directory, but I want to pass image to watermark()
before save image on server. Is there any way to do this?
Here is my Code:
Upload function
[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 });
}
Watermark Function
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;
}
}
You can pass file.InputStream
directly to Watermark
method, where you already use Image.FromStream
method. So you will directly read image from input stream.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.