removeBackground2.php 1.98 KB
<?php
// phpinfo();

//  die;
define('WHERE_TO_PUT','img_bg');
define('PATH_TO_BG', "img_bg");
define('TEMP','temp');
define('KEY','n6CkFXudANRCubRKMKG5hjNa');

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"];
        $newfilename = $filename;
        $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($_FILES["photo"]["tmp_name"], 'r')
                    ],
                    [
                        'name'     => 'size',
                        'contents' => 'auto'
                    ]
                ],
                'headers' => [
                    'X-Api-Key' => KEY
                ]
            ]);
            // On supprime l'image intermédiaire
            // $deletefile=unlink(TEMP.'/'.$newfilename);

            //On crée et stocke l'image détourée
            $fp = fopen('img_bg/'.pathinfo($newfilename, 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);
        }
    }
}
?>