List of Bytes to File Image

Hello everyone, I’m using: SWI-Prolog version 8.2.4 and I’m doing a code that reads the bytes of an image and then saves them into a list. The goal I’m trying to achieve is that given that list of bytes that contains the full information of the image I should be able to convert that information into an image again, but I’m getting an error.

What I’m getting is:
ERROR: No permission to write bytes to TEXT stream `(0x55d5e8125800)’
ERROR: In:
ERROR: [13] put_byte((0x55d5e8125800),66)
ERROR: [12] ‘__aux_maplist/2_put_byte+1’([66,77|…],(0x55d5e8125800)) at /home/fausto/Escritorio/Prolog/TT/version31.prolog:219
ERROR: [11] list_to_file([66,77|…],‘hola.bmp’) at /home/fausto/Escritorio/Prolog/TT/version31.prolog:221
ERROR: [10] ejemplo_prueba(‘grises.bmp’,_24506) at /home/fausto/Escritorio/Prolog/TT/version31.prolog:215
ERROR: [9]

My code looks like this:

% your code here

% principal/2(+File,-List). This predicate receives on the first parameter the name of the file and returns a % list with all the bytes of information of that file 

ejemplo_prueba(Archivo,Image) :-
	principal(Archivo,Lista),
	list_to_file(Lista,'hola.bmp'),
	file_to_image('hola.bmp',Image).

list_to_file(Bytes, FilePath) :-
    open(FilePath, write, Stream),
    maplist(put_byte(Stream), Bytes),
    close(Stream).

file_to_image(FilePath, Image) :-
    open(FilePath, read, Stream),
    read_stream_to_codes(Stream, Codes),
    close(Stream),
    phrase(image(Image), Codes).

image(Image) -->
    sequence(Image).

sequence([]) --> [].
sequence([Byte | Bytes]) -->
    [Byte],
    sequence(Bytes).

Try:

open(FilePath, write, Stream, [type(binary)])

Also try the type(binary) option for the input stream.
Codes are not necessarily the same as bytes; if you read a file that’s in UTF8, for example, you’ll get the Unicode codes.

1 Like