【问题标题】:Compress & save base64 image压缩并保存 base64 图像
【发布时间】:2013-06-22 21:32:59
【问题描述】:

我的应用正在从网络浏览器接收 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);

这不起作用。

【问题讨论】:

    标签: php image gd


    【解决方案1】:

    您可以使用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(); 
    

    【讨论】:

    • 这是评论,不是答案。
    • 不,不是,这是对原始问题的回答。与此同时,问题发生了变化。
    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2016-12-14
    • 2011-07-28
    相关资源
    最近更新 更多