3
$\begingroup$

What I want to do: Have a script, which opens a glb file, reduce all textures with sizes greater than 512x512 to 512x512 and export to a glb again.

I've tested in blender:

  1. import a .glb
  2. open python console
  3. type: bpy.data.images[0].scale(512,512)
  4. type: bpy.data.images[0].save()
  5. export as glb which works fine.

Then I wrote a script:

# Import glb, which is working fine...
for image in bpy.data.images:
    if (image.size[0] > 512 or image.size[1] > 512):
        scalingfactor = 512.01 / max(image.size[0], image.size[1])
        nx = math.floor(scalingfactor * image.size[0])
        ny = math.floor(scalingfactor * image.size[1])
        print("scaling image", image.size[0], image.size[1], "to", nx, ny)
        image.scale( nx, ny )
        print("new size is:", image.size[0], image.size[1])
        image.save()
        print("image saved")
# Export .glb

The last valid output I get is: "new size is: 512 512" and then

Error: Unable to pack file, source path 'C:\Users\MYNAME\AppData\Local\Temp\gltfimg-k4yrdaga\Image_1.png' not found
ERROR: Image "C:\Users\MYNAME\AppData\Local\Temp\gltfimg-k4yrdaga\Image_1.png" not available. Keeping packed image fp

If I remove image.save() then saving the glb does not work (not even in blender itself): This causes the following error message:

TypeError: expected sequence size is 16777216, got 1048576
@ "gltf2_blender_image.py", line 254, in make_temp_image_copy
tmp_image.pixels.foreach_setting(tmp_buf)

The file, which I used, is a standard sample from Khronos Group: https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/Corset/glTF-Binary ( But this happens across all files I tested )

$\endgroup$
2
  • $\begingroup$ What happens if you call image.pack() instead of image.save() there? $\endgroup$
    – emackey
    Commented Feb 2, 2022 at 14:09
  • $\begingroup$ That did the trick! Thank you very much! $\endgroup$ Commented Feb 2, 2022 at 14:27

1 Answer 1

3
$\begingroup$

After modifying the image, the result becomes a temporary thing that's different from the original stored image. To solve this, call:

image.pack()

This makes the resized image a more permanent object in the Blender project, and helps it export correctly.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .