我通过向该示波器发送查询来读取 .gif 格式的打印屏幕图像。返回的数据是二进制 block 形式。我通过套接字连接并使用 tcl 与此范围进行通信。我可以很好地读取数据,但是当我尝试将数据写入本地文件时,它似乎无法正确写入,因为创建的文件中没有信息。目标:将此数据保存或写入本地文件,以便以后访问。
这是尝试在 TCL 中执行该任务的代码段。
#reading .gif data(binary block form) and writing it to a local file
fconfigure $channelid -encoding binary -translation binary ; #converts the stdin to binary data input
fconfigure $fileId -encoding binary -translation binary ; #converts the stdout to binary data output
set image [getdata $channelid "some query?"] ;# getdata proc reads the query returned data
puts stderr $image ;#to verify what data I am reading
set filename "C:/test.gif"
set fileId [open $filename "w"]
puts -nonewline $fileId $image
close $fileId
任何想法或帮助将不胜感激。谢谢。
最佳答案
GIF 数据本质上是二进制的;当写出来时,您需要将其写为二进制,否则 Tcl 将对其应用一些转换(例如,编码转换),这些转换对于文本数据是正确的,但对于二进制数据是错误的。最简单的方法是使用 wb
模式而不是 w
打开(如果您使用的 Tcl 版本支持该模式)——它是在 8.5 中引入的有点像 C stdio - 但在打开之后和写入任何数据之前使用 fconfigure $fileId -translation binary
。
请注意,Tcl总是立即对呈现的事物进行操作;在打开 channel 之前您无法对其进行fconfigure
。我猜你的第二个 fconfigure
确实太早了几行。将代码转换为过程,这样它就不会处理全局变量,这可能是个好主意;这可以帮助您更轻松地检测操作排序的各种问题:
proc copy_data {source_channel query_string target_file} {
# -translation binary implies -encoding binary (and a few other things too)
fconfigure $source_channel -translation binary
set image [getdata $source_channel $query_string]
set fileId [open $target_file "wb"]
puts -nonewline $fileId $image
close $fileId
}
# Invoke to do the operation from your example
copy_data $channelid "some query?" "C:/test.gif"
关于tcl - 将 .gif 数据从示波器读取到 tcl 并写入本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12755691/