1

I am building an auto image background remover website using the remove.bg API. I have the following code:

# 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) 

here on the 5th line, they have added the image path manually so what I should write in this code to get local image input from users just like they access ours??

Mig82
  • 4,856
  • 4
  • 40
  • 63
Khan Rehan
  • 11
  • 1

1 Answers1

1

Try an input statement:

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

file_path = input("Please insert the path to the image: ")

response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open(f'{file_path}', '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) 
alien_jedi
  • 306
  • 3
  • 11
  • Great answer! Note that `f'{file_path}'` can be just `file_path`. There is no need for `f'{}'` when you already have a string. – Code-Apprentice Apr 23 '22 at 16:08
  • 1
    @Code-Apprentice Thanks for pointing that out! I use string formatting so much I'm just in the habit of always using f-strings, but you are correct, it is not necessary in this situation. – alien_jedi Apr 23 '22 at 16:42