您的当前位置:首页正文

golang 水平翻转图片生成该图片的镜像文件

2024-11-30 来源:个人技术集锦
package main

import (
	"image"
	"image/jpeg"
	"log"
	"os"
)

// 水平翻转生成镜像图片
func main() {
	// Open the input image file
	log.SetFlags(log.Llongfile)
	inFile, err := os.Open("input.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer inFile.Close()

	// Decode the image
	src, err := jpeg.Decode(inFile)
	if err != nil {
		log.Fatal(err)
	}

	// Create a new image with the same dimensions as the input image
	dst := image.NewRGBA(src.Bounds())

	// Iterate over the pixels in the input image
	for x := src.Bounds().Min.X; x < src.Bounds().Max.X; x++ {
		for y := src.Bounds().Min.Y; y < src.Bounds().Max.Y; y++ {
			// Flip the pixel horizontally by setting the pixel in the output image
			// to the pixel in the input image with the x-coordinate flipped
			color := src.At(x, y)
			dst.Set(src.Bounds().Max.X-x-1, y, color)
		}
	}

	// Create a new output file
	outFile, err := os.Create("output.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer outFile.Close()

	// Encode the output image as a PNG and write it to the output file
	err = jpeg.Encode(outFile, dst, &jpeg.Options{Quality: 100})
	if err != nil {
		log.Fatal(err)
	}
}
显示全文