package main

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

func main() {
	// 创建一个新的图片对象
	img := image.NewRGBA(image.Rect(0, 0, 100, 100))

	// 填充图片为蓝色
	for x := 0; x < 100; x++ {
		for y := 0; y < 100; y++ {
			img.Set(x, y, color.RGBA{0, 0, 255, 255})
		}
	}

	// 创建文件
	file, err := os.Create("image.jpg")
	if err != nil {
		// 处理错误
		panic(err)
	}
	defer file.Close()

	// 保存为JPEG格式
	if err := jpeg.Encode(file, img, nil); err != nil {
		// 处理错误
		panic(err)
	}
}

这段代码做了以下几件事:

  1. 导入必要的包。
  2. 创建一个新的图片对象,大小为100x100像素。
  3. 使用循环填充图片为蓝色。
  4. 创建一个新的文件,文件名为image.jpg
  5. 使用jpeg.Encode函数将图片编码为JPEG格式并写入文件。

请确保你的环境中安装了Go语言,并且有适当的权限来创建文件。

package main

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

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

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

	// 创建新的文件
	outputFile, err := os.Create("output.jpg")
	if err != nil {
		panic(err)
	}
	defer outputFile.Close()

	// 编码并保存图片
	if err := jpeg.Encode(outputFile, img, nil); err != nil {
		panic(err)
	}
}