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:\test.bmp", ImageFormat.Png);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM