Cara menggunakan make background transparent python

If we want to convert a picture background into transparent, we can use the Pillow package in Python to do it.

If you want to know more how to use Pillow module, you can refer to here: https://pillow.readthedocs.io/en/3.0.x/handbook/tutorial.html


Convert the background of the picture to transparent

Assume I have a picture as follows:

Cara menggunakan make background transparent python
Cara menggunakan make background transparent python

It is a picture in .jpg format.

As we can see, most of the background color is white color (rgb(255, 255, 255)). So in below, we use the Pillow package to perform conversion processing.

If it is the first time to use Pillow, use the following command to install it:

pip3 install pillow


After the installation is over, let's look at an example:

# -*- coding: utf-8 -*-
from PIL import Image

image = Image.open('input.jpg')
print(image)
print(image.mode)


Output:

<PIL.Image.Image image mode=RGBA size=626x417 at 0x179240973C8>
RGB


We can see that this is a file of PIL.Image.Image data type, and the mode of this file is "RGB".

To make the image background transparent, we need to change "RGB" to "RGBA" first. RGBA stands for Red, Green, Blue and Alpha channel.

Alpha channel stands for transparency. This is why we need to convert to this format.

image = image.convert('RGBA')

print(image.mode)


Output:

RGBA


Then we first take out the pixel value of this picture and determine whether the pixel is white (255, 255, 255):

# Transparency
newImage = []
for item in image.getdata():
    if item[:3] == (255, 255, 255):
        newImage.append((255, 255, 255, 0))
    else:
        newImage.append(item)

image.putdata(newImage)


As you can see, I replaced all dots with pixel values (255, 255, 255) with transparent. Of course, you can set what color you want to convert here.

image.save('output.png')


Finally, remember to save the picture in PNG format. JPG format does not seem to support transparent backgrounds.

Cara menggunakan make background transparent python
Cara menggunakan make background transparent python

The background of this one is already transparent. Of course, if the background is all white, there is no obvious difference, hahaha.

Learn how to create a responsive website that will work on all devices, PC, laptop, tablet, and phone.


Create a Website from Scratch


A "Layout Draft"

It can be wise to draw a layout draft of the page design before creating a website:

Side Content

Some text some text..

Main Content

Some text some text..

Some text some text..

Some text some text..


First Step - Basic HTML Page

HTML is the standard markup language for creating websites and CSS is the language that describes the style of an HTML document. We will combine HTML and CSS to create a basic web page.

Sample Code

cURL Node.js Python Ruby PHP Java .NET Swift Objective-C

$ curl -H 'X-API-Key: INSERT_YOUR_API_KEY_HERE'           \
       -F '[email protected]/path/to/file.jpg'                 \
       -F 'size=auto'                                     \
       -f https://api.remove.bg/v1.0/removebg -o no-bg.png

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});

# Requires "requests" to be installed (see python-requests.org)
import requests

response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open('/path/to/file.jpg', 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE'},
)
if response.status_code == requests.codes.ok:
    with open('no-bg.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)

# Install "remove_bg" first (https://github.com/remove-bg/ruby)
require "remove_bg"

RemoveBg.from_file("/path/to/file.jpg",
  api_key: "INSERT_YOUR_API_KEY_HERE"
).save("no-bg.png")

// Requires "guzzle" to be installed (see guzzlephp.org)
// If you have problems with our SSL certificate with error 'Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.remove.bg/v1.0/removebg'
// follow these steps to use the latest cacert certificate for cURL: https://github.com/guzzle/guzzle/issues/1935#issuecomment-371756738

$client = new GuzzleHttp\Client();
$res = $client->post('https://api.remove.bg/v1.0/removebg', [
    'multipart' => [
        [
            'name'     => 'image_file',
            'contents' => fopen('/path/to/file.jpg', 'r')
        ],
        [
            'name'     => 'size',
            'contents' => 'auto'
        ]
    ],
    'headers' => [
        'X-Api-Key' => 'INSERT_YOUR_API_KEY_HERE'
    ]
]);

$fp = fopen("no-bg.png", "wb");
fwrite($fp, $res->getBody());
fclose($fp);

// Requires "Apache HttpComponents" to be installed (see hc.apache.org)

Response response = Request.Post("https://api.remove.bg/v1.0/removebg")
    .addHeader("X-Api-Key", "INSERT_YOUR_API_KEY_HERE")
    .body(
        MultipartEntityBuilder.create()
        .addBinaryBody("image_file", new File("/path/to/file.jpg"))
        .addTextBody("size", "auto")
        .build()
    ).execute();
response.saveContent(new File("no-bg.png"));

// Requires AFNetworking to be installed (see https://github.com/AFNetworking/AFNetworking)

NSURL *fileUrl = [NSBundle.mainBundle URLForResource:@"file" withExtension:@"jpg"];
NSData *data = [NSData dataWithContentsOfURL:fileUrl];
if (!data) {
    return;
}

AFHTTPSessionManager *manager =
[[AFHTTPSessionManager alloc] initWithSessionConfiguration:
 NSURLSessionConfiguration.defaultSessionConfiguration];

manager.responseSerializer = [AFImageResponseSerializer serializer];
[manager.requestSerializer setValue:@"INSERT_YOUR_API_KEY_HERE"
                 forHTTPHeaderField:@"X-Api-Key"];

NSURLSessionDataTask *dataTask = [manager
                                  POST:@"https://api.remove.bg/v1.0/removebg"
                                  parameters:nil
                                  constructingBodyWithBlock:^(id  _Nonnull formData) {
                                      [formData appendPartWithFileData:data
                                                                  name:@"image_file"
                                                              fileName:@"file.jpg"
                                                              mimeType:@"image/jpeg"];
                                  }
                                  progress:nil
                                  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                      if ([responseObject isKindOfClass:UIImage.class] == false) {
                                          return;
                                      }

                                      self.imageView.image = responseObject;
                                  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                      // Handle error here
                                  }];

[dataTask resume];

// Requires Alamofire 5 to be installed (see https://github.com/Alamofire/Alamofire)

guard let fileUrl = Bundle.main.url(forResource: "file", withExtension: "jpg"),
  let data = try? Data(contentsOf: fileUrl)
else { return false }

struct HTTPBinResponse: Decodable { let url: String }

AF.upload(
  multipartFormData: { builder in
    builder.append(
      data,
      withName: "image_file",
      fileName: "file.jpg",
      mimeType: "image/jpeg"
    )
  },
  to: URL(string: "https://api.remove.bg/v1.0/removebg")!,
  headers: [
    "X-Api-Key": "INSERT_YOUR_API_KEY_HERE"
  ]
).responseDecodable(of: HTTPBinResponse.self) { imageResponse in
  guard let imageData = imageResponse.data,
    let image = UIImage(data: imageData)
  else { return }

  self.imageView.image = image
}

using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
    formData.Headers.Add("X-Api-Key", "INSERT_YOUR_API_KEY_HERE");
    formData.Add(new ByteArrayContent(File.ReadAllBytes("/path/to/file.jpg")), "image_file", "file.jpg");
    formData.Add(new StringContent("auto"), "size");
    var response = client.PostAsync("https://api.remove.bg/v1.0/removebg", formData).Result;

    if(response.IsSuccessStatusCode) {
        FileStream fileStream = new FileStream("no-bg.png", FileMode.Create, FileAccess.Write, FileShare.None);
        response.Content.CopyToAsync(fileStream).ContinueWith((copyTask) =>{ fileStream.Close(); });
    } else {
        Console.WriteLine("Error: " + response.Content.ReadAsStringAsync().Result);
    }
}

💭 happy easter 2022 from the team at remove.bg

🏁 🍇
  😀🔤👋🐣!🔤❗️
🍉

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
0

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
1

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
2

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
3

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
4

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
5

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
6

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
7

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
  method: 'post',
  url: 'https://api.remove.bg/v1.0/removebg',
  data: formData,
  responseType: 'arraybuffer',
  headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});
8

💭 happy easter 2022 from the team at remove.bg

🏁 🍇
  😀🔤👋🐣!🔤❗️
🍉

Was this section helpful? Yes No

Thanks for your feedback.