压缩&保存base64图像
我的应用程序正在从webbrowser接收base64编码的图像文件。我需要将它们保存在客户端上。所以我做了:
My app is receiving base64-encoded image-files from the webbrowser. I need to save them on the client. So I did:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
哪个工作正常。
现在我需要压缩和将图像调整为最大值。 800宽度&高度,保持宽高比。
Now I need to compress & resize the image to max. 800 width & height, maintaining the aspect-ratio.
所以我试过:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
哪个不起作用(错误:imagejpeg()期望参数1为资源,给定字符串 )。
当然,这会压缩,但不会调整大小。
which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given"). And of course, this does compress, but not resize.
最好将文件保存在/ tmp中,读取它并调整大小/移动GD?
Would it be best to save the file in /tmp, read it and resize/move via GD?
谢谢。
第二部分
感谢@ontrack我现在知道
Thanks to @ontrack I know now that
$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);
有效。
但现在我需要将图像调整到最大800宽度和高度。我有这个功能:
But now I need to resize the image to max 800 width and height. I have this function:
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);
这不起作用。
您可以使用 imagecreatefromstring
回答第二部分:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
$ data只包含true或false,表示 imagejpeg 取得了成功。字节在 $ uploadPath中。 $文件名
。如果你想要实际的字节回到 $ data
,你必须使用临时输出缓冲区:
$data will only contain either true or false to indicate wether the operation of imagejpeg was a success. The bytes are in $uploadPath . $fileName
. If you want the actual bytes back in $data
you have to use a temporary output buffer:
$img = imagecreatefromstring($data);
$img = resizeAndCompressImagefunction($img, 800, 800);
ob_start();
imagejpeg($img, null, 80);
$data = ob_get_clean();