简体   繁体   中英

How can I create from two images a new image which inside there will be the two images side by side?

I tried this code:

private void CreateAnimatedGif(string FileName1 , string FileName2)
        {
            Bitmap file1 = new Bitmap(FileName1);
            Bitmap file2 = new Bitmap(FileName2);
            Bitmap bitmap = new Bitmap(file1.Width + file2.Width, Math.Max(file1.Height, file2.Height));
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.DrawImage(file1, 0, 0);
                g.DrawImage(file2, file1.Width, 0);
            }
            bitmap.Save(@"d:\test.gif", System.Drawing.Imaging.ImageFormat.Gif);
        }

In general it's working. But the result is not good enough.

  1. The first image since the code try to make it in same size in the height I see some black space on the bottom.

  2. The second image is bigger then the first one. The second image is on the right. So I need that it will make the left image the first one to be the same size/resolution of the second one.

How can I fix this code for that?

This is an example of the new image result after combined the two. And why it's not good as I wanted:

在此处输入图片说明

You can resize the left image and set some graphics property to get a better quality and try to don't lose the quality :

using (Graphics g = Graphics.FromImage(bitmap))
{       
     //high quality rendering and interpolation mode
     g.SmoothingMode = SmoothingMode.HighQuality; 
     g.PixelOffsetMode = PixelOffsetMode.HighQuality; 
     g.InterpolationMode = InterpolationMode.HighQualityBicubic;

     //resize the left image
     g.DrawImage(file1, new Rectangle(0, 0, file1.Width, file2.Height));
     g.DrawImage(file2, file1.Width, 0);
}

The result is:

在此处输入图片说明

Or if you want to resize it proportionally to the new height just use:

//calculate the new width proportionally to the new height it will have
int newWidth =  file1.Width + file1.Width / (file2.Height / (file2.Height - file1.Height));
Bitmap bitmap = new Bitmap(newWidth + file2.Width, Math.Max(file1.Height, file2.Height));
using (Graphics g = Graphics.FromImage(bitmap))
{       
     //high quality rendering and interpolation mode
     g.SmoothingMode = SmoothingMode.HighQuality; 
     g.PixelOffsetMode = PixelOffsetMode.HighQuality; 
     g.InterpolationMode = InterpolationMode.HighQualityBicubic;

     //resize the left image
     g.DrawImage( file1, new Rectangle( 0, 0, newWidth, file2.Height ) );
     g.DrawImage(file2, newWidth, 0);
}

Infact the result is better:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM