removeBackground2.php 1.98 KB
Newer Older
1 2 3
<?php
// phpinfo();

Okthane's avatar
Okthane committed
4
//  die;
5 6
define('WHERE_TO_PUT','img_bg');
define('PATH_TO_BG', "img_bg");
Okthane's avatar
p  
Okthane committed
7
define('TEMP','temp');
Okthane's avatar
Okthane committed
8
define('KEY','n6CkFXudANRCubRKMKG5hjNa');
Okthane's avatar
Okthane committed
9

10
require_once "vendor/autoload.php"; 
Okthane's avatar
Okthane committed
11

12 13
if($_SERVER["REQUEST_METHOD"] == "POST")
{
Okthane's avatar
Okthane committed
14
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0 )
15 16 17 18 19 20
    {
        $allowed = array(
            "jpg" => "image/jpeg", 
            "png" => "image/png"
        );
        $filename = $_FILES["photo"]["name"];
Okthane's avatar
Okthane committed
21
        $newfilename = $filename;
22 23 24 25 26
        $filetype = $_FILES["photo"]["type"];
        
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(array_key_exists($ext, $allowed))
        {
Okthane's avatar
Okthane committed
27
            $client = new GuzzleHttp\Client(["verify"=>false]);
28 29 30 31
            $res = $client->post('https://api.remove.bg/v1.0/removebg', [
                'multipart' => [
                    [
                        'name'     => 'image_file',
Okthane's avatar
Okthane committed
32
                        'contents' => fopen($_FILES["photo"]["tmp_name"], 'r')
33 34 35 36 37 38 39
                    ],
                    [
                        'name'     => 'size',
                        'contents' => 'auto'
                    ]
                ],
                'headers' => [
Okthane's avatar
Okthane committed
40
                    'X-Api-Key' => KEY
41 42
                ]
            ]);
Okthane's avatar
p  
Okthane committed
43
            // On supprime l'image intermédiaire
Okthane's avatar
Okthane committed
44
            // $deletefile=unlink(TEMP.'/'.$newfilename);
45

Okthane's avatar
p  
Okthane committed
46
            //On crée et stocke l'image détourée
Okthane's avatar
Okthane committed
47
            $fp = fopen('img_bg/'.pathinfo($newfilename, PATHINFO_FILENAME)."NO-BG.png", "wb");
48
            fwrite($fp, $res->getBody());
Okthane's avatar
Okthane committed
49 50
            fclose($fp);

Okthane's avatar
Okthane committed
51
            $path = 'img_bg/'.pathinfo($filename, PATHINFO_FILENAME)."NO-BG.png";
Okthane's avatar
Okthane committed
52 53 54
            $type = pathinfo($path, PATHINFO_EXTENSION);
            $data = file_get_contents($path);
            $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
55
            $data = array(
Okthane's avatar
Okthane committed
56 57
                "témoin"=>"ok",
                "src" => $base64
58 59 60 61 62 63
            );
            echo json_encode($data);
        }
    }
}
?>