Php 压缩&;保存base64映像

Php 压缩&;保存base64映像,php,image,gd,Php,Image,Gd,我的应用程序正在从webbrowser接收base64编码的图像文件。我需要在客户端保存它们。所以我做了: $data = base64_decode($base64img); $fileName = uniqid() . '.jpg'; file_put_contents($uploadPath . $fileName, $data); return $fileName; 这很好用 现在,我需要压缩和调整图像的最大宽度和高度800,保持纵横比 所以我试着: $data = base64_de

我的应用程序正在从webbrowser接收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);
不起作用。

您可以使用


回答第二部分:

$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
$data将仅包含true或false,以指示的操作是否成功。字节位于
$uploadPath中$文件名
。如果要将实际字节返回到
$data
中,则必须使用临时输出缓冲区:

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

这是一个评论,不是回答。不,不是,这是对原始问题的回答。与此同时,问题发生了变化。