[ASP.NET] 產出 QRcode - 網頁版 - 使用 Google ZXing

  • 6629
  • 0

摘要:[ASP.NET] 產出 QRcode - 網頁版 - 使用 Google ZXing

 

前一篇剛寫了「產出QRcode-網頁版-MessagingToolkit.QRCode 版」總覺得哪裡不對勁,明明大家都用 Google ZXing ,我幹嘛那麼反骨的去用連 DLL 都不太好找的 MessagingToolkit.QRcode 呢?於是又有了這一篇(還是再說怎麼產出) QR code,只是採用了不同的方法。

Google ZXing 目前為2.1版,你可以在「http://code.google.com/p/zxing/」下載

很多步驟在前一篇都說過了,這裡就不囉唆了,直接來看產出的程式碼

操作過程簡述:使用者在 TextBox1 輸入內容,然後觸發 Button1 的動作,丟到 MultiFormatWriter().encode 產出 bytematrix 內容,接著利用「WriteToFile」將 bytematrix 內容繪製成 Bitmap 接著轉存為 png 格式之圖檔。

protected void Button1_Click(object sender, EventArgs e)
{
    String xtime = DateTime.Now.Millisecond.ToString();  // 以 ms 隔開不同檔名,避免 browser cache        
    string docupath = Request.PhysicalApplicationPath; //抓取專案所在實際目錄路徑
    string Output_Name = docupath + "uploads\\qrcode" + xtime + ".png";
    // 在 web form 程式部分要特別注意專案之路徑
    ByteMatrix byteMatrix = new MultiFormatWriter().encode(TextBox1.Text,BarcodeFormat.QR_CODE, 350, 350);
    // encode(欲編碼內容, 格式, 寬, 高)
    WriteToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, Output_Name);
    // 將編碼後的 bytematrix 內容,依設定格式作檔案輸出
} // EOS Button1

// ---------------------------

public static void WriteToFile(ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, string xfile)
{  // 將 bytematrix 內容輸出存檔
    System.Drawing.Imaging.EncoderParameters eps = newSystem.Drawing.Imaging.EncoderParameters();
    eps.Param[0] = newSystem.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
    Bitmap bmap = MatrixToBitmap(matrix); //將 ByteMatrix 內容轉成 Bitmap 格式
    bmap.Save(xfile, format);  //輸出檔案的地方
} //EOS writeToFile

// ---------------------------

public static Bitmap MatrixToBitmap(ByteMatrix matrix)
{   //將 ByteMatrix 內容轉成 Bitmap 格式 ------
    int width = matrix.Width; //轉讀為 int 是為了避免每次在 loop 裡都要重新算
    int height = matrix.Height;
    Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    //依 ByteMatrix 內容,來輸出 Bitmap 格式
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != -1 ?ColorTranslator.FromHtml("0xFF000000") :ColorTranslator.FromHtml("0xFFFFFFFF"));
            // FromHtml("0xFF000000") 前景顏色、ColorTranslator.FromHtml("0xFFFFFFFF")) 背景顏色
        }
    }
    return bmap;
} // EOS toBitmap

 

程式碼大致上沒啥問題,跟著範例作準沒錯,不過拿著同一段文字,就可以發現 ZXing 與 MessagingToolkit.QRcode 編碼上的不同,而利用手機都可以做兩者編碼的正確解讀!!

原文:The state or quality of being green; verdure. The greenth of December.

Google ZXing 
 
Messaging
Toolkit
QRcode 

 

看來應該還蠻多很有趣的理論與應用可以發揮在 QRcode 上面。

~ End