我将图像作为 base64 编码的字符串前端获取,我必须对它们进行解码并将它们作为图像保存在服务器中。图像可以是任何格式 - png、gif 或 jpeg。 这部分工作正常。但有时用户上传的图片可能非常大,所以我试图从后端压缩它们,这部分失败得很惨。
我有两个功能。一种用于将 base64 字符串转换为图像,另一种用于压缩它。
这是将字符串转换为图像的函数。
function uploadTimelineImage($base64Img)
{
$data= array();
$upAt=date('YmdHis');
if (strpos($base64Img, 'data:image/png;base64') !== false)
{
$img = str_replace('data:image/png;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'png';
}
if (strpos($base64Img, 'data:image/gif;base64') !== false)
{
$img = str_replace('data:image/gif;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'gif';
}
if (strpos($base64Img, 'data:image/jpeg;base64') !== false)
{
$img = str_replace('data:image/jpeg;base64,', '', $base64Img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$extension= 'jpeg';
}
$fileName = 'img'.$upAt.$extension;
$filePath = 'foldername/'.'img'.$upAt.$extension;
//upload image to folder
$success = file_put_contents($filePath, $data);
$result = $success ? 1 : 0;
//call to compression function
$compressThisImg= $filePath;
$d = compress($compressThisImg, $fileName, 80);
if($result==1)
{
return $fileName;
}
else
{
return null;
}
}
这是压缩函数:
//Function to compress an image
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
但是上面的函数没有做任何压缩,它抛出错误:
failed to open stream: No such file or directory
我的函数上传原始图像。
最佳答案
为什么不使用此函数从 base64 编码的图像字符串创建任何类型的图像?
function uploadTimelineImage($base64Img,$h,$w)
{
$im = imagecreatefromstring($base64Img);
if ($im !== false) {
$width = imagesx($im);
$height = imagesy($im);
$r = $width / $height; // ratio of image
// calculating new size for maintain ratio of image
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagedestroy($im);
$fileName = 'img'.date('Ymd').'.jpeg';
$filepath = 'folder/'.$fileName ;
imagejpeg($dst,$filepath);
imagedestroy($dst);
return $fileName;
}
else
{
return "";
}
}
关于php- 压缩 base64 解码图像失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38829331/