Remove Image Background Color and Make Transparent Image Using PHP
Most graphic designers using Photoshop to make image background transparent and it will take time to learn Photoshop first. In this article I’m trying to show you, how we can remove background color of an image and make it transparent without the use of any software like Photoshop etc.
I will used an API remove.bg, which will remove background color from an image. For this first we have to create an account on remove.bg website. An API KEY is required to used this API. After creating an account successfully, we need to generate API KEY, which you generate to follow below steps:
Login into your account and go to `My Dashboard` page under top right corner image drop-down.
A new page will appear, after that click on `API Key` tab
Click on `show` button to visible your API KEY
Now I’m going to use CURL curl to hit an API `https://api.remove.bg/v1.0/removebg` with POST method. In CURL i will use a live image URL in CURLOPT_POSTFIELDS with key `image_url`. Use below code to make your image background transparent.
<?php
//API URL
$apiURL = “https://api.remove.bg/v1.0/removebg";//CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
‘x-api-key:YOUR API KEY HERE’,
]);curl_setopt($ch, CURLOPT_POSTFIELDS, [
‘image_url’ => ‘https://images.pexels.com/photos/5971183/pexels-photo-5971183.jpeg',
]);$server_output = curl_exec($ch);
curl_close($ch);$imageOutput = ‘usingphp.com.png’;
//Save image
$content = file_put_contents($imageOutput, $server_output);
if($content === FALSE) {
echo ‘Something went wrong with the API’;
}
else{
echo ‘Your transparent image is successfully downloaded’;
}
?>
Steps i used on my local using Xampp
- Create `index.php` in `xampp\htdocs\image`
- Copy paste about code in it (Use you API KEY)
- Open this URL in your browser: http://localhost/image/index.php
- Your image will downloaded successfully
In theabove code replace `YOUR API KEY HERE` to your API KEY. I’ve used file_put_content function to save an image and you can change image name using variable $imageOutput.
Note: It will not work if you do not use your API KEY
- With the help of this API we can save our time. Often I’ve hired a freelancer to make an image transparent, which will take time and money. This API will takes less than 5 seconds to make a transparent background image.
- Very simple to use this API, Copy the above code after that just replace image URL and API key. We don’t need to install heavy software which slows down our computer systems.
You can read latest articles of Srvdev on https://usingphp.com
Reference: https://usingphp.com/post/how-to-make-image-background-transparent-using-php