尝试创建一个.pgm文件,但最终得到了一个二进制文件。

huangapple go评论74阅读模式
英文:

Go - trying to create a .pgm file but end up with a binary file

问题

我正在阅读一个pgm文件,以便对其应用一些滤镜,并将结果重写到一个新的pgm文件中。然而,我总是得到一个二进制文件(vim不显示数值,而是显示^G ^0 ^K等字符,file命令告诉我这是一个数据文件,imagemagick无法打开该文件)。

我写入文件的代码如下:

fd,err := os.Create(filename)
wr := bufio.NewWriter(fd)
//img是一个[][]int类型的变量,保存要写入的数值
str := "P2\n" + filename + "\n" + string(len(img[0])) + ...
if _,err := wr.WriteString(outStr); err != nil {..}

然后在一个循环中,我遍历img数组执行类似的操作。

我在这里漏掉了什么?

英文:

I'm reading a pgm-file in order to apply some filter to it and rewrite the result to a new pgm-file. However, I always end up with a binary file (vim doesn't show the values but stuff like ^G ^0 ^K etc, the file-command tells me it's a data file and imagemagick can't open the file)

The code where I write to the file looks like this:

fd,err := os.Create(filename)
wr := bufio.NewWriter(fd)
//img is of type [][]int and holds the values to be written
str := "P2\n" + filename + "\n" + string(len(img[0])) + ...
if _,err := wr.WriteString(outStr); err != nil {..}

and then some more of that in a loop where I go through the img array.

What am I missing here?

答案1

得分: 4

string(len(img[0]))在这里并不是你想要的操作。你需要使用strconv.Itoa

string(len(img[0]))会创建一个只包含Unicode码点为len(img[0])的字符的单个字符字符串(参见规范中的转换部分)。

英文:

string(len(img[0])) doesn't do what you're trying to do here. You need strconv.Itoa

string(len(img[0])) is creating a single character string containing whichever character is the Unicode code point for len(img[0]) (see the spec section on conversions)

huangapple
  • 本文由 发表于 2013年8月17日 02:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/18279902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定