PHP / Codeigniter - How to convert image to byte array?

Asked

Viewed 773 times

0

I want to record here my solution to this problem.

$data = file_get_contents("/ImagePath/Image.jpg");

$array = array(); 

foreach(str_split($data) as $char){ 
   array_push($array, ord($char)); 
}
  • Translate Please!

  • Welcome, is this the answer or the question? I recommend you visit the tour, because we are not a forum but a Q&A: http://answall.com/tour

  • I am voting to close this question as out of scope because it is not a question, but rather an answer.

2 answers

2

Tried to read image straight as binary data?

<?php
$filename = "image.png";
$file = fopen($filename, "rb");
$contents = fread($file, filesize($filename));
fclose($file);
?>

If sending via form, convert $contents for Base64 using base64_encode($contents).

1

The answer from @Felipedouradinho was nice. But, if you want to create an array of bytes, you would have to do so.

    $filename = "image.png";

    $file = fopen($filename, "rb");

    $tamanho_do_buffer = 4096;

    $array = array();

    while (! feof($file)) {

        $array[] = fread($file, $tamanho_do_buffer);
    }

    fclose($file);

Use file_get_contents in this case is not recommended. The file_get_contents returns all the contents of the file. Already the fopen combined with the fread sets a specific buffer face size that will be opened from the file, thus avoiding an overload in memory (depending, your script may generate an error if memory usage reaches the limit set in PHP)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.