简体   繁体   English

如何从两个图像创建一个新图像,其中两个图像并排放置?

[英]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:事实上,结果更好:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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