Golang Image Processing: Learn how to add filter effects
Introduction: Image processing is one of the common requirements in program development, and using Golang for image processing is also An efficient and easy-to-use method. This article will introduce how to use Golang to add filter effects to images, with code examples.
1. Environment preparation
Before starting, make sure that the Golang development environment has been installed correctly and the dependent libraries related to image processing have been installed.
go get -u github.com/golang/image
2. Add filter effects
Now, we can start Learn how to add filter effects to images. Below we will introduce two common filter effects: grayscale filter and blur filter.
Grayscale filter converts the image to black and white. The following is a code example for using Golang to implement a grayscale filter effect:
package main import ( "image" "image/color" "image/jpeg" "image/png" "log" "os" ) func main() { // 打开图像文件 file, err := os.Open("input.jpg") if err != nil { log.Fatal(err) } defer file.Close() // 解码图像 img, err := jpeg.Decode(file) if err != nil { log.Fatal(err) } // 创建灰度图像 grayImg := image.NewGray(img.Bounds()) // 将每个像素点转换为灰度色彩 for x := 0; x < img.Bounds().Max.X; x++ { for y := 0; y < img.Bounds().Max.Y; y++ { gray := color.GrayModel.Convert(img.At(x, y)).(color.Gray) grayImg.Set(x, y, gray) } } // 创建输出图像文件 outFile, err := os.Create("output_gray.jpg") if err != nil { log.Fatal(err) } defer outFile.Close() // 编码并保存图像文件 err = jpeg.Encode(outFile, grayImg, &jpeg.Options{Quality: 100}) if err != nil { log.Fatal(err) } }
Save the above code as gray_filter.go
and name it input.jpg## Place the # image in the same directory and run the following command:
is an image with a grayscale filter effect added.
package main import ( "image" "image/jpeg" "image/png" "log" "os" "github.com/anthonynsimon/bild/blur" ) func main() { // 打开图像文件 file, err := os.Open("input.jpg") if err != nil { log.Fatal(err) } defer file.Close() // 解码图像 img, err := jpeg.Decode(file) if err != nil { log.Fatal(err) } // 创建模糊图像 blurredImg := blur.Gaussian(img, 10.0) // 创建输出图像文件 outFile, err := os.Create("output_blur.jpg") if err != nil { log.Fatal(err) } defer outFile.Close() // 编码并保存图像文件 err = jpeg.Encode(outFile, blurredImg, &jpeg.Options{Quality: 100}) if err != nil { log.Fatal(err) } }
Save the above code as
blur_filter.go and name it input.jpg
Place the image in the same directory and run the following command: go run blur_filter.go
After successful operation, you will get an image named ## in the same directory The image of #output_blur.jpg
is the image with the blur filter effect added.Summary:
The above is the detailed content of Golang Image Processing: Learn How to Add Filter Effects. For more information, please follow other related articles on the PHP Chinese website!