如何使用 php 压缩/降低 base64 图像的质量?

Jān*_*iss 2 php base64

我在我的数据库中的 base64 中存储了多个图像。我使用 php 作为图像路径获取图像。但是我想在从 base64 解码时减小图像的大小,因为如果我加载全尺寸图像,它会减慢我的应用程序的速度。(我只需要在后端的全尺寸图像)。

/* 

DB stuff getting base64 string from database

$img = base64 string (can be with 'data:image/jpg;base64,' in front, thats for the str_replace())
*/

if($img){
  header("Content-Type: image/png");
  echo base64_decode(str_replace("data:image/jpg;base64,","",$img));
}
Run Code Online (Sandbox Code Playgroud)

这样一切都很好。我像这样使用它:

<img src="http://example.com/getimg.php?id=4" />
Run Code Online (Sandbox Code Playgroud)

或在 css 中。由于安全原因,我需要这个,我不能在服务器上存储任何图像,也在我有access_token变量的路径中,所以随机的人看不到图像。

有没有办法在不将实际图像存储在服务器中的情况下做到这一点?

Ant*_*son 5

您可以使用imagecreatefromstringimagecopyresized

现场示例在这里

<?php
if ($img) {
    $percent = 0.5;

    // Content type
    header('Content-Type: image/jpeg');

    $data = base64_decode($img);
    $im = imagecreatefromstring($data);
    $width = imagesx($im);
    $height = imagesy($im);
    $newwidth = $width * $percent;
    $newheight = $height * $percent;

    $thumb = imagecreatetruecolor($newwidth, $newheight);

    // Resize
    imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output
    imagejpeg($thumb);
}
Run Code Online (Sandbox Code Playgroud)