我需要一个 python 脚本,它从给定的 URL 获取一个动态创建的图像文件,并使用该图像文件创建一个 Material 。
然后我将该 Material 应用于我的搅拌器对象。
下面的 python 代码适用于本地镜像文件
import bpy, os
def run(origin):
# Load image file from given path.
realpath = os.path.expanduser('D:/color.png')
try:
img = bpy.data.images.load(realpath)
except:
raise NameError("Cannot load image %s" % realpath)
# Create image texture from image
cTex = bpy.data.textures.new('ColorTex', type = 'IMAGE')
cTex.image = img
# Create material
mat = bpy.data.materials.new('TexMat')
# Add texture slot for color texture
mtex = mat.texture_slots.add()
mtex.texture = cTex
# Create new cube
bpy.ops.mesh.primitive_cube_add(location=origin)
# Add material to created cube
ob = bpy.context.object
me = ob.data
me.materials.append(mat)
return
run((0,0,0))
我试过了:
import urllib, cStringIO
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
但是我运气不好。我遇到的第一个错误是
ImportError: No module named 'StringIO'
Blender 中的 python 脚本 API 使用限制性模块还是什么?
感谢您的帮助。
最佳答案
您似乎使用的是 Python 3.3,它没有 cStringIO
。使用 io.BytesIO
代替:
import io
data = io.BytesIO(urllib.urlopen(URL).read())
[编辑]
在 OSX 上的 Blender 2.68a 中测试:
import io
from urllib import request
data = io.BytesIO(request.urlopen("http://careers.stackoverflow.com/jobs?a=288").read())
data
>>>> <_io.BytesIO object at 0x11050aae0>
[编辑2]
好的,blender 似乎只能从文件加载。这是对您的脚本的修改,它下载一个 url,将其存储在一个临时位置,从中创建 Material ,将 Material 打包到 blend 文件中并删除临时图像。
导入bpy、os、io 来自 urllib 导入请求
def run(origin):
# Load image file from url.
try:
#make a temp filename that is valid on your machine
tmp_filename = "/tmp/temp.png"
#fetch the image in this file
request.urlretrieve("https://www.google.com/images/srpr/logo4w.png", tmp_filename)
#create a blender datablock of it
img = bpy.data.images.load(tmp_filename)
#pack the image in the blender file so...
img.pack()
#...we can delete the temp image
os.remove(tmp_filename)
except Exception as e:
raise NameError("Cannot load image: {0}".format(e))
# Create image texture from image
cTex = bpy.data.textures.new('ColorTex', type='IMAGE')
cTex.image = img
# Create material
mat = bpy.data.materials.new('TexMat')
# Add texture slot for color texture
mtex = mat.texture_slots.add()
mtex.texture = cTex
# Create new cube
bpy.ops.mesh.primitive_cube_add(location=origin)
# Add material to created cube
ob = bpy.context.object
me = ob.data
me.materials.append(mat)
run((0,0,0))
输出:
关于python - 来自 URL 的 Blender Material ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076062/