index.php
1 2 3 4 5 6 7 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
{ "require": { "mtownsend/remove-bg": "^2.0" } } <!DOCTYPE html> <html> <head> <title>Remove.BG API Example in PHP</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-center">Image Background Removal</h1> <form action="upload.php" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="markdownFile">Select a Image file:</label> <input type="file" class="form-control" name="file" accept="image/*"> </div> <button type="submit" class="btn btn-block btn-danger">Convert to PDF</button> </form> </div> </body> </html> <?php require 'vendor/autoload.php'; use Mtownsend\RemoveBg\RemoveBg; $target_dir = "public/uploads/"; $unique_id = uniqid(); $target_file = $target_dir . $unique_id . '_' . basename($_FILES['file']['name']); // upload the file if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){ echo "The file ". htmlspecialchars(basename($_FILES["file"]["name"])). " has been uploaded."; }else{ echo "Sorry, there was an error uploading your file."; exit; } // remove the background $removebg = new RemoveBg('####YOURAPIKEY####'); try { $output_file = $target_dir . $unique_id . '_no_bg.jpg'; $removebg->file($target_file)->save($output_file); // download the file in browser if(file_exists($output_file)){ header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($output_file).'"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: '.filesize($output_file)); readfile($output_file); exit; }else{ echo "Sorry, there was an error generating the image without background."; } } catch (Exception $e) { echo "Sorry, there was an error removing the background from your image."; } |