In this thread, @David Carlisle tells us how to use luatex to read some of the properties of a png image. Alas, the image library seems to fail regarding the colorspace
property. Always reports nil
.
If I could read two bytes from the file (at known locations), and have those bytes assigned to a LaTeX variable as plain text 00 through FF, then I know what to do from there.
I've looked at this thread, which seems related, but it does not provide what I need.
So, here is my general question: How would Lua code do this:
1) Open an arbitrary binary file (partially). Although I have PNG in mind, I assume that any file type could be used. The method must be cross-platform.
2) Select only the bytes from offset P to offset Q, where P and Q are provided as variables, via a LaTeX macro. Might be as much as a couple of hundred bytes, but probably much less.
3) Express the bytes as a plain text string, using codes 0 through F. So, if asked for ten bytes, the string might look something like A9003405BC
without space or return.
4) Assign the string to a LaTeX macro, for subsequent processing via ordinary LaTeX.
Why I want to know: In my LuaLaTeX application, the use of images is limited. I understand the image specs, but (not being a programmer) am baffled by such things as the LuaTeX manual.
Why anyone else should care: Seems to me that the power of Lua is under-used in LuaLaTeX, probably because most users are doing a one-time project, and don't want to learn another programming language. My request is for something that is modular, and has general applicability.
Note that a solution to 1-4 also can be used when the desired information is not at a specific byte offset, as long as it is somewhere near the start of the file. Then, the plain text string can be parsed for values, using ordinary LaTeX methods.
EDIT: Looking at David's answer, below, I have some questions:
The desired code is something like this (PSEUDOCODE, THIS DOES NOT WORK):
\newcommand\getsomebytes[3]{ % filename, start, end
\directlua{
local inp = assert(io.open("#1", "rb"))
local data = inp:read("*all")
\gdef\heretheyare{string.byte(data,#2,#3)}
}
}
Then, in the document body, I would use:
\getsomebytes{filename.png}{4}{56} % bytes from 4 to 56 here
That would not print anything, but it would store the result in macro \heretheyare
as plain text (numbers instead of letters OK, as long as the string can be parsed by LaTeX string methods, such as from package xstring
). After processing, I would re-use the commands, for another file.
I wonder if it is necessary to open "all" of the file, since in some cases the file might be very large (20Mb or more) and I only need to inspect a part of it.