Does anyone know of a library that will handle bytea encodings from postgres? The bytea field that I need to access contains a jpg file. I want to retrieve it from the database and write it out for an image display program. bytea: Bytea octets are also escaped in the output. In general, each "non-printable" octet is converted into its equivalent three-digit octal value and preceded by one backslash. Most "printable" octets are represented by their standard representation in the client character set. The octet with decimal value 92 (backslash) has a special alternative output representation. Details are in Table 8-8<http://www.postgresql.org/docs/7.4/interactive/datatype-binary.html#DATATYPE-BINARY-RESESC>. *Table 8-8. bytea Output Escaped Octets* Decimal Octet ValueDescriptionEscaped Output Representation ExampleOutput Result92backslash\\SELECT '\\134'::bytea;\\ 0 to 31 and 127 to 255 "non-printable" octets\*xxx* (octal value) SELECT '\\001'::bytea;\00132 to 126"printable" octetsclient character set representation SELECT '\\176'::bytea;~ Depending on the front end to PostgreSQL you use, you may have additional work to do in terms of escaping and unescaping bytea strings. For example, you may also have to escape line feeds and carriage returns if your interface automatically translates these. So, here is part of the file from the database: \377\330\377\340\000\020JFIF\000\001\001\000\000\001\000\001\000\000\377\333\000C\000\012\007\007\010\007\006\012\010\010\010\013\012\012\013\016\030\020\016\015\015\016\035\025\026\021\030#\037%$"\037"!&+7/&)4)!"0A149;>>>%.DIC<H7=>;\377 I may have to write a converter myself but I don't like re-inventing the wheel if I don't need to do so. Any pointers would be greatly appreciated. Bryan Green
2008/1/20 Bryan Green <dbryan.green@gmail.com>:
Does anyone know of a library that will handle bytea encodings from postgres? The bytea field that I need to access contains a jpg file. I want to retrieve it from the database and write it out for an image display program.
I'd love to see Don give the correct ByteString solution, but here's a slow version I knocked up (probably buggy): import qualified Data.ByteString as B import Data.ByteString.Internal (c2w) import Data.Maybe (catMaybes) import Data.List (mapAccumL) byteaDecode :: B.ByteString -> B.ByteString byteaDecode = B.pack . catMaybes . snd . mapAccumL f initState . B.unpack where initState = (0, 0) f (0, _) 92 = ((1, 0), Nothing) f (0, _) x = ((0, 0), Just x) f (1, _) 92 = ((0, 0), Just 92) f (3, n) x = ((0, 0), Just (n * 8 + (x - 48))) f (c, n) x = ((c + 1, n * 8 + (x - 48)), Nothing) AGL -- Adam Langley agl@imperialviolet.org http://www.imperialviolet.org 650-283-9641
participants (2)
-
Adam Langley -
Bryan Green