• C# 文字转Bitmap,Bitmap转为字节流或Bitmap转为图片


    1.文字转为Bitmap:

    /// <summary>
    /// 把文字转换才Bitmap
    /// </summary>
    /// <param name="text"></param>
    /// <param name="font"></param>
    /// <param name="rect">用于输出的矩形,文字在这个矩形内显示,为空时自动计算</param>
    /// <param name="fontcolor">字体颜色</param>
    /// <param name="backColor">背景颜色</param>
    /// <returns></returns>
    private static Bitmap TextToBitmap(string text, Font font, Rectangle rect, Color fontcolor, Color backColor)
    {
    Graphics g;
    Bitmap bmp;
    StringFormat format = new StringFormat(StringFormatFlags.NoClip);
    if (rect == Rectangle.Empty)
    {
    bmp = new Bitmap(1, 1);
    g = Graphics.FromImage(bmp);
    //计算绘制文字所需的区域大小(根据宽度计算长度),重新创建矩形区域绘图
    SizeF sizef = g.MeasureString(text, font, PointF.Empty, format);

    int width = (int)(sizef.Width + 1);
    int height = (int)(sizef.Height + 1);
    rect = new Rectangle(0, 0, width, height);
    bmp.Dispose();

    bmp = new Bitmap(width, height);
    }
    else
    {
    bmp = new Bitmap(rect.Width, rect.Height);
    }

    g = Graphics.FromImage(bmp);

    //使用ClearType字体功能
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
    g.FillRectangle(new SolidBrush(backColor),rect);
    g.DrawString(text, font, new SolidBrush(fontcolor), rect, format);
    return bmp;
    }

    2.Bitmap转为字节流:

    /// <summary>

    /// bitmap转换为字节流
    /// </summary>
    /// <param name="bitmap"></param>
    /// <returns></returns>
    public static byte[] BitmapByte(Bitmap bitmap)
    {
    using (MemoryStream stream = new MemoryStream())
    {
    bitmap.Save(stream, ImageFormat.Png);
    byte[] data = new byte[stream.Length];
    stream.Seek(0, SeekOrigin.Begin);
    stream.Read(data, 0, Convert.ToInt32(stream.Length));
    return data;
    }
    }

    3.Bitmap转为图片:

    Bitmap bmp = TextToBitmap(text, font, Rectangle.Empty, fontcolor, backColor);
    bmp.Save(@"D: est.bmp", ImageFormat.Png);

  • 相关阅读:
    [转]手工实现RTTI
    小楫轻舟
    百年孤独
    The power of now
    [转帖]Android平台下OpenGL初步
    设计模式六大原则(5):迪米特法则
    设计模式六大原则(4):接口隔离原则
    设计模式六大原则(3):依赖倒置原则
    设计模式六大原则(1):单一职责原则
    设计模式六大原则(2):里氏替换原则
  • 原文地址:https://www.cnblogs.com/wlming/p/14228746.html
Copyright © 2020-2023  润新知