c# 生成文字图片和合并图片的示例

生成文字图片:

/// 
    /// 生成文字图片
    /// 
    /// 
    /// 
    /// 
    public Image CreateImage(string text, bool isBold, int fontSize)
    {
      int wid = 400;
      int high = 200;
      Font font;
      if (isBold)
      {
        font = new Font("Arial", fontSize, FontStyle.Bold);

      }
      else
      {
        font = new Font("Arial", fontSize, FontStyle.Regular);

      }
      //绘笔颜色
      SolidBrush brush = new SolidBrush(Color.Black);
      StringFormat format = new StringFormat(StringFormatFlags.NoClip);
      Bitmap image = new Bitmap(wid, high);
      Graphics g = Graphics.FromImage(image);
      SizeF sizef = g.MeasureString(text, font, PointF.Empty, format);//得到文本的宽高
      int width = (int)(sizef.Width + 1);
      int height = (int)(sizef.Height + 1);
      image.Dispose();
      image = new Bitmap(width, height);
      g = Graphics.FromImage(image);
      g.Clear(Color.White);//透明

      RectangleF rect = new RectangleF(0, 0, width, height);
      //绘制图片
      g.DrawString(text, font, brush, rect);
      //释放对象
      g.Dispose();
      return image;
    }

合并图片:

/// 
    /// 合并图片
    /// 
    /// 
    /// 
    /// 
    public static Bitmap CombinImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0)
    {

      Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height + img.Height);

      Graphics g = Graphics.FromImage(bmp);
      g.Clear(Color.White);
      g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);

      //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框

      //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);

      g.DrawImage(img, imgBack.Width / 2 - img.Width / 2 + xDeviation, imgBack.Height + yDeviation, img.Width, img.Height);
      GC.Collect();
      return bmp;
    }
/// 
    /// Resize图片
    /// 
    /// 原始Bitmap
    /// 新的宽度
    /// 新的高度
    /// 保留着,暂时未用
    /// 处理以后的图片
    public static Image ResizeImage(Image bmp, int newW, int newH, int mode)
    {
      try
      {
        Image b = new Bitmap(newW, newH);
        Graphics g = Graphics.FromImage(b);

        // 插值算法的质量
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height),
              GraphicsUnit.Pixel);
        g.Dispose();
        return b;
      }
      catch
      {
        return null;
      }
    }

MemoryStream保存到图片

     Bitmap bmp = CombinImage(ms, img1);
     MemoryStream ms = new MemoryStream();
     bmp.Save(ms, ImageFormat.Png);  

以上就是c# 生成文字图片和合并图片的示例的详细内容,更多关于c# 生成文字图片和合并图片的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(c# 生成文字图片和合并图片的示例)