我有多张图片,已保存为Base64字符串,现在我想将它们调整大小以获取缩略图...
最好使用Javascript(Node-Server)来调整它们的大小,但也可以使用php进行调整。
谢谢提前。
我同意Jon Hanna的方法:对Base64code进行解析,然后加载到GD图像中再进行重新采样。然而,要将其作为数据获取回来并不像我想象的那么容易。在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));
这是一个图像资源,可以直接放入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);
结果也是一个图像资源。要将其作为数据获取,我们需要缓冲。
请参见如何从图像资源创建base64编码的字符串
// Buffering
ob_start();
imagepng($image_p);
$data = ob_get_contents();
ob_end_clean();
使用下面的文档,我在我的项目上设置了一个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");
$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);
imagecopyresampled()
生成的质量比imagecopyresized()
更好,因为它进行了插值。 - garrettlynchirl