---
# System prepended metadata

title: ASP.NET Core Zxing.NET ImageSharp を使用した QRコードの生成・読込のサンプル 2023-07-27
tags: [ImageSharp, Webアプリ, C#, Webカメラ, Zxing.NET, バーコード, ASP.NET Core]

---

---
lang: ja-jp
breaks: true
---
# 参考資料

> ASP.NET Core - Read OR Generate QR Code | Zxing.NET
> https://www.youtube.com/watch?v=JLCqxFPZckk

## プロジェクトを作成

![](https://hackmd.io/_uploads/HJ29e8ys3.png)

![](https://hackmd.io/_uploads/HJ2oeLyo2.png)

## wwwroot/images を作成

![](https://hackmd.io/_uploads/BkWvWUks2.png)


## csproj

```xml=
・・・
  <ItemGroup>
    <PackageReference Include="SixLabors.ImageSharp" Version="3.0.1" />
    <PackageReference Include="ZXing.Net" Version="0.16.9" />
    <PackageReference Include="ZXing.Net.Bindings.ImageSharp.V2" Version="0.16.15" />
  </ItemGroup>
・・・
```

## Controllers/HomeController.cs

```csharp=
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using QRCodeGenerateRead.Models;
using ZXing;
using ZXing.QrCode;

namespace QRCodeGenerateRead.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IWebHostEnvironment _hostEnvironment;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment hostEnvironment)
    {
        _logger = logger;
        _hostEnvironment = hostEnvironment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(IFormCollection formCollection)
    {
        string? contents = formCollection["QRCodeString"];

        if (string.IsNullOrEmpty(contents) == false)
        {
            var hints = new Dictionary<EncodeHintType, object>()
            {
                { EncodeHintType.CHARACTER_SET, "UTF-8" }
            };
            var writer = new QRCodeWriter();
            var resultBit = writer.encode(contents, ZXing.BarcodeFormat.QR_CODE, 200, 200, hints);
            var matrix = resultBit;
            int scale = 2;

            using (var image = new Image<Rgba32>(matrix.Width * scale, matrix.Height * scale))
            {
                for (int x = 0; x < matrix.Height; x++)
                {
                    for (int y = 0; y < matrix.Width; y++)
                    {
                        Color pixel = matrix[x, y] ? Color.Black : Color.White;
                        for (int i = 0; i < scale; i++)
                        {
                            for (int j = 0; j < scale; j++)
                            {
                                image[x * scale + i, y * scale + j] = pixel;
                            }
                        }
                    }
                }

                string webRootPath = _hostEnvironment.WebRootPath;
                if (Directory.Exists(webRootPath + "/images") == false)
                {
                    Directory.CreateDirectory(webRootPath + "/images");
                }
                await image.SaveAsPngAsync(webRootPath + "/images/QRCode.png");
                ViewBag.URL = "/images/QRCode.png";
            }
        }

        return View();
    }

    public IActionResult ReadQRCode()
    {
        string webRootPath = _hostEnvironment.WebRootPath;

        var path = webRootPath + "/images/QRCode.png";
        using (var image = Image.Load<Rgba32>(path))
        {
            LuminanceSource source = new ZXing.ImageSharp.ImageSharpLuminanceSource<Rgba32>(image);

            var reader = new BarcodeReaderGeneric();
            Result result = reader.Decode(source);

            ViewBag.Text = result.Text;
        }
        return View("Index");
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
```

## View/Home/Index.cshtml

```html=
@{
    ViewData["Title"] = "Home Page";
}

<br />
<form asp-controller="Home" asp-action="Index">
    <div class="col-lg-12">Enter QR Code String</div>
    <Br />
    <div class="col-lg-12">
        <textarea name="QRCodeString" id="QRCodeString" class="form-control"></textarea>

    </div>
    <br />
    <br />
    <div class="col-lg-12">
        <input type="submit" value="Generate QR Code" class="btn btn-primary" />
    </div>
    <br />
    <br />
</form>

@if (!string.IsNullOrEmpty(ViewBag.URL))
{
    <div class="col-lg-12">
        <img src="@ViewBag.URL" />
    </div>
}

<div class="col-lg-12">
    <a href="/Home/ReadQRCode">Read Image and show text</a>
</div>

@if (!string.IsNullOrEmpty(ViewBag.Text))
{
    <div class="col-lg-12">
        QR Code int Text -> @ViewBag.Text
    </div>
}
```