c# -合并文本与图像

本文关键字:图像 文本 合并 | 更新日期: 2023-09-27 17:54:45

我为合并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;
            }
        }
    }
}

c# -合并文本与图像

下面是完整的代码。真不敢相信我没有早点分享!

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;
            }
        }
    }
}