iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 2
0
自我挑戰組

網路世界的奇怪冒險系列 第 2

【Day 2】 在Visual Studio 2017 寫一個QRcode產生器

大家好,相信大部分的人都有使用過LINE的QRcode功能,QRcode現在已經算滿普遍的應用,因此今天跟大家一起學習如何寫QRcode產生器。

Step 1. 首先先建立專案
https://ithelp.ithome.com.tw/upload/images/20190918/201120009yQkzkGtJU.png

https://ithelp.ithome.com.tw/upload/images/20190918/20112000YcJdEcoatV.png

Step 2.使用Zxing套件

https://ithelp.ithome.com.tw/upload/images/20190918/20112000ETlOboE45t.png

https://ithelp.ithome.com.tw/upload/images/20190918/20112000WD3w8JiMSU.png

https://ithelp.ithome.com.tw/upload/images/20190918/20112000ULFMqw9uJx.png

Step 3.建立QRcode 頁面

先Using會使用的套件

using System.Drawing;
using System.Drawing.Imaging;
using ZXing;                  // for BarcodeWriter
using ZXing.QrCode;           // for QRCode Engine

Controller程式

        public ActionResult QRcode()
        {

            var writer = new BarcodeWriter  //dll裡面可以看到屬性
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new QrCodeEncodingOptions //設定大小
                {
                    Height = 500,
                    Width = 500,
                }
            };
            //產生QRcode
            var img = writer.Write("https://www.ithome.com.tw/");
            string FileName = "ithome";
            Bitmap myBitmap = new Bitmap(img);
         
            string filePath = string.Format("F:\\{0}.bmp", FileName);
            ViewBag.filePath = filePath;

          
            myBitmap.Save(filePath, ImageFormat.Bmp);

            ViewBag.IMG = myBitmap;

            return View();
        }

https://ithelp.ithome.com.tw/upload/images/20190918/20112000FfXONG7n1Z.png

Step 4. 寫一個方法 讓圖片顯示在View上

在Controller中加上

        public ActionResult PhotoGet()
        {
            string FileName = "ithome";
            string filepath = string.Format("F:\\{0}.bmp", FileName);
            byte[] filedata = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filepath,
                Inline = false
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(filedata, contentType);
        }

Step5. View的語法
在View中加上

@{
    ViewBag.Title = "QRcode";
}

<h2>QRcode</h2>

<div align="center"><img src="@Url.Action("PhotoGet", "Home")" width="500" /></div>

https://ithelp.ithome.com.tw/upload/images/20190918/20112000BYwvLYxVBC.png

Step6.完成畫面

https://ithelp.ithome.com.tw/upload/images/20190918/20112000O8KjoJ437w.png

參考網址:
C# 用 ZXing 產生 QR Code QR Code generator using ZXing

How to return any type of file from MVC action method?


上一篇
【Day 1】 在Visual Studio 2017 依季節顯示不同訊息
下一篇
【Day 3】 練習撈出一週日期的SQL語法
系列文
網路世界的奇怪冒險30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言