removeBackground2.php 1.73 KB
Newer Older
1 2 3 4 5 6
<?php
// phpinfo();


define('WHERE_TO_PUT','img_bg');
define('PATH_TO_BG', "img_bg");
Okthane's avatar
Okthane committed
7

Okthane's avatar
Okthane committed
8

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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'
                ]
            ]);

Okthane's avatar
Okthane committed
41
            $fp = fopen('img_bg/'.pathinfo($filename, PATHINFO_FILENAME)."NO-BG.png", "wb");
42
            fwrite($fp, $res->getBody());
Okthane's avatar
Okthane committed
43 44 45 46 47 48
            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);
49
            $data = array(
Okthane's avatar
Okthane committed
50 51
                "témoin"=>"ok",
                "src" => $base64
52 53 54 55 56 57
            );
            echo json_encode($data);
        }
    }
}
?>