Skip to content Skip to sidebar Skip to footer

Is File_get_contents In Php The Same As Todataurl In Javascript?

I want to use an API to compress images. It says the input can as well be a buffer (string with binary), for example: $sourceData = file_get_contents('unoptimized.jpg'); $resultDat

Solution 1:

file_get_contents returns the content of a file as string, and that string exactly represents the content of the file.

.toDataURL() gives you a data url. The data:image/png;base64, part tells that the following data represents a png and that the data is base64 encoded.

To get the same data representation as you get with file_get_content you would need to decode the iVBORw0KGgoAAAANSUh...

So yes, both give you the content of a file, but they don't do that in the same way.

To toBlob on the other hand will return a Buffer containing the data in the same representation as file_get_contents would do.

Solution 2:

Assuming you have a PNG file named input.png, the following two pieces of code produce the same result:

  1. Read the image data from the PNG file:

    $sourceData = file_get_contents('input.png');
    
  2. Read the image data from a data: URL generated from the PNG file:

    // Generate the 'data:' URL
    $url = 'data:image/png;base64,'.base64_encode(file_get_contents('input.png'));
    
    // Read the image data from the 'data:' URL
    $sourceData = file_get_contents($url);
    

The second piece of code works only if fopen wrappers are enabled on the server where the file_get_contents() is executed.

It doesn't make much sense to use the second fragment of code in a single script (because it does a redundant encoding and decoding) but it makes a lot of sense if the encoding and restoring (decoding) happen in different scripts.

They can be part of the same application (the script that encodes the data stores it in the database, the other script loads from the database, restores the image data and uses it) or the decoding could happen in a remote application that sends the data URL over the Internet to be decoded and used by a different application.

Post a Comment for "Is File_get_contents In Php The Same As Todataurl In Javascript?"