登录
首页 >  Golang >  Go问答

控制台输出流和媒体文件流之间的差异

来源:stackoverflow

时间:2024-02-01 22:58:26 447浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《控制台输出流和媒体文件流之间的差异》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我在尝试在 Go 中渲染 GIF 时遇到问题。使用某种方法时,输出的 GIF 文件无法打开,但使用另一种方法则可以正常打开。我在 Go 中找到了 Rendering .gif,但它没有解决我的具体问题。

这是有问题的代码:

package main

import (
    "bufio"
    "fmt"
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
    "time"
)

var palette = []color.Color{color.White, color.Black}

const (
    whiteIndex = 0
    blackIndex = 1
)

func main() {
    w := bufio.NewWriter(os.Stdout)
    lissajous(w)
}

func lissajous(out io.Writer) {
    const (
        cycles  = 5
        res     = 0.001
        size    = 100
        nframes = 64
        delay   = 8
    )
    rand.Seed(time.Now().UTC().UnixNano())

    freq := rand.Float64() * 3.0
    anim := gif.GIF{LoopCount: nframes}
    phase := 0.0

    for i := 0; i < nframes; i++ {
        rect := image.Rect(0, 0, 2 * size+1, 2 * size + 1)
        img := image.NewPaletted(rect, palette)

        for t := 0.0; t < cycles * 2 * math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t * freq + phase)
            img.SetColorIndex(size + int(x * size + 0.5), size + int(y * size + 0.5), blackIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    err := gif.EncodeAll(out, &anim)
    if err != nil {
        return
    } else {
        fmt.Println(err)
    }
}

以下是命令:

go build main.go
main > out.gif

然后,out.gif 无法打开。不过,这个方法效果很好:

func main() {
    fileName := "out.gif"
    f, err3 := os.Create(fileName)
    if err3 != nil {
        fmt.Println("create file fail")
    }
    w := bufio.NewWriter(f) 
    lissajous(w)
    w.Flush()
    f.Close()

}

我很困惑为什么第一种方法无法创建功能性 GIF 文件,而第二种方法却可以。这与 Go 处理文件写入或缓冲的方式有关吗?


正确答案


根据@CeriseLimón 注释

func main() {
    w := bufio.NewWriter(os.Stdout)
    lissajous(w)
    w.Flush()
}

解释最后一个问题

今天关于《控制台输出流和媒体文件流之间的差异》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>