當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Encode用法及代碼示例

GO語言"image/png"包中"Encode"函數的用法及代碼示例。

用法:

func Encode(w io.Writer, m image.Image) error

Encode 以 PNG 格式將圖像 m 寫入 w。任何圖像都可以被編碼,但不是 image.NRGBA 的圖像可能會被有損編碼。

例子:

package main

import (
	"image"
	"image/color"
	"image/png"
	"log"
	"os"
)

func main() {
	const width, height = 256, 256

	// Create a colored image of the given width and height.
	img := image.NewNRGBA(image.Rect(0, 0, width, height))

	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			img.Set(x, y, color.NRGBA{
				R: uint8((x + y) & 255),
				G: uint8((x + y) << 1 & 255),
				B: uint8((x + y) << 2 & 255),
				A: 255,
			})
		}
	}

	f, err := os.Create("image.png")
	if err != nil {
		log.Fatal(err)
	}

	if err := png.Encode(f, img); err != nil {
		f.Close()
		log.Fatal(err)
	}

	if err := f.Close(); err != nil {
		log.Fatal(err)
	}
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Encode。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。