Чтобы преобразовать строку в кодировке Base64 в изображение в PHP, вы можете использовать несколько методов. Я предоставлю вам три различных подхода вместе с примерами кода:
Метод 1: использование функций base64_decode()и file_put_contents()
<?php
$base64_string = 'data:image/png;base64,iVBORw0KG...'; // Replace with your base64 string
// Remove the data:image/png;base64 part
$image_parts = explode(";base64,", $base64_string);
$base64_image = $image_parts[1];
// Decode base64 image and save to a file
$file_path = '/path/to/save/image.png'; // Replace with your desired file path
file_put_contents($file_path, base64_decode($base64_image));
// Output success message or perform further operations
echo "Image successfully saved!";
?>
Метод 2. Использование библиотеки GD
<?php
$base64_string = 'data:image/png;base64,iVBORw0KG...'; // Replace with your base64 string
// Remove the data:image/png;base64 part
$image_parts = explode(";base64,", $base64_string);
$base64_image = $image_parts[1];
// Create image from base64 string
$image = imagecreatefromstring(base64_decode($base64_image));
// Save image to a file
$file_path = '/path/to/save/image.png'; // Replace with your desired file path
imagepng($image, $file_path);
// Free up memory
imagedestroy($image);
// Output success message or perform further operations
echo "Image successfully saved!";
?>
Метод 3. Использование библиотеки изображений вмешательства (требуется установка)
<?php
// Install Intervention Image library using composer: composer require intervention/image
require 'vendor/autoload.php';
use Intervention\Image\ImageManager;
$base64_string = 'data:image/png;base64,iVBORw0KG...'; // Replace with your base64 string
// Remove the data:image/png;base64 part
$image_parts = explode(";base64,", $base64_string);
$base64_image = $image_parts[1];
// Create Intervention Image Manager instance
$imageManager = new ImageManager();
// Create image from base64 string
$image = $imageManager->make(base64_decode($base64_image));
// Save image to a file
$file_path = '/path/to/save/image.png'; // Replace with your desired file path
$image->save($file_path);
// Output success message or perform further operations
echo "Image successfully saved!";
?>