Search code examples
phplaravelimagefile-uploadbase64

Laravel image got corrupted while decoding from base64 and storing to local storage


$imgData = base64_decode($validatedData['img']);
$uniqueFilename = hash('sha256', time() . $imgData) . '.jpg';
Storage::disk('public')->put('products/' . $uniqueFilename, $imgData);

I have used this code to store an image in local storage. The file is successfully stored, but when I try to open it, it appears to be corrupted. I have tried various solutions but to no avail. Can someone please guide me on how to fix this issue?


Solution

  • You can try this code to decode any base64 file like image, pdf, mp3, etc. without knowing and having actual file details inside base64 encoded string.

    $encodedString = explode(',', $base64String, 2);
    $decodedImage = str_replace(' ', '+', $encodedString[1]);
    
    $decodedImage = base64_decode($decodedImage);
    $mime_type = finfo_buffer(finfo_open(), $decodedImage, FILEINFO_MIME_TYPE);
    $extension = $this->mime2ext($mime_type);
    
    $imageName = Str::random().'.'.$extension;
    Storage::disk('upload')->put($imageName, $decodedImage);
    return $imageName;
    
    

    add below function to the same class or use trait for identifying file format, you can also add more mime types to this array if you are dealing with any other file formats as well.

    
    public function mime2ext($mime)
    {
        $all_mimes = '{
        "png":["image\/png","image\/x-png"],
        "bmp":["image\/bmp","image\/x-bmp","image\/x-bitmap","image\/x-xbitmap","image\/x-win-bitmap","image\/x-windows-bmp","image\/ms-bmp","image\/x-ms-bmp","application\/bmp","application\/x-bmp","application\/x-win-bitmap"],
        "gif":["image\/gif"],
        "jpeg":["image\/jpeg","image\/pjpeg", "image\/x-citrix-jpeg"]
        }';
    
        $all_mimes = json_decode($all_mimes,true);
        foreach ($all_mimes as $key => $value) {
            if(array_search($mime,$value) !== false) return $key;
        }
        return false;
    }