I’m using Intervention Image in a Laravel project and I’m trying to create an image from a base64 encoded string.
Here is the code of the Service:
<?php
namespace App\Services;
use DB;
use Image;
class Compressor
{
public function compress()
{
$files = DB::table('app_payment_reports')
->where(function ($query) {
$query->where('voucher_file_type', '=', 'image/jpeg')
->orWhere('voucher_file_type', '=', 'image/png');
})
->whereNull('new_voucher_file_size')
->get();
foreach ($files as $file) {
$imageData = $file->voucher_file_base64;
$image = Image::make($file->voucher_file_base64);
$originalSize = strlen($file->voucher_file_base64);
$compressedImage = $image->encode('jpg', 75);
$newSize = strlen($compressedImage);
DB::table('app_payment_reports')
->where('id', $file->id)
->update([
'new_voucher_file_size' => $newSize,
'voucher_file_base64' => $newBase64
]);
}
}
public function getTotalImages()
{ return DB::table('app_payment_reports')
->where(function ($query) {
$query->where('voucher_file_type', '=', 'image/jpeg')
->orWhere('voucher_file_type', '=', 'image/png');
})
->whereNull('new_voucher_file_size')
->count();
}
}
However, when I run this code, I get the following error:
Intervention\Image\Exception\NotReadableException
Image source not readable
at vendor/intervention/image/src/Intervention/Image/AbstractDecoder.php:351
347▕ case $this->isBase64():
348▕ return $this->initFromBinary(base64_decode($this->data));
349▕
350▕ default:
➜ 351▕ throw new NotReadableException("Image source not readable");
352▕ }
353▕ }
354▕
355▕ /**
+3 vendor frames
4 app/Services/Compressor.php:25
Illuminate\Support\Facades\Facade::__callStatic()
5 app/Console/Commands/TestCommand.php:23
App\Services\Compressor::compress()
According to the Intervention Image documentation, it should be possible to use base64 encoded image data with the make method. However, it doesn’t seem to be working in my case.
Here’s an example of how the data is stored in the voucher_file_base64 column:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAE2qADAAQAAAABAAAEmQAAAAD...
Does anyone know what could be causing this issue and how to fix it?