Question

How to convert base 64 image format to image file and save image in local file directory in magento 2

  public function setProfileImage($customerId, $base64)
        {
             if ($customerId) {
                     //code for convert base64 to image file and save file directory
                  } 

        }

Thanks in advance !!

Was it helpful?

Solution

public function setProfileImage($customerId, $base64, $name)
    {
        if ($customerId) {

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
            $mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
            $media = $mediaPath . 'customer/profile_image/';

            $data = $base64;
            list($type, $data) = explode(';', $data);
            list(, $data)      = explode(',', $data);
            $data = base64_decode($data);
            if (file_put_contents($media . $name . uniqid() . '.png', $data)) {
                return 'success';
            } else {
                return 'failed';
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top