eff*_*ffe 5 python blender python-3.3
我需要一个 python 脚本,它从给定的 URL 获取动态创建的图像文件,并使用该图像文件创建材质。
然后我将该材质应用于我的搅拌机对象。
下面的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))
Run Code Online (Sandbox Code Playgroud)
我试过 :
import urllib, cStringIO
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
Run Code Online (Sandbox Code Playgroud)
但我没有运气。我得到的第一个错误是
导入错误:没有名为“StringIO”的模块
Blender 中的 python 脚本 API 是否使用限制性模块或什么?
感谢您的帮助。

您似乎使用 Python 3.3,它没有cStringIO. 改用io.BytesIO:
import io
data = io.BytesIO(urllib.urlopen(URL).read())
Run Code Online (Sandbox Code Playgroud)
[编辑]
在 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>
Run Code Online (Sandbox Code Playgroud)
[编辑2]
好的,搅拌机似乎只能从文件加载。这是对脚本的修改,它下载一个 URL,将其存储在临时位置,从中创建材质,将材质打包到混合文件中并删除临时图像。
从 urllib 导入请求导入 bpy、os、io
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))
Run Code Online (Sandbox Code Playgroud)
输出:

| 归档时间: |
|
| 查看次数: |
3247 次 |
| 最近记录: |