画像のアスペクト比を保ったまま正方形オブジェクトのスケールを調整 デューラー
このコードでは、画像の縦横比を計算し、正方形のサイズを決定した上で、テクスチャを読み込んでから、テクスチャの縦横比を修正するためのノードを追加しています。
import bpy
import urllib.request
from math import ceil
# 画像ファイルのパス
image_path = r"C:\aaa 2023 dondon\aaa2023いつもの\test_image\main-image デューラー メトロポリタン.jfif"
# 画像を開く
try:
image = Image.open(image_path)
except:
# ファイルが読み込めなかった場合は縦3横4の比でオブジェクトを作成する
width, height = 4, 3
else:
# 画像の幅と高さを取得する
width, height = image.size
# サイズを計算する
if width > height:
size = width
ratio = height / width
else:
size = height
ratio = width / height
# 正方形を作成
bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, align='WORLD', location=(0,0,0))
square_obj = bpy.context.active_object
# オブジェクトに名前を付ける
square_obj.name = "狛犬 xy"
# アスペクト比を保ったままオブジェクトのスケールを変更する
if width > height:
square_obj.scale[1] = ratio
else:
square_obj.scale[0] = ratio
# マテリアルを作成
material = bpy.data.materials.new(name="ImageMaterial")
material.use_nodes = True
square_obj.data.materials.append(material)
square_obj.active_material = material
# テクスチャイメージを読み込む
tex_path = image_path
tex = bpy.data.images.load(tex_path)
# テクスチャノードを作成し、マテリアルに接続する
tex_node = material.node_tree.nodes.new("ShaderNodeTexImage")
tex_node.image = tex
tex_node.location = (-400, 0)
output_node = material.node_tree.nodes["Material Output"]
material.node_tree.links.new(tex_node.outputs[0], output_node.inputs[0])
# オブジェクトをXZ平面に回転する
square_obj.rotation_euler = (1.5708, 0, 0)
import bpy
import urllib.request
from math import ceil
# 画像ファイルのパス
image_path = r"C:\aaa 2023 dondon\aaa2023いつもの\test_image\main-image デューラー メトロポリタン.jfif"
# 画像を開く
try:
image = Image.open(image_path)
except:
# ファイルが読み込めなかった場合は縦3横4の比でオブジェクトを作成する
width, height = 4, 3
else:
# 画像の幅と高さを取得する
width, height = image.size
# サイズを計算する
if width > height:
size = width
ratio = height / width
else:
size = height
ratio = width / height
# 正方形を作成
bpy.ops.mesh.primitive_plane_add(size=size, enter_editmode=False, align='WORLD', location=(0,0,0))
square_obj = bpy.context.active_object
# オブジェクトに名前を付ける
square_obj.name = "狛犬 xy"
# アスペクト比を保ったままオブジェクトのスケールを変更する
if width > height:
square_obj.scale[1] = ratio
else:
square_obj.scale[0] = ratio
# マテリアルを作成
material = bpy.data.materials.new(name="ImageMaterial")
material.use_nodes = True
square_obj.data.materials.append(material)
square_obj.active_material = material
# テクスチャイメージを読み込む
tex_path = image_path
tex = bpy.data.images.load(tex_path)
# テクスチャノードを作成し、マテリアルに接続する
tex_node = material.node_tree.nodes.new("ShaderNodeTexImage")
tex_node.image = tex
tex_node.location = (-400, 0)
output_node = material.node_tree.nodes["Material Output"]
material.node_tree.links.new(tex_node.outputs[0], output_node.inputs[0])
# オブジェクトをXZ平面に回転する
square_obj.rotation_euler = (1.5708, 0, 0)