2007年8月9日 星期四

產生 BarCode 的方法

產生BarCode比較常見的方式,是透過 third-party提供元件來產生
居多,但是會根據不同的開發工具而有個別對應的BarCode產生元件
。當然,比較有彈性的方法,就是自己寫,缺點就是要花時間。日前
我在藍色小舖找到一篇不錯的文章,其作法可供為參考。

他主要作法,是先安裝BarCode字型,當USER輸入文字後,將這些文字
轉換成對應的BarCode字型,然後將這些BarCode以繪圖的模式輸出成
圖形檔。而我們在畫面中,則是利用<img>的方式,將BarCode圖檔秀
出來。

藍色小舖資料來源如下:

網頁上的即時條碼產生--->使用VB.Net
類別 :
ASP.NET ,
摘要 :
即時產生條碼的程式

Response.Expires = 0
Dim BMP As Bitmap = New Bitmap(320, 250, Imaging.PixelFormat.Format32bppPArgb)
Dim G As Graphics = Graphics.FromImage(BMP)
Dim 來源影像 As Image = Image.FromFile(Request.PhysicalApplicationPath + "logo.jpg") ' 讀取背景影像進來
G.DrawImage(來源影像, New Rectangle(0, 0, 320, 250), New Rectangle(0, 0, 210, 60), GraphicsUnit.Pixel)
Dim 字型 As Font = New Font("IDAutomationHC39M", 25) <--- 這行是重點, 自行到網路上抓取該條碼字型吧
Dim 筆刷 As Brush = New SolidBrush(ColorTranslator.FromHtml("Gold")) < --- 這裡是條碼顏色
G.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
G.DrawString("123456", 字型, 筆刷, 50, 15) < --- 印出條碼
BMP.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)

想要顯示條碼的部分, 加上這段就可以囉
另外, 需
Imports system.drawing




改成C#後的程式如下:


using System.Drawing;
using System.IO;



 
private void Button1_Click(object sender, System.EventArgs e)
{

Bitmap BMP=new Bitmap(420, 100, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics G=Graphics.FromImage(BMP);
System.Drawing.Image IMGSource= System.Drawing.Image.FromFile( Server.MapPath("images/logo.jpg"));

/* 預先要準備一張空白畫面的背景圖,範例中是指 logo.jpg */
G.DrawImage( IMGSource, new Rectangle(0, 0, 420, 100), new Rectangle(0, 0, 210, 30), GraphicsUnit.Pixel);
System.Drawing.Font F=new Font("IDAutomationHC39M", 14);

/* 指定所要選用的字型,也就是 BarCode 字型,以及字型大小 */

System.Drawing.Brush B= new SolidBrush( ColorTranslator.FromHtml("Black")) ;

/* 設定字型顏色 */
G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
G.DrawString( string.Format( "*{0}*",TextBox1.Text),F,B,30,15);

/* 指訂要轉換成BarCode的內容,在字首字尾須加星號(請參考BarCode - Code39的規範) */


BMP.Save( Server.MapPath("images/kk.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg );

/* 將結果輸出成圖片,檔名為 kk.jpg */
/* 另一種呈現方式,只需要一張暫存圖片。 */

Byte[] bf =new byte[10];
ReadBinaryFile(ref bf,Server.MapPath("images/kk.jpg"));
Session["BarCode"]=bf;
IMGSHOW.Src="ShowPic.aspx";
}
private bool ReadBinaryFile(ref Byte[] buffer,string FilePath)
{
//System.IO.File MyFile;
System.IO.Stream FileStream;
if(!File.Exists(FilePath))
return false;


FileStream=File.OpenRead(FilePath);
buffer=new Byte[FileStream.Length];
FileStream.Read(buffer,0,Convert.ToInt32(FileStream.Length));
FileStream.Close();
return true;
}
 
 
public class ShowPic : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.BinaryWrite((byte[])Session["BarCode"]);
Response.End();
}


}

沒有留言:

張貼留言