Current Location: Home> Latest Articles> How to Convert Images from Qiniu Cloud to Base64 and Save Locally with PHP

How to Convert Images from Qiniu Cloud to Base64 and Save Locally with PHP

M66 2025-06-19

How to Convert Images from Qiniu Cloud to Base64 and Save Locally with PHP

With the widespread use of cloud storage technologies, Qiniu Cloud has become one of the leading cloud storage platforms in China. It is widely used by developers in various applications. In some cases, you may need to convert image files from Qiniu Cloud to Base64 format and save them locally. This article will guide you through the process of doing this using PHP.

Steps to Follow

First, create a PHP file, such as convert_image.php. Next, you need to include the Qiniu Cloud SDK, which can be installed via Composer:

require_once 'vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;

Then, set up the Access Key and Secret Key for your Qiniu Cloud storage, along with the storage space name that you want to work with:

$accessKey = 'YOUR_ACCESS_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$bucket = 'YOUR_BUCKET_NAME';

Next, create an authorization object for the Qiniu Cloud storage:

$auth = new Auth($accessKey, $secretKey);

Now, retrieve the list of all files in your storage space:

$bucketManager = new BucketManager($auth);
$files = $bucketManager->listFiles($bucket);

Then, loop through the file list and convert each image file to Base64 format, saving it to a local folder:

if (!file_exists('images')) {
    mkdir('images');
}

foreach ($files['items'] as $file) {
    $key = $file['key'];
    $fileInfo = pathinfo($key);
    $extension = $fileInfo['extension'];

    // Check if the file is an image
    if (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
        $imageData = file_get_contents('http://' . $bucket . '.qiniudn.com/' . $key);
        $base64Image = base64_encode($imageData);
        file_put_contents("images/{$fileInfo['filename']}.txt", $base64Image);
    }
}

Code Explanation

In the code above, you need to replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your own Access Key and Secret Key obtained from Qiniu Cloud, and YOUR_BUCKET_NAME with the name of the storage space you're working with.

Additionally, the images directory is used to store the Base64-encoded images. If the directory doesn't exist, the code will automatically create it.

Conclusion

Through the steps outlined above, you can convert image files from Qiniu Cloud into Base64 format and save them locally. This is particularly useful in scenarios where you need to process images or store them in a database. We hope this tutorial helps you achieve your goal successfully.