Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

How to convert JSON Byte Array back to binary image?

by vsawant (Initiate)
on Jan 28, 2011 at 11:24 UTC ( #884785=perlquestion: print w/replies, xml ) Need Help??
vsawant has asked for the wisdom of the Perl Monks concerning the following question:


I have a CGI script which accepts parameters in JSON format.

The .Net client is POSTing the binary image (one of the paramter) file converted into JSON Byte Array. The byte array after decoding using JSON::XS looks something like this:

$data = [120, 64, 232, ...];

I think I have to use pack/unpack but not sure how to use it to get the entire byte array converted back into the binary image file. Any help appreciated.


Replies are listed 'Best First'.
Re: How to convert JSON Byte Array back to binary image?
by chrestomanci (Priest) on Jan 28, 2011 at 11:32 UTC

    You would want pack to turn numbers into binary data. There is an old but extremely good node on this site that explains how to use pack.

    Having said that you will probably find that you need to do more to turn the raw numbers from the JSON Byte Array back into an image than just pack them. For example what format is the image? Are you being sent the bytes for an image in a known file format such a PNG or JPEG, or are you getting pixel values? How do you know what size the image is, and what format?

    If the JSON data you are receving is the byte values for a file, then you may get away with something simple like:

    $imgData = pack( "b", @byte_array); open my $outfile, '>', $fileName or die "Error writing $fileName $!"; binmode $outfile; print $outfile $imgData; close $outfile;

    (In this example the b pack format string means a list of bytes.)

    If the JSON data you are receving is pixel values, then I would forget about using pack, and instead use the pixel data to directly create the image file. You could either use GD, and just set each pixel individualy from the data you have, and then save the image in your prefered file format, or you could generate an image file in Netpbm format which stores the pixel values as plain text in file. If necessary you can then convert that file to a more optimised format with an external libary.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://884785]
Approved by moritz
[Lotus1]: damn, I just opened the attacment on a phishing simulation email in the $work email
[Lotus1]: now I'll be sent to re-education camp or something
[stevieb]: relocate Lotus1 to the brig, straight away!

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2017-05-24 13:38 GMT
Find Nodes?
    Voting Booth?