Home > Backend Development > Golang > How to use Golang to draw straight lines and curves on pictures

How to use Golang to draw straight lines and curves on pictures

王林
Release: 2023-08-22 13:48:30
Original
1795 people have browsed it

How to use Golang to draw straight lines and curves on pictures

How to use Golang to draw straight lines and curves on pictures

1. Introduction
In graphics processing, we often need to perform various drawing operations on pictures. Such as drawing straight lines and curves, etc. This article will introduce how to use Golang language to draw straight lines and curves on pictures, and give corresponding code examples.

2. Drawing a straight line
Drawing a straight line is one of the simplest graphics drawings. It is very convenient to use Golang's image package and draw package to draw straight lines. The following is a sample code for drawing a straight line:

package main

import (
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "os"
)

func main() {
    // 打开图片文件
    file, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 解码图片
    img, err := jpeg.Decode(file)
    if err != nil {
        panic(err)
    }

    // 创建一个可绘制区域
    bounds := img.Bounds()
    drawImg := image.NewRGBA(bounds)

    // 复制图片内容到绘制区域
    draw.Draw(drawImg, bounds, img, bounds.Min, draw.Src)

    // 绘制直线
    lineColor := color.RGBA{255, 0, 0, 255} // 红色直线
    start := image.Point{100, 100}         // 起点坐标
    end := image.Point{300, 300}           // 终点坐标
    drawLine(drawImg, start, end, lineColor)

    // 保存绘制后的图片
    outFile, err := os.Create("output.jpg")
    if err != nil {
        panic(err)
    }
    defer outFile.Close()

    jpeg.Encode(outFile, drawImg, &jpeg.Options{Quality: 100})
}

// 绘制直线
func drawLine(img draw.Image, start, end image.Point, c color.Color) {
    dx := abs(end.X - start.X)
    dy := abs(end.Y - start.Y)
    sx := 0
    if start.X < end.X {
        sx = 1
    } else {
        sx = -1
    }
    sy := 0
    if start.Y < end.Y {
        sy = 1
    } else {
        sy = -1
    }
    err := dx - dy

    for {
        img.Set(start.X, start.Y, c)
        if start.X == end.X && start.Y == end.Y {
            break
        }
        e2 := 2 * err
        if e2 > -dy {
            err -= dy
            start.X += sx
        }
        if e2 < dx {
            err += dx
            start.Y += sy
        }
    }
}

// 计算绝对值
func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
Copy after login

In the above code, first we open the image file that needs to be drawn and decode it into an image object. Then, we create a drawable area and copy the image content into the drawable area. Next, we call the drawLine() function to draw a straight line.

drawLine()The function uses the Bresenham algorithm, which draws line segments through step-by-step iteration. By setting the coordinates of the start and end points, we can draw a straight line in the drawing area. Finally, we save the drawn image to a file.

3. Drawing curves
Drawing curves is relatively complicated, but it can also be achieved using Golang's image and draw packages. The following is a sample code for drawing a Bezier curve:

package main

import (
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "math"
    "os"
)

func main() {
    // 打开图片文件
    file, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 解码图片
    img, err := jpeg.Decode(file)
    if err != nil {
        panic(err)
    }

    // 创建一个可绘制区域
    bounds := img.Bounds()
    drawImg := image.NewRGBA(bounds)

    // 复制图片内容到绘制区域
    draw.Draw(drawImg, bounds, img, bounds.Min, draw.Src)

    // 绘制贝塞尔曲线
    curveColor := color.RGBA{0, 255, 0, 255} // 绿色曲线
    controlPoints := []image.Point{
        {100, 100}, // 控制点1
        {200, 300}, // 控制点2
        {300, 100}, // 控制点3
    }
    drawCurve(drawImg, controlPoints, curveColor)

    // 保存绘制后的图片
    outFile, err := os.Create("output.jpg")
    if err != nil {
        panic(err)
    }
    defer outFile.Close()

    jpeg.Encode(outFile, drawImg, &jpeg.Options{Quality: 100})
}

// 绘制贝塞尔曲线
func drawCurve(img draw.Image, controlPoints []image.Point, c color.Color) {
    step := 0.01 // 步长
    stepNum := int(1 / step) + 1

    for t := 0; t <= stepNum; t++ {
        tf := float64(t) * step
        x, y := calculateBezier(controlPoints, tf)

        if x >= 0 && y >= 0 && x < img.Bounds().Dx() && y < img.Bounds().Dy() {
            img.Set(x, y, c)
        }
    }
}

// 计算贝塞尔曲线上的点
func calculateBezier(controlPoints []image.Point, t float64) (x, y int) {
    n := len(controlPoints) - 1
    x = 0
    y = 0

    for i := 0; i <= n; i++ {
        coeff := binomialCoefficient(n, i) * math.Pow(1-t, float64(n-i)) * math.Pow(t, float64(i))
        x += int(float64(controlPoints[i].X) * coeff)
        y += int(float64(controlPoints[i].Y) * coeff)
    }

    return x, y
}

// 计算二项式系数
func binomialCoefficient(n, k int) int {
    return factorial(n) / (factorial(k) * factorial(n-k))
}

// 计算阶乘
func factorial(n int) int {
    result := 1
    for i := 1; i <= n; i++ {
        result *= i
    }
    return result
}
Copy after login

In the above code, first we open the image file that needs to be drawn and decode it into an image object. Then, we create a drawable area and copy the image content into the drawable area. Next, we call the drawCurve() function to draw the Bezier curve.

drawCurve()The function uses the Bezier curve algorithm, which calculates the corresponding points on the curve based on the given control point array and parameter t. Please refer to relevant literature for specific algorithm details. Finally, we save the drawn image to a file.

4. Conclusion
This article introduces how to use Golang to draw straight lines and curves on pictures, and gives corresponding code examples. By using the image and draw packages, we can easily draw different graphics. Readers can further expand and optimize as needed.

References:

  1. Golang image package(https://golang.org/pkg/image/)
  2. Golang draw package(https://golang .org/pkg/image/draw/)

The above is the detailed content of How to use Golang to draw straight lines and curves on pictures. 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