繁体   English   中英

上传图片时将水印添加到图片

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM