Compress & save base64 image

守給你的承諾、 提交于 2019-12-07 14:13:27

问题


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;

Which works fine.

Now I need to compress & resize the image to max. 800 width & height, maintaining the aspect-ratio.

So I tried:

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

which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given"). And of course, this does compress, but not resize.

Would it be best to save the file in /tmp, read it and resize/move via GD?

Thanks.

2nd part

Thanks to @ontrack I know now that

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

works.

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;
}

So I thought I could do:

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

which does not work.


回答1:


You can use imagecreatefromstring


To answer the second part:

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

$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(); 


来源:https://stackoverflow.com/questions/17255521/compress-save-base64-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!