博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 /// <summary>
    /// 图像生成辅助类
    /// </summary>
    public class ImageHelper
    {

        public static Bitmap GetDeskBitMap(string url, string name, StringBuilder sb)
        {
            try
            {
                var xiaochengxuBitmap = UrlToImage(url);
                FontFamily fontFamily = new FontFamily("微软雅黑");
                Font font = new Font(fontFamily, 40);
                System.Drawing.Bitmap backgroundImage = Resource.desk;
                var res = DrawText(backgroundImage, xiaochengxuBitmap, name, font, Color.White, 260);
                return res;
            }
            catch (Exception ex)
            {
                sb.Append(ex.ToString());
                return null;
            }
        }

        public static Bitmap UrlToImage(string url)
        {
            WebClient mywebclient = new WebClient();
            byte[] Bytes = mywebclient.DownloadData(url);
            using (MemoryStream ms = new MemoryStream(Bytes))
            {
                Image tTempBitmap = Image.FromStream(ms);
                return (Bitmap)tTempBitmap;
            }
        }
        public static Bitmap DrawText(Bitmap original, Bitmap erweima, string text, Font font, Color color, int height)
        {
            Bitmap result = new Bitmap(original.Width, original.Height);
            using (Graphics graphics = Graphics.FromImage(result))
            {
                graphics.DrawImage(original, 0, 0);
                int x = (original.Width - erweima.Width) / 2;
                int y = (int)original.Height * 1 / 7 + (original.Height * 5 / 6 - erweima.Height) / 2;
                graphics.DrawImage(erweima, new Rectangle(x, y, erweima.Width, erweima.Height));
                Rectangle rect = new Rectangle(0, original.Height - height, original.Width, height);
                using (SolidBrush brush = new SolidBrush(color))
                {
                    using (StringFormat format = new StringFormat())
                    {
                        format.Alignment = StringAlignment.Center;
                        format.LineAlignment = StringAlignment.Center;
                        graphics.DrawString(text, font, brush, rect, format);
                    }
                }
            }
            return result;
        }

    }