• Okthane's avatar
    n · 61812c2e
    Okthane authored
    61812c2e
removeBackground2.php 1.73 KB
<?php
// phpinfo();


define('WHERE_TO_PUT','img_bg');
define('PATH_TO_BG', "img_bg");


require_once "vendor/autoload.php"; 
if($_SERVER["REQUEST_METHOD"] == "POST")
{
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0)
    {
        $allowed = array(
            "jpg" => "image/jpeg", 
            "png" => "image/png"
        );
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(array_key_exists($ext, $allowed))
        {
            $client = new GuzzleHttp\Client(['verify' => false]);
            $res = $client->post('https://api.remove.bg/v1.0/removebg', [
                'multipart' => [
                    [
                        'name'     => 'image_file',
                        'contents' => fopen('img/'.$filename, 'r')
                    ],
                    [
                        'name'     => 'size',
                        'contents' => 'auto'
                    ]
                ],
                'headers' => [
                    'X-Api-Key' => 'qYXf5PimffLjeH1i5B1rySQw'
                ]
            ]);

            $fp = fopen('img_bg/'.pathinfo($filename, PATHINFO_FILENAME)."NO-BG.png", "wb");
            fwrite($fp, $res->getBody());
            fclose($fp);

            $path = 'img_bg/'.pathinfo($filename, PATHINFO_FILENAME)."NO-BG.png";
            $type = pathinfo($path, PATHINFO_EXTENSION);
            $data = file_get_contents($path);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
            $data = array(
                "témoin"=>"ok",
                "src" => $base64
            );
            echo json_encode($data);
        }
    }
}
?>