79125894

Date: 2024-10-25 13:30:28
Score: 0.5
Natty:
Report link

I'm working with a Laravel application that uses an HTML editor where users can upload images. These images are embedded as Base64 strings in the HTML content. I want to convert these Base64 image tags to image paths stored on the server (specifically using Amazon S3). Below is a custom code snippet I implemented to achieve this.

preg_match_all('/<img[^>]+src="data:image\/[^;]+;base64,[^"]+"[^>]*>/i', $data['html'], $matches);

foreach ($matches[0] as $imgTag) {
    preg_match('/src="(data:image\/[^;]+;base64,[^"]+)"/', $imgTag, $srcMatch);

    if (isset($srcMatch[1])) {
        // Use a different variable name to avoid overwriting $data
        list(, $base64Data) = explode(',', $srcMatch[1]);
        $imageData = base64_decode($base64Data);

        // Create a temporary file to store the image
        $tempFilePath = tempnam(sys_get_temp_dir(), 'upload') . '.jpg';
        file_put_contents($tempFilePath, $imageData);

        // Upload the image to S3 or local
        $filePath = $this->uploadOne(new UploadedFile($tempFilePath, 'image.jpg'), 'images', null, 's3'); // Specify your S3 disk
        
        // Get the URL of the uploaded image
        $s3Url = Storage::disk('s3')->url($filePath);
        
        // Replace the Base64 src with the S3 URL in the HTML
        $data['html'] = str_replace($srcMatch[0], 'src="' . $s3Url . '"', $data['html']);
        
        // Delete the temporary file
        unlink($tempFilePath);
    }
}
Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Umair Khan