调整base64图像的大小

时间:2012-09-01 23:28:19

标签: php image node.js resize base64

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

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

提前致谢

4 个答案:

答案 0 :(得分:13)

我同意the method from Jon Hanna解析 Base64code然后在重新采样之前将其加载到GD Image。然而,要把它作为数据取回它并不像我那么容易。在GAE中的php中,需要enable output buffering在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));

这是一个图片资源,可直接放入重新采样功能: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);

结果也是图像资源。要将其作为数据,我们需要缓冲 看到 how to create a base64encoded string from image resource

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

使用下面的文档我在my project上设置了一个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");

答案 1 :(得分:4)

答案 2 :(得分:3)

不知道如何在node.js中做到这一点(或者好吧,任何东西),但你的问题的PHP位当然是可能的。解析Base64后,将其加载到GD image,然后加载resample

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

答案 3 :(得分:0)

也许您可以使用一个lib来处理它。尝试WideImage。我已经使用过并且工作得很好。

示例:

$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $req->image));

$thumbnail = WideImage::load($image)
  ->resize(300, 300, 'inside')
  ->crop('center', 'center', 300, 300);

图书馆文档:http://wideimage.sourceforge.net/