我的第一个go程序

生成一张png图片

创建RGBA图像

background := image.NewRGBA(image.Rect(0,0,500,500))
go文档接口说明,image.Rect指定图像的左下角和右上角
func Rect(x0, y0, x1, y1 int) Rectangle
type Rectangle struct{
      Min,Max Point
}

image.NewRGBA生成一张图像,图像的结构为RGBA定义如下:

// RGBA is an in-memory image whose At method returns color.RGBA values.
type RGBA struct {
    // Pix holds the image's pixels, in R, G, B, A order. The pixel at
    // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*4].
    Pix []uint8
    // Stride is the Pix stride (in bytes) between vertically adjacent pixels.
    Stride int
    // Rect is the image's bounds.
    Rect Rectangle
}

func NewRGBA(r Rectangle) *RGBA {
    w, h := r.Dx(), r.Dy()
    buf := make([]uint8, 4*w*h)
    return &RGBA{buf, 4 * w, r}
}

以上,我成功地在内存中创建了一张图像,但这张图像不是png格式,也没有写进硬盘。

创建文件

outFile,err := os.Create("p1.png")
接口说明:
// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
    return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

关闭文件

defer是go的语言特性,在离开作用域时会执行defer声明的语句

defer outFile.Close()

写文件

将数据直接写进硬盘的开销较大,通常情况下是先写内存缓存,在适当时候再写进硬盘。
bufio包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象。

接口说明:
buff := bufio.NewWriter(outFile)
func NewWriter(w io.Writer)) *Writer
// Writer implements buffering for an io.Writer object.
// If an error occurs writing to a Writer, no more data will be
// accepted and all subsequent writes, and Flush, will return the error.
// After all data has been written, the client should call the
// Flush method to guarantee all data has been forwarded to
// the underlying io.Writer.
type Writer struct {
    err error
    buf []byte
    n   int
    wr  io.Writer
}

将RGBA格式转换为PNG格式

png.Encode(buff,background)

将文件刷到硬盘png.Encode(buff,background)

buff.Flush()

至此完成了一个简单的程序

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • GO简介 Go 语言教程 Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。Go是从2007年...
    C_GO流媒体后台开发阅读 394评论 0赞 0
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,849评论 1赞 32
  • 转载自VR设计云课堂[https://www.jianshu.com/u/c7ffdc4b379e]Unity S...
    水月凡阅读 1,236评论 0赞 0
  • 今天读完《图说区块链》就跟它的介绍一样,这是一本普及类书籍,和《精通比特币》相比要浅显很多,最后一部分介绍了比特币...
    李双男阅读 784评论 0赞 1
  • 归途(1) 顷昭 9月30号下...
    皈辰阅读 293评论 0赞 1

友情链接更多精彩内容