Solved

Merge two images in ASP.NET 2.0 using C#

Posted on 2009-04-02
17
5,330 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
Comment Utility
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
Comment Utility
0
 

Author Comment

by:dotsandcoms
Comment Utility
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
 
LVL 23

Expert Comment

by:apresto
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

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

Accepted Solution

by:
apresto earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
any code to sharp the resize image?
0
 

Author Comment

by:dotsandcoms
Comment Utility
i am waiting for your reply.
0
 
LVL 23

Expert Comment

by:apresto
Comment Utility
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
Comment Utility
good one
0
 
LVL 23

Expert Comment

by:apresto
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
This video discusses moving either the default database or any database to a new volume.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now