用GO扫描图片像素,复制图片

关键是使用image、image/png、image/color包

 

// main.go
package main

import (
	"fmt"

	"bufio"
	"image"

	"image/png"

	"image/color"
	"io/ioutil"
	"log"
	"os"
)

var picWidth, picHeight int
var rgbaDataList [][]color.Color

func main() {
	readPncPic()
}

func readPncPic() {

	//读取本地文件
	f, err := os.Open("/Users/jiading/Documents/whiteblack.png")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	g, _, err := image.Decode(bufio.NewReader(f))
	if err != nil {
		log.Fatal(err)
		return
	}

	rect := g.Bounds()
	size := rect.Size()

	picWidth = size.X
	picHeight = size.Y

	fmt.Printf("图片宽度: %d __ 图片高度: %d\n", picWidth, picHeight)

	rgbaDataList = [][]color.Color{}

	for y := 0; y < picHeight; y++ {

		rgbaDataSingleList := []color.Color{}
		for x := 0; x < picWidth; x++ {
			pixelItem := g.At(x, y)
			r0, _, _, _ := pixelItem.RGBA()
			if r0 == 0x0000 {
				//white 0
			} else if r0 == 0xffff {

				//black 1
			}
			rgbaDataSingleList = append(rgbaDataSingleList, pixelItem)
		}
		rgbaDataList = append(rgbaDataList, rgbaDataSingleList)
	}

	//	writeLocalFile(pixelData, txtName)

	writePngFile()
}

func writePngFile() {

	//创建新图片
	f, err := os.Create("/Users/jiading/Documents/copypic.png")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	m := image.NewNRGBA(image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{picWidth, picHeight}})
	for y := 0; y < picHeight; y++ {
		list1 := rgbaDataList[y]

		for x := 0; x < picWidth; x++ {
			r0, g0, b0, a0 := list1[x].RGBA()
			m.SetNRGBA(x, y, color.NRGBA{uint8(r0), uint8(g0), uint8(b0), uint8(a0)})

		}
	}
	if err = png.Encode(f, m); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

}

func writeLocalFile(val string, filePath string) bool {

	var content = []byte(val)
	err := ioutil.WriteFile(filePath, content, 0644)
	if err != nil {
		fmt.Printf("%s\n", err)
		panic(err)
		return false
	}

	fmt.Println("==写文件成功: " + filePath + "==")
	return true

}

 

====================================================================================================================

2017_7_16,在win10上测试读取png图片信息时返回错误unkown format类似语句,是因为用到了image.Decode(),改成png.Decode()即可在win10上跑起来。

posted @ 2015-11-16 14:49  居家懒人  阅读(650)  评论(0编辑  收藏  举报