Convert image to byte array in php

I have to send a picture to a webservice. The web service should receive the image as bytes [mayby bytearray] - not as a string... How do I convert the images to "byte" or bytearray?

I have tried this [without succes]:

$image1 = file_get_contents["LINK TO IMAGE"];
$image1BinaryData = "".base64_encode[$image1]."";

Any help will be appreciated...

asked May 21, 2012 at 14:33

2

Have you tried to directly read the image as binary data?


answered May 21, 2012 at 14:41

sucotronicsucotronic

1,4948 silver badges19 bronze badges

3

This is the actual byte array equivalent to what is generated in C# and Java.

$data = file_get_contents["test.jpg"];

$array = array[]; 
foreach[str_split[$data] as $char]{ 
    array_push[$array, ord[$char]]; 
}
var_dump[implode[' ', $array]];

answered Jul 12, 2012 at 12:07

Arvind BhardwajArvind Bhardwaj

5,1935 gold badges35 silver badges48 bronze badges

1

a php string is binary, so it's already in bytes.

get rid of base64_encode[] and use urlencode[] or rawurlencode[]

answered May 21, 2012 at 14:38

goatgoat

30.7k7 gold badges70 silver badges96 bronze badges

2

Recently I worked on integration between Drupal CMS with backend SOAP service and encountered a problem with saving image to the backend. The backend required image to be passed as byte array. Googling around I was suprised to find out answers like "I don't think PHP has such low level control..." or "change your backend service...". Eventually after not finding anything useful I decided to tackle the issue myself and soon I came up with a solution which is actually very easy.

So to convert image to byte array you will have to read the image using file_get_contents[] and then base encode it using base64_encode before sending it to backend SOAP service:

  1. This may not be the best place to ask, but nowhere else could I find an answer. Basically I want to pack image data into an array of bytes.

  2. Nevermind, I found it. Using the unpack[] function in PHP:

    $data file_get_contents["image.jpg"];
    $bytes unpack["C*"$data];
    //Blah......

  3. offtopic but is that to display map?

Share This Page

  • Forums
  • Members
  • Plugins
  • Get PocketMine-MP
  • Documentation
  • Issues
  • Discord
  • Jenkins
  • Donate
  • Menu

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Chủ Đề