Adding 3D-view background with Python

As part of a script I’m writing I’m trying to get Python to add some backgrounds to the editor 3D-view, just as it is done manually via the “Background Images” tab of the 3D-view properties.

I’m not sure if I’m trying to do it the right way… Right now I’m trying to influence the “Background Images” menu itself with my script. So far I did this:

img ="/path/to/file.jpg", directory="/path/to/", files=[{"name":"file.jpg", "name":"file.jpg"}], relative_path=True, show_multiview=False)
bpy.context.space_data.show_background_images = True
view = bpy.context.space_data
for i, bg in enumerate(view.background_images):
         '''bg is each background image object - returns <bpy_struct, BackgroundImage at 0x7f588cfb3188>'''

Currently it loads an image file to Blender (saved as the “img” variable), adds a new background slot in “Background Images” tab and cycles through the background slots (just 1 in this example code).
However, I haven’t figured out how to assign the loaded image to the background slot, even after looking at the source code for “Background Images” tab. Is it even the right thing to do, or should I assign the image somewhere else instead?


PS: Sorry if I’m posting this in the wrong forum, not sure if the thread fits here or in “Beginning Blender Code and Development”

Hi you can do this using API calls rather than operators

import bpy
context = bpy.context
screen = context.screen

filepath = "somepathtoimage"

# adds a new image to blender 
im =

#get a view 3d area for testing purposes
#will be context.area if code is invoked from that area.
for a in screen.areas:
    if a.type == 'VIEW_3D':

# get the 3d space
space =

# add a new background image "slot"
bi =
# assign the image to it
bi.image = im
# set some bg image props.
bi.view_axis = 'CAMERA'

batFINGER, thanks, it’s working! :slight_smile:
Just needed to change “for a in screen.areas:” to “for a in bpy.context.screen.areas:”

The image is added to the screen, and all the options in “Background Images” tab are automatically set as needed.

Big thanks to batFINGER, i used part of this code and a part he posted on blender.stackexhange to make this a addon. I made a addon which can export background images into a file so you can import them into a other scene or new scene. One thing to mind is that when using relative paths the scene which is going to import the files needs to be aside of the original. Absolute paths works just fine

For now i got it working and it gathers all background images from all scene. Puts them in a textfile. Then open your new scene and use import. It will add all images as background images according to the original file. I think im going to add some more function like add screens orso, not sure if this is handy though??

People can try it out getting this link