C# - 将文本与图像合并

时间:2014-03-28 15:19:12

标签: c# image text merge

我编写了以下用于合并2个图像的代码。我的需求很简单,图像总是大小相同,所以不需要定位。我可以稍后处理...我想知道的是,我可以修改它将文本标签合并为我的imgFront到图像上,imgBack。最后返回的结果将是一个新文本,我的文字位于顶部。

这可能吗?怎么样?

public static byte[] ImageMerge(Image imgBack, Image imgFront, Int32 width = 200, Int32 height = 200)
{
    using (imgBack)
    {
        using (var bitmap = new Bitmap(width, height))
        {
            using (var canvas = Graphics.FromImage(bitmap))
            {
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                canvas.DrawImage(imgBack, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
                canvas.DrawImage(imgFront, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
                canvas.Save();
            }
            try
            {
                return ImageToByte(bitmap);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是完成的代码。我无法相信我没有早点分享!

public static byte[] ImageTextMerge(Image imgBack, string str, Int32 x, Int32 y, Int32 w, Int32 h, Int32 width = 200, Int32 height = 200)
{
    using (imgBack)
    {
        using (var bitmap = new Bitmap(width, height))
        {
            using (var canvas = Graphics.FromImage(bitmap))
            {
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                canvas.DrawImage(imgBack, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);

                // Create font and brush
                Font drawFont = new Font("Arial", 20);
                SolidBrush drawBrush = new SolidBrush(Color.Black);

                // Create rectangle for drawing. 
                RectangleF drawRect = new RectangleF(x, y, w, h);

                // Draw rectangle to screen.
                Pen blackPen = new Pen(Color.Transparent);
                canvas.DrawRectangle(blackPen, x, y, w, h);

                // Set format of string.
                StringFormat drawFormat = new StringFormat();
                drawFormat.Alignment = StringAlignment.Near;

                // Draw string to screen.
                canvas.DrawString(str, drawFont, drawBrush, drawRect, drawFormat);
                canvas.Save();
            }
            try
            {
                return ImageToByte(bitmap);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}