Code
Code

Reputation: 6251

Get Exif image orientation from Base-64 encoded image too slow

I'm using this code to get the Exif orientation of a JPEG image from its base64 encoded data.

$exif = exif_read_data('data://image/jpeg;base64,' . $base64EncodedImageData);
$orientation = $exif['Orientation'];

However this code is slow especially when dealing with HD images. Is there any way to get the orientation faster?


It seems to be much faster when passing a actual file path instead of the base-64 encoded string, but the image is not on the disk and the base-64 encoded string is all I have.

Upvotes: 1

Views: 3135

Answers (1)

mister martin
mister martin

Reputation: 6252

The fact you're loading in the entire blob is why it is taking so long, so you really just need to load in the part of the image that contains the exif data.

When you give exif_read_data a file path instead of a blob, it only reads the necessary information by default. If that is simply not an option, then you may need an ugly workaround / hack.

For example, you could specify a hard-coded value:

$image = base64_encode(file_get_contents('test.jpg'));
echo strlen($image) . '<br />'; // 81684
// only read the first 30000 characters
$exif = exif_read_data('data://image/jpeg;base64,' . substr($image, 0, 30000));
echo '<pre>';
var_dump($exif);
echo '</pre>';

Or you could increment it dynamically until the appropriate size is found:

$image = base64_encode(file_get_contents('test.jpg'));
$read = '8192';
// this will produce errors, so i am suppressing them
while (!$exif = @exif_read_data('data://image/jpeg;base64,' . substr($image, 0, $read))) {
    $read += $read;
}
echo '<pre>';
var_dump($exif);
echo '</pre>';

There may be a better solution but I don't know what it is. Hope that helps.

Upvotes: 2

Related Questions