Solved

Merge two images in ASP.NET 2.0 using C#

Posted on 2009-04-02
17
5,507 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

617 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