Water Marked 水印

from : Pro ASPnetMVCFramework

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace TestMvcWebApp1.ActionResultEx
{
    public class WatermarkedImageResult : ActionResult
    {
        public WatermarkedImageResult() { }
        public string ImageFileName { get; private set; }
        public string WatermarkText { get; private set; }
        public WatermarkedImageResult(string imageFileName, string watermarkText)
        {
            ImageFileName = imageFileName;
            WatermarkText = watermarkText;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            using (var image = Image.FromFile(ImageFileName))
            using (var graphics = Graphics.FromImage(image))
            using (var font = new Font("Arial", 10))
            using (var memoryStream = new MemoryStream())
            {
                // Render the watermark text in bottom-left corner
                var textSize = graphics.MeasureString(WatermarkText, font);
                graphics.DrawString(WatermarkText, font, Brushes.Black, 10,
                    image.Height - textSize.Height - 10);
                // Transmit the image in PNG format (note: must buffer it in
                // memory first due to GDI+ limitation)284 CHAPTER 9 n CONTROLLERS AND ACTIONS
                image.Save(memoryStream, ImageFormat.Png);
                var response = context.RequestContext.HttpContext.Response;
                response.ContentType = "image/png";
                response.BinaryWrite(memoryStream.GetBuffer());
            }
        }
    }
}

使用:

 public ActionResult ViewmarkedImage()
        {

            string ImageFileName = @"C:\Documents and Settings\Administrator\My Documents\My Pictures\oem.gif";
            string WatermarkText = "这是我的水印";
            WatermarkedImageResult result = new WatermarkedImageResult(ImageFileName, WatermarkText);
            return result;
        }

 

 

 

 

posted @ 2010-12-20 15:28  庚武  Views(301)  Comments(0Edit  收藏  举报