如何在php中将图像保存到文件夹

问题描述 投票:0回答:1

我有一个裁剪的图像,它的src就像data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAY....。当我点击此URL时,它将在我自己的系统中打开,而不是在其他系统中打开。如何移动到文件夹,从而保存?

php image
1个回答
1
投票
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
//THIS FOR VALIDATION(CHECK VALID BASE64)
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif
    //GET FILE NAME AND EXTENSION

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    //EXTENSION VALIDATION

    $data = base64_decode($data);
    //DECODE DATA

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }

} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);
//FINALLY GET  IMAGE
© www.soinside.com 2019 - 2024. All rights reserved.