twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

F# 生成 QRcode #370

Open twn39 opened 2 years ago

twn39 commented 2 years ago

代码:

open System.Drawing.Imaging
open ZXing
open ZXing.QrCode
open ZXing.QrCode.Internal

[<EntryPoint>]
let main argv =
    let writer = BarcodeWriter(Format = BarcodeFormat.QR_CODE,
                               Options = QrCodeEncodingOptions(ErrorCorrection = ErrorCorrectionLevel.Q,
                                                               CharacterSet = "UTF-8",
                                                               Height = 400,
                                                               Width = 400,
                                                               Margin = 1))
    let image = writer.Write("Hello world!")
    image.Save("barcode.jpg", ImageFormat.Jpeg)
    0
twn39 commented 2 years ago

Aspnet core 集成 ZXing.net 代码:

[<ApiController>]
[<Route("/")>]
type BarCodeController (logger : ILogger<BarCodeController>) =
    inherit ControllerBase()

    [<HttpGet>]
    [<Route("/barcode")>]
    member _.Get() =
        let barCodeWriter = BarcodeWriter(Format = BarcodeFormat.QR_CODE,
                                          Options = QrCodeEncodingOptions(ErrorCorrection = ErrorCorrectionLevel.Q,
                                                                          Width=400,
                                                                          Height=400,
                                                                          Margin=1))
        let image = barCodeWriter.Write("Hello world!")
        let ms = new MemoryStream()
        image.Save(ms, ImageFormat.Png)
        let file = FileContentResult(ms.ToArray(), "images/png")
        file.FileDownloadName <- "barcode.png"
        file
        //let base64 = Convert.ToBase64String(ms.ToArray())
        //$"data:image/png;base64,{base64}"