调整base64图像的大小

Luk*_*sen 13 php base64 resize image node.js

我有多个图像 - 保存为Base64字符串,现在我想调整这些图像的大小以获得它们的缩略图...

最好的是使用Javascript(Node-Server)调整它们的大小,但也可以使用php调整它们的大小.

提前致谢

Che*_*ana 14

我同意Jon Hanna的方法:解析 Base64code然后在Resample之前将其加载到GD Image.然而,要把它作为数据取回它并不像我那么容易.在GAE中的php中,它需要通过在php.ini文件中设置来启用输出缓冲output_buffering = "On".

在这里,我详细解释了这个步骤.

本文档作为使用Base64code的解析创建图像资源的参考:http://php.net/manual/en/function.imagecreatefromstring.php

// Create image resource from Base64code
$data64 = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
        . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
        . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
        . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$image = imagecreatefromstring(base64_decode($data64));
Run Code Online (Sandbox Code Playgroud)

这是一个可以直接放到Resample函数的图像资源:http: //php.net/manual/en/function.imagecopyresampled.php

// Resample
$image_p = imagecreatetruecolor($new_w, $new_h);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_w, $new_h, $org_w, $org_h);
Run Code Online (Sandbox Code Playgroud)

结果也是图像资源.要将其作为数据,我们需要缓冲.
了解 如何从图像资源创建base64encoded字符串

// Buffering
ob_start();
imagepng($image_p);
$data = ob_get_contents();
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)

使用下面的doc我在我的项目中将GCS存储桶设置为网站,以便我可以直接存储和显示它:https: //cloud.google.com/storage/docs/website-configuration#tips

//Store & Display
$context = stream_context_create([
   'gs' =>[
        'acl'=> 'public-read', 
        'Content-Type' => 'image/jpeg', 
        'enable_cache' => true, 
        'enable_optimistic_cache' => true,
        'read_cache_expiry_seconds' => 300,
    ]
]);
file_put_contents("gs://mybucket/resample/image.jpeg", $data, false, $context); 
header("Location: http://mybucket/resample/image.jpeg");
Run Code Online (Sandbox Code Playgroud)


Jon*_*nna 3

不知道如何在node.js 中做到这一点(或者任何事情),但是您问题的PHP 位肯定是可能的。解析Base64后,将其加载到GD图像中,然后重新采样

http://php.net/manual/en/function.imagecopyresampled.php