In this article, we will learn how to overlay two images using ASP.NET. Recently, while working on my web application project, I received a requirement to develop a video gallery similar to YouTube in my MVC web application.
For this purpose, I needed to display a video thumbnail for each video along with a play icon. After successfully completing this task, I decided to share the code with you all.
Essentially, I opted to create a new image by first rendering the background thumbnail image, and then overlaying a play icon image on top of it.
Instead of replacing one image with another, my goal was to position the second smaller image on top of the first image, allowing both images to be visible simultaneously.
So, my requirement is to place a play icon image at the center of the background image. Let's get started.
1. Create an empty application.
2. Create a folder.
3. Add a background image and play icon.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Converter.aspx.cs" Inherits="Converter" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="ActualImage" Font-Bold="True"></asp:Label>
<asp:Image ID="Image1" runat="server" Width="134px" />
<asp:Label ID="Label2" runat="server" Text="OverlayImage" Font-Bold="True"></asp:Label>
<asp:Image ID="Image2" runat="server" Width="135px" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Converter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Draw();
Image1.ImageUrl = "Video/BackGround.jpg";
Image2.ImageUrl = "Video/output.png";
}
public void Draw()
{
string BackgroundImage = Server.MapPath("Video/BackGround.jpg");
string IconImage = Server.MapPath("Video/play.png");
string OutputImage = Server.MapPath("Video/output.png");
System.Drawing.Image imageBackground = System.Drawing.Image.FromFile(BackgroundImage); //background image or big image
System.Drawing.Image imageOverlay = System.Drawing.Image.FromFile(IconImage); //small image
System.Drawing.Image img = new Bitmap(imageBackground.Width, imageBackground.Height);
using (Graphics gr = Graphics.FromImage(img))
{
gr.DrawImage(imageBackground, new Point(0, 0));
gr.DrawImage(imageOverlay, new Point(imageBackground.Width / 2 - 50, imageBackground.Height / 2 - 50));
}
img.Save(OutputImage, ImageFormat.Png);
}
}
Page_Load Method:
Draw Method:
Above code overlays a play icon image onto a background image and saves the resulting image as an output PNG file.