调整 base64 图像大小

2022-01-21 00:00:00 resize image node.js base64 php

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

I have multiple Images - saved as Base64 Strings and now i want to resize these images to get thumbnails of them...

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

Best would be using Javascript (Node-Server) to resize them, but it would be possible to resize them with php, too.

提前致谢

推荐答案

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

I agree to the method from Jon Hanna: Do Parsing the Base64code then load it to GD Image before Resample. However to get it back as data it is not as easy as I though. On php in GAE it will need to enable output buffering by setting output_buffering = "On" in php.ini file.

这里我详细解释一下步骤.

Here I explain the step in detail.

此文档被视为使用 Base64code 解析创建图像 Resource 的参考:http://php.net/manual/en/function.imagecreatefromstring.php

This doc is taken as reference to Create Image Resource using the Parsing of 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));

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

This is an image resource which can be directly put to the Resample function: 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);

结果也是一个图像资源.要将其作为数据获取,我们需要缓冲.
看如何从图片资源创建base64编码字符串

The result is also an image resource. To get it as a data we need Buffering.
See how to create a base64encoded string from image resource

// Buffering
ob_start();
imagepng($image_p);
$data = ob_get_contents();
ob_end_clean();

使用下面的文档,我在 我的项目上设置了一个 GCS 存储桶作为网站所以我可以存储 &直接显示:https://cloud.google.com/storage/docs/website-configuration#提示

Using doc below I set a GCS bucket on my project as a website so I can Store & Display it directly: 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");

相关文章