Solved

Merge two images in ASP.NET 2.0 using C#

Posted on 2009-04-02
17
5,409 Views
Last Modified: 2012-05-06
Hi,

I need a code which will merge two images and creates a single image. I have two images. One is of 150 * 150 px and other is dynamic image less than 150 * 150 px and i want to merge second image with first image.

Your help will be counted.

Regards

Glenn
0
Comment
Question by:dotsandcoms
  • 8
  • 8
17 Comments
 
LVL 23

Expert Comment

by:apresto
ID: 24048209
What do you mean merge? As in have them both in a single file, as in a Sliding GIF or on top of each other? please clarify
0
 
LVL 23

Expert Comment

by:apresto
ID: 24048214
0
 

Author Comment

by:dotsandcoms
ID: 24048226
As said that i have two images.

(1) One is blank image with white background of 150 * 150 px

(2) Second is dynamic image with less than 150 * 150 px

I want to overlap the second image with first image. For that i need the code in asp.net 2.0 using c#

0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 23

Expert Comment

by:apresto
ID: 24048256
Have a look here:
http://www.daniweb.com/forums/thread112667.html
Here is a snippet of the code suggested, i am testing it myself as we speak:

protected void Page_Load(object sender, EventArgs e)
{
 
string s = Server.MapPath("original.jpg");
string s2 = Server.MapPath("ikon.gif");
 
System.Drawing.Image original= Bitmap.FromFile(s);
Graphics gra = Graphics.FromImage(original);
Bitmap logo = new Bitmap(s2);
gra.DrawImage(logo, new Point(70, 70));
 
Response.ContentType = "image/JPEG";
big.Save(Response.OutputStream, ImageFormat.Jpeg);
 
} 

Open in new window

0
 
LVL 23

Expert Comment

by:apresto
ID: 24048326
ok this works. Just change "s" to the name of your background image, and "s2" to the name of the image you want to overlay
You'll have to have a play to get it where you want but thats the giste

string s = Server.MapPath("original.jpg");
        string s2 = Server.MapPath("ikon.jpg");
 
        System.Drawing.Image original = Bitmap.FromFile(s);
        Graphics gra = Graphics.FromImage(original);
        System.Drawing.Image logo = Bitmap.FromFile(s2);
        gra.DrawImage(logo, new Point(70, 70));
 
        Response.ContentType = "image/JPEG";
        original.Save(Server.MapPath("new.jpg"), ImageFormat.Jpeg);

Open in new window

0
 

Author Comment

by:dotsandcoms
ID: 24059221
Hi,

Thanks for the code but i have few queries in my mind and they are as follows:

(1) How can i define the position of second image in first image. As told earlier that i have two images, one with fixed 150 * 150 px and second with variable size. Suppose second image is 50 * 50 px then how can we define the location of second image in first image. In your code you have define the points 70 , 70 and they are fixed (static).
0
 
LVL 23

Expert Comment

by:apresto
ID: 24059580

string s = Server.MapPath("original.jpg");
        string s2 = Server.MapPath("ikon.jpg");
 
        System.Drawing.Image original = Bitmap.FromFile(s);
        Graphics gra = Graphics.FromImage(original);
        System.Drawing.Image logo = Bitmap.FromFile(s2);
 
        int origW, origH, logoW, logoH, xPos, yPos;
        origW = original.Width;
        origH = original.Height;
        logoW = logo.Width;
        logoH = logo.Height;
 
        xPos = (origW - logoW) / 2;
        yPos = (origH - logoH) / 2;
 
        gra.DrawImage(logo, new Point(xPos, yPos));
 
        Response.ContentType = "image/JPEG";
        original.Save(Server.MapPath("new.jpg"), ImageFormat.Jpeg);

Open in new window

0
 

Author Comment

by:dotsandcoms
ID: 24065924
Hi,

After merging the two images the resulted image is not good and that is not required. I am attaching the two images. Merge them and see the result and let me know your comments.

Regards

Glenn
0
 

Author Comment

by:dotsandcoms
ID: 24066015
Please find the attached two images.
imagetomerge.jpg
rose-peace-500.jpg
0
 
LVL 23

Accepted Solution

by:
apresto earned 500 total points
ID: 24066881
Cgabge you code to thisI changed the overlay code to this:
gra.DrawImage(logo, xPos, yPos, logoW, logoH); instead of this:
gra.DrawImage(logo, new Point(xPos, yPos));

The image i got is attached

string s = Server.MapPath("imagetomerge.jpg");
            string s2 = Server.MapPath("rose-peace-500.jpg");
 
            System.Drawing.Image original = Bitmap.FromFile(s);
            Graphics gra = Graphics.FromImage(original);
            System.Drawing.Image logo = Bitmap.FromFile(s2);
 
            int origW, origH, logoW, logoH, xPos, yPos;
            origW = original.Width;
            origH = original.Height;
            logoW = logo.Width;
            logoH = logo.Height;
 
            xPos = (origW - logoW) / 2;
            yPos = (origH - logoH) / 2;
 
            gra.DrawImage(logo, xPos, yPos, logoW, logoH);
 
            Response.ContentType = "image/JPEG";
            original.Save(Server.MapPath("new.jpg"), ImageFormat.Jpeg);

Open in new window

new.jpg
0
 

Author Comment

by:dotsandcoms
ID: 24067082
yes the merged image is good.

I am resizing the second image through code and quality of second image is getting disturb. See the attach code file and original image which i want to resize to get the second image and finally i want to merge this second image with white background image.

Hope you will assist me.

many thanks
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading;
 
public partial class _Default : System.Web.UI.Page
{    
    private string Finalimagename = "";    
 
    protected void Page_Load(object sender, EventArgs e)
    {
         
    }
    protected void btnUpload1_Click(object sender, EventArgs e)
    {
        ImageUpload();
    }
 
    private void ImageUpload()
    {       
        /* this code used to make directory name RealImage */        
        Directory.CreateDirectory(Server.MapPath("RealImage\\"));       
        HtmlInputFile htmlFile = (HtmlInputFile)BrowseImage0;
        if (htmlFile.PostedFile.ContentLength > 0)
        {
            string sFormat = String.Format("{0:#.##}", (float)htmlFile.PostedFile.ContentLength / 2048);
            if (float.Parse(sFormat) < float.Parse("2048"))
            {
                if (htmlFile.PostedFile != null)
                {
                    ViewState["ImageName"] = htmlFile.PostedFile.FileName.Substring(htmlFile.PostedFile.FileName.LastIndexOf("\\") + 1);//browseImagePath[0];                    
                }
                else
                {
                    ViewState["ImageName"] = "";
                }
            }
            else
            {
                lblError1.Visible = true;
                lblError1.Text = "Image Size is Large, please resize it !!";                
            }
        }
        else
        {
            ViewState["ImageName"] = "";
            if (ViewState["ImageName"].ToString() == "")
            {
                lblError1.Visible = true;
                lblError1.Text = "Attach an image to upload";
            }
            return;
        }
 
        //This function is used to make image thumbnail
        MakeThumbnail();
    }
    
    //Return thumbnail callback
    public bool ThumbnailCallback()
    {
        return true;
    }
 
    //For image thumbnial
    private void MakeThumbnail()
    {
        System.Drawing.Image myThumbnail150;
        object obj = new object();
        obj = BrowseImage0;
        System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        HtmlInputFile hFile = (HtmlInputFile)obj;
        if (hFile.PostedFile != null && hFile.PostedFile.ContentLength > 0)
        {
            //this code used to remove some symbols between image name and replace with space
            string imgname1 = hFile.PostedFile.FileName.Replace('%', ' ').Substring(hFile.PostedFile.FileName.LastIndexOf("\\") + 1);
            string imgname2 = imgname1.Replace('#', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname3 = imgname2.Replace('@', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname4 = imgname3.Replace(',', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            string imgname5 = imgname4.Replace('&', ' ').Substring(imgname1.LastIndexOf("\\") + 1);
            
            Finalimagename = imgname5.ToString();
 
            string imgname = hFile.PostedFile.FileName.Substring(hFile.PostedFile.FileName.LastIndexOf("\\") + 1);
            string sExtension = imgname.Substring(imgname.LastIndexOf(".") + 1);
 
            //this code is used to check image extension
            if (sExtension.ToLower() == "jpg" || sExtension.ToLower() == "gif" || sExtension.ToLower() == "bmp" || sExtension.ToLower() == "jpeg")
            {
                if (!File.Exists(MapPath("RealImage\\" + Finalimagename)))
                {
                    hFile.PostedFile.SaveAs(ResolveUrl(Server.MapPath("RealImage\\" + Finalimagename)));
 
                    System.Drawing.Image imagesize = System.Drawing.Image.FromFile(ResolveUrl(Server.MapPath("RealImage\\" + Finalimagename)));
                    
                    //Bitmap bitmapNew = new Bitmap(imagesize);
                    if (imagesize.Width < imagesize.Height)
                    {
 
                        //myThumbnail150 = bitmapNew.GetThumbnailImage(150 * imagesize.Width / imagesize.Height, 150, myCallback, IntPtr.Zero);
                        myThumbnail150 = imagesize.GetThumbnailImage(150 * imagesize.Width / imagesize.Height, 150, myCallback, IntPtr.Zero);
                    }
                    else
                    {
                        //myThumbnail150 = bitmapNew.GetThumbnailImage(150, imagesize.Height * 150 / imagesize.Width, myCallback, IntPtr.Zero);
                        myThumbnail150 = imagesize.GetThumbnailImage(150, imagesize.Height * 150 / imagesize.Width, myCallback, IntPtr.Zero);
                    }
                    
                        //Create a new directory name ThumbnailImage
                        Directory.CreateDirectory(Server.MapPath("ThumbnailImage"));
                        //Save image in TumbnailImage folder
                        myThumbnail150.Save(ResolveUrl(Server.MapPath("ThumbnailImage\\")) + Finalimagename, System.Drawing.Imaging.ImageFormat.Jpeg);
                        
                    //=============================
                        //Merging of two images
 
                        string s = Server.MapPath("imagetomerge.jpg");
                        string s2 = Server.MapPath("ThumbnailImage\\" + Finalimagename);
 
 
 
                       
 
                        System.Drawing.Image original = Bitmap.FromFile(s);
                        Graphics gra = Graphics.FromImage(original);
                        System.Drawing.Image logo = Bitmap.FromFile(s2);
 
                        int origW, origH, logoW, logoH, xPos, yPos;
                        origW = original.Width;
                        origH = original.Height;
                        logoW = logo.Width;
                        logoH = logo.Height;
 
                        xPos = (origW - logoW) / 2;
                        yPos = (origH - logoH) / 2;
 
                        gra.DrawImage(logo, xPos, yPos, logoW, logoH);
 
                        Response.ContentType = "image/JPEG";
                        original.Save(Server.MapPath("new.jpg"), ImageFormat.Jpeg);
 
 
                    //===================================
                        //Image1.ImageUrl = "RealImage/" + Finalimagename;
                        //Image2.ImageUrl = "data2/t_" + Finalimagename;
                    MessageLabel.Text = "Successfully uploaded";
                   
                }
            }
            else
            {
                lblError1.Visible = true;
                lblError1.Text = "Check image extension";
            }
        }
    }
}

Open in new window

ais198a.jpg
0
 

Author Comment

by:dotsandcoms
ID: 24067086
any code to sharp the resize image?
0
 

Author Comment

by:dotsandcoms
ID: 24076869
i am waiting for your reply.
0
 
LVL 23

Expert Comment

by:apresto
ID: 24084924
I dont think its possible to resize without losing some quality because you are reducing the number of pixels. See here:
http://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality 
0
 

Author Closing Comment

by:dotsandcoms
ID: 31565718
good one
0
 
LVL 23

Expert Comment

by:apresto
ID: 24105807
Glad i could help, but I dont think it should have been given a B just because i told you that you cant do anything about the image quality on programatical resize. There isnt much i can do about that, and i did what i could to help with the actual image overlay
Apresto
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question