Quick Start: Use Go language functions to implement simple image verification code generation function

王林
Release: 2023-07-30 21:09:33
Original
1657 people have browsed it

Title: Quick Start: Using Go language functions to implement simple image verification code generation function

In modern network applications, verification codes are a very important security protection measure. It determines whether the user is a real person by showing the user a picture with random characters and asking the user to enter the characters they see. In this article, we will use Go language functions to implement a simple image verification code generation function.

Before we start, we first need to install the Go language development environment. The corresponding version can be downloaded and installed on the official website https://golang.org/dl/.

First, we need to import some Go language libraries. Use the following code snippet to import the libraries you need to use.

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math/rand"
    "os"
    "time"
)
Copy after login

Next, we define a function to generate random characters. We can choose to use characters such as numbers, uppercase and lowercase letters, etc. as the generated random characters. Here we take numbers as an example. The code is as follows:

func generateRandomCode(length int) string {
    rand.Seed(time.Now().UnixNano())
    code := ""
    for i := 0; i < length; i++ {
        code += fmt.Sprintf("%d", rand.Intn(10))
    }
    return code
}
Copy after login

In this function, we use the Intn function in the rand package to generate a random integer between 0 and 9 and convert it to a string. Add to the code until it reaches the specified length.

Next, we define a function to generate a verification code image. The code is as follows:

func generateCaptchaImage(code string) {
    // 创建一个空白图片
    imgWidth := 200
    imgHeight := 100
    bgColor := color.RGBA{220, 220, 220, 255}
    img := image.NewRGBA(image.Rect(0, 0, imgWidth, imgHeight))
    draw.Draw(img, img.Bounds(), &image.Uniform{bgColor}, image.ZP, draw.Src)

    // 设置字体样式
    fontFile, err := os.Open("font.ttf")
    if err != nil {
        fmt.Println("Open font file failed:", err)
        return
    }
    defer fontFile.Close()
    font, err := truetype.Parse(fontFile)
    if err != nil {
        fmt.Println("Load font failed:", err)
        return
    }
    fontSize := 50
    fontDPI := 72.0
    c := freetype.NewContext()
    c.SetDPI(fontDPI)
    c.SetFont(font)
    c.SetFontSize(float64(fontSize))
    c.SetClip(img.Bounds())
    c.SetDst(img)
    c.SetSrc(&image.Uniform{color.RGBA{0, 0, 0, 255}})

    // 在图片上绘制字符
    pt := freetype.Pt(10, 70)
    for _, ch := range code {
        _, err = c.DrawString(string(ch), pt)
        if err != nil {
            fmt.Println("Draw string failed:", err)
            return
        }
        pt.X += c.PointToFixed(float64(fontSize * 5 / 7))
    }

    // 保存图片到本地文件
    file, err := os.Create("captcha.png")
    if err != nil {
        fmt.Println("Create image file failed:", err)
        return
    }
    defer file.Close()
    err = png.Encode(file, img)
    if err != nil {
        fmt.Println("Encode image failed:", err)
        return
    }
    fmt.Println("Captcha image generated successfully.")
}
Copy after login

In this function, we first create a blank RGBA image and set the background color. After that, we use the truetype package to read and load the custom font file and set the text style. Then, we use the Context type of the freetype package to perform drawing operations on the image. Finally, we save the generated image locally.

Finally, we write a main function and call the above function to generate a verification code image. The complete code is as follows:

package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math/rand"
    "os"
    "time"

    "github.com/golang/freetype"
    "golang.org/x/image/font/gofont/goregular"
)

func generateRandomCode(length int) string {
    rand.Seed(time.Now().UnixNano())
    code := ""
    for i := 0; i < length; i++ {
        code += fmt.Sprintf("%d", rand.Intn(10))
    }
    return code
}

func generateCaptchaImage(code string) {
    imgWidth := 200
    imgHeight := 100
    bgColor := color.RGBA{220, 220, 220, 255}
    img := image.NewRGBA(image.Rect(0, 0, imgWidth, imgHeight))
    draw.Draw(img, img.Bounds(), &image.Uniform{bgColor}, image.ZP, draw.Src)

    font, err := freetype.ParseFont(goregular.TTF)
    if err != nil {
        fmt.Println("Load font failed:", err)
        return
    }
    fontSize := 50
    fontDPI := 72.0
    c := freetype.NewContext()
    c.SetDPI(fontDPI)
    c.SetFont(font)
    c.SetFontSize(float64(fontSize))
    c.SetClip(img.Bounds())
    c.SetDst(img)
    c.SetSrc(&image.Uniform{color.RGBA{0, 0, 0, 255}})

    pt := freetype.Pt(10, 70)
    for _, ch := range code {
        _, err = c.DrawString(string(ch), pt)
        if err != nil {
            fmt.Println("Draw string failed:", err)
            return
        }
        pt.X += c.PointToFixed(float64(fontSize * 5 / 7))
    }

    file, err := os.Create("captcha.png")
    if err != nil {
        fmt.Println("Create image file failed:", err)
        return
    }
    defer file.Close()
    err = png.Encode(file, img)
    if err != nil {
        fmt.Println("Encode image failed:", err)
        return
    }
    fmt.Println("Captcha image generated successfully.")
}

func main() {
    code := generateRandomCode(4)
    generateCaptchaImage(code)
}
Copy after login

In the main function, we first generate a random 4-digit verification code, In the next line, call the generateCaptchaImage function to generate the verification code image.

After completing the above steps, we can execute the go run main.go command in the terminal to run the program, and it will generate a verification code image named captcha.png.

Through the code examples in this article, we learned how to use Go language functions to generate simple image verification codes. Of course, in actual applications, we need to add more functions to implement user input verification, refresh verification codes and other functions, but the sample code shown in this article provides us with a basis for quick start.

I hope that through studying this article, I can have some understanding of using Go language to realize the image verification code generation function. Happy programming!

The above is the detailed content of Quick Start: Use Go language functions to implement simple image verification code generation function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!