-1

How can I write this array with unsigned bytes (0-255) to a binary file?

The array look like this:

note that I did not add any index because PHP automatically add the value to the next available index in the array variable when you use []. So the first my_PNG[]=137; is the same as my_PNG[0]=137;. Next time [] is used the next index 1 is returned and so on and so forth

my_PNG = array();
my_PNG[]=137;
my_PNG[]=80;
my_PNG[]=78;
my_PNG[]=71;
my_PNG[]=13;
my_PNG[]=10;
my_PNG[]=26;
my_PNG[]=10;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=13;
my_PNG[]=73;
my_PNG[]=72;
my_PNG[]=68;
my_PNG[]=82;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=1;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=1;
my_PNG[]=8;
my_PNG[]=6;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=31;
my_PNG[]=21;
my_PNG[]=196;
my_PNG[]=137;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=13;
my_PNG[]=73;
my_PNG[]=68;
my_PNG[]=65;
my_PNG[]=84;
my_PNG[]=120;
my_PNG[]=156;
my_PNG[]=99;
my_PNG[]=96;
my_PNG[]=96;
my_PNG[]=96;
my_PNG[]=248;
my_PNG[]=15;
my_PNG[]=0;
my_PNG[]=1;
my_PNG[]=4;
my_PNG[]=1;
my_PNG[]=0;
my_PNG[]=95;
my_PNG[]=229;
my_PNG[]=195;
my_PNG[]=75;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=0;
my_PNG[]=73;
my_PNG[]=69;
my_PNG[]=78;
my_PNG[]=68;
my_PNG[]=174;
my_PNG[]=66;
my_PNG[]=96;
my_PNG[]=130;

This is each byte in a PNG file with just one black pixel in it. I want to write or somehow save this array to a file so it can be used as an PNG image on the server.

I have tested:

file_put_contents('img.png', pack("C*",$my_PNG));

But it only save one byte to the file. I also tested a bunch of other things for the past 2 days now. So I finally wanted to get some help.

7
  • 1
    That's not an array. Commented May 17, 2017 at 19:59
  • You are expected to try to write the code yourself. After doing more research if you have a problem post what you've tried with a clear explanation of what isn't working and provide a Minimal, Complete, and Verifiable example. Read How to Ask a good question. Be sure to take the tour and read this. Commented May 17, 2017 at 20:00
  • do you really need that many lines? Commented May 17, 2017 at 21:31
  • @KenWhite added my_PNG = array(); to show it's an array. Commented May 18, 2017 at 4:49
  • @PedroLobito 1 black pixel 1x1 Commented May 18, 2017 at 4:50

1 Answer 1

3

Assuming that the input array is a byte array you just need to use write it out as binary.

file_put_contents($filename, pack("C*", ...$my_PNG));
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! Thank you. I should have checked that I needed to use ... to pack an array :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.