Show image with watermark dynamic using code

Task: Show Image With Watermark dynamically using Asp.net and C# code.

Description: Sometime we need to add watermark with image on website so that no one can copy and reuse it. So that we can do it by a vary simple way using our back-end code. Here I write a code for achieving this task.
Here we can use image URL to that page URL where we write a code for merging these two images. And in code file I make a function for it we can call it in page_load event. In this function we have to pass both image URL, our image and watermark (watermark should be less then of image size - I will work later for resolve this issue also) and two points x and y for watermark position on that image (these points should be appropriate I also resolve this issue in my next post).
Watermark image should be "PNG" for better result.

Here I show the repetitive watermark on image, You can use it single or anyway as you w...
  

Call the page where you code for image merging :

Image1.ImageUrl = "dynamicimage.aspx";
 

Dynamic Code for image generation and merging (dynamicimage.aspx.cs)

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;


protected void Page_Load(object sender, EventArgs e)
{

string ThumbnailPath = Server.MapPath(@"images/testimage.jpg");
string watermark =Server.MapPath(@"images/watermark.png");
drawimagewm(ThumbnailPath, watermark, 50, 50);


}
public void drawimage(string imageurl, string watermark, int startx, int starty)
{
    string ThumbnailPath = imageurl;
    string Thumb_WMPath = watermark;

    System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
    System.Drawing.Image img_WM = System.Drawing.Image.FromFile(Thumb_WMPath);

    int width = image.Width;
    int height = image.Height;

    int width2 = img_WM.Width;
    int height2 = img_WM.Height;

    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image);

    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.CompositingQuality = CompositingQuality.HighQuality;

    if (startx > (width - width2) || starty > (height - (height2)))
    {
        graphics.DrawImage(image2, new Point(startx, starty));
    }
// I use 50 for gapping between two watermark...
    for (int i = startx; i < (width - (width2)); i = i + width2 + 50)
    {
        for (int j = starty; j < (height - (height2)); j = j + height2 + 50)
        {
            graphics.DrawImage(img_WM, new Point(i, j));
        }
    }
    ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

    string sExt = System.IO.Path.GetExtension(ThumbnailPath);
    Response.ContentType = "image/jpeg";

    if (sExt.ToString() == ".jpg" || sExt.ToString() == ".jpeg")
    {
        image.Save(Response.OutputStream, info[1], encoderParameters);
    }
    else
    {
        image.Save(Response.OutputStream, image.RawFormat);
    }
    image.Dispose();
    img_WM.Dispose();
}

Get Blogger Post - Rss Feed in our website

Task: Get Blogger RSS Feed/Post to our website (Show blogger post to our website).

Description: Sometime we need to show blogger post(RSS Feed) to our website. Using below code we can read all blog post from blogger(blogspot) Or we can also modify the code for reading other RSS feed(XML). The basic behind the reading RSS is read XML response. The blogger provides us a Rss link, from where we can read the XML.
I also used the string trimming with removing html tag Method As I used previously : Remove Html Tag
Here I used two methods for achieving this.

Method 1 : Using XML...

// Code Start //

using System.Xml;

using System.Text.RegularExpressions;

public string blogdetail = "";
private void ReadRssFeed()
{
    string blog = "";
    string RssFeedUrl = "http://hemantrautela.blogspot.com/feeds/posts/default?alt=rss";
    XDocument xDoc = new XDocument();
    xDoc = XDocument.Load(RssFeedUrl);
    var items = (from x in xDoc.Descendants("item")
                 select new
                 {
                     title = x.Element("title").Value,
                     link = x.Element("link").Value,
                     pubDate = x.Element("pubDate").Value,
                     description = x.Element("description").Value
                 });
    if (items != null)
    {
        foreach (var i in items)
        {
            String result = Regex.Replace(i.description, @"<[^>]*>", String.Empty);
            if (result.Length > 300)
            {
                result = result.Substring(0, 300);
                result = result.Substring(0, result.LastIndexOf(" ")) + "...";

            }
            blog += "<a href='" + i.link + "' rel='nofollow'>" + i.title + "</a><br/>" +
                    result + "<br/><br/>";
        }
        blogdetail = blog;
    }

}

// Code End//


Method 2 : Using by System.ServiceModel.Syndication

// Code Start //

    
    using System.Text.RegularExpressions;

    public string blogdetail = "";
    public void ReadRssFeed()
    {
        string rssFeedUrl = "http://hemantrautela.blogspot.com/feeds/posts/default?alt=rss";
        var syndicationFeed = System.ServiceModel.Syndication.SyndicationFeed.Load(XmlReader.Create(rssFeedUrl));
        string blog = "";
        foreach (var item in syndicationFeed.Items)
        {
            String result = Regex.Replace(item.Summary.Text, @"<[^>]*>", String.Empty);
            if (result.Length > 300)
            {
                result = result.Substring(0, 300);
                result = result.Substring(0, result.LastIndexOf(" ")) + "...";
            }
            blog += "<a href='" + item.Links[0].Uri + "' rel='nofollow'>" + item.Title.Text + "</a><br/>" +
                    result + "<br/><br/>";
        }
        blogdetail = blog;

    }

// Code End//

How detect mobile device or desktop using code

Task: Detect Mobile Device Or Desktop using Asp.net and C# code.

Description: Today is the market of responsive website(desktop & mobile friendly). we can manage easily responsive design of website using media query in CSS. But if we want to detect Device type using back-end code then what have to do ?
So here I show a code for detecting different type of  Mobile devices using code. I use a function detectDevice() which returns Boolean value, "True" for detect successfully mobile device else return "False" for desktop/laptop.
  

Code :

using System.Text.RegularExpressions;

public bool detectDevice()
{
    bool deviceStatus = false;
    string user_agent = Request.ServerVariables["HTTP_USER_AGENT"];
    Regex reg1 = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    Regex reg2 = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);

    if ((reg1.IsMatch(user_agent) || reg2.IsMatch(user_agent.Substring(0, 4))))
    {
        deviceStatus = true//Mobile Device Detected
    }
    return deviceStatus;

}
 

Upload Image by external URL in asp.net

Task: Upload Image using external URL on our website using asp.net.

Description: Sometime we need to upload image option using URL of image(from some external resources). So that we need not to download it and then upload in our website & also need not to use external image link in our website. This code create new image in your website folder(here i used yourfolder).
We can also use it for Data-scrapping(Read Content/images from another website).
We can Resize it also. In older post I describe the resize image with maintain aspect ration here ->  Upload & Resize Image



// Code Start //


 using System.Net;
 using System.IO;
 using System.Drawing;

  public void saveimage(string imageURL)
    {
        Stream imageStream = new WebClient().OpenRead(imageURL);
        System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream);
        string path = Server.MapPath("yourfolder") + "\\test.jpg";
        img.Save(path);
    }



// Code End//