Use httphandler in Asp.net to add watermarks to website Images

Source: Internet
Author: User

First, create a class named watermarkhandler. Implementation of this class: ihttphandler interface. Add the following code to the processrequest method:

Then, add



Finally, configure IIS. Select "properties" of the website. In the "properties" dialog box, click "directory tag"> "Configure ".

In the "Application configuration" dialog box that appears, select "add" to map the file with the extension:. jpg to aspnet_isapi.dll (the same as the. aspx handler ).

String url = context. Request. rawurl. tolower ();

/**//*
Determine whether the user request is a JPG file
You can put the image you want to add a watermark to a specific folder. Then determine whether the user is
The image in the requested folder. Here is a simple example without judgment.
*/
If (URL. endswith ("jpg "))
...{
Image PIC = image. fromfile (context. server. mappath (context. Request. rawurl ));
Graphics G = graphics. fromimage (PIC );
// I saved the path of the "watermark image" in Web. config.
Image watermarkimage = image. fromfile (configurationsettings. etettings ["watemarkpic"]);
/**//*
Draw the watermark image to the image requested by the user, and set the position and size of the watermark image.
Drawimage has many reload methods to choose from. Here is just an example
*/
G. drawimage (watermarkimage, 20, 20 );
G. Dispose ();
// Save the watermark image to the output stream
PIC. Save (context. response. outputstream, system. Drawing. imaging. imageformat. JPEG );
PIC. Dispose ();
Watermarkimage. Dispose ();
/**//*
Indicates the type as JPG. If it is not added, ie browsing will not be a problem, and Firefox will be garbled.
*/
Context. response. contenttype = "image/JPEG ";
Context. response. Flush ();
Context. response. End ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.