压缩并保存base64图片

3

我的应用程序从Web浏览器接收Base64编码的图像文件。我需要将它们保存在客户端上。所以我这样做了:

$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;

这个很好用。

现在我需要将图片压缩并调整大小,最大宽度和高度为800,同时保持纵横比。

所以我尝试了以下方法:

$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;

代码出现错误(错误信息:"imagejpeg() 期望参数1为资源类型,但传递了字符串类型")。当然,这段代码可以压缩图片,但无法改变尺寸。

最好的做法是将文件保存在/tmp目录下,并通过GD库读取并重新调整大小或移动。

谢谢。

第二部分

感谢 @ontrack,我现在知道了

$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);

这段代码原本能够正常工作。

但是现在我需要将图片缩放至最大800宽度和高度。我有以下函数:

function resizeAndCompressImagefunction($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*($r-$w/$h)));
        } else {
            $height = ceil($height-($height*($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return $dst;
}

所以我认为我可以这样做:

$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);

无法正常工作。
1个回答

3

您可以使用imagecreatefromstring


回答第二个问题:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);

$data只包含true或false,表示imagejpeg操作是否成功。字节在$uploadPath . $fileName中。如果您想要实际的字节返回$data,您必须使用临时输出缓冲区:

$img = imagecreatefromstring($data);
$img = resizeAndCompressImagefunction($img, 800, 800);
ob_start();
imagejpeg($img, null, 80);
$data = ob_get_clean(); 

这是一条注释,而不是答案。 - Alain Tiemblo
3
不是的,它是对最初问题的回答。与此同时,问题已经改变。 - ontrack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接