[Bf-extensions-cvs] [45afacf7] blender-v2.83-release: glTF importer: use friendly filenames for temp image files

Julien Duroure noreply at git.blender.org
Sat Apr 18 09:39:35 CEST 2020


Commit: 45afacf7a630e7e77cdfc58c1b363e6e0e7747a5
Author: Julien Duroure
Date:   Sat Apr 18 09:39:07 2020 +0200
Branches: blender-v2.83-release
https://developer.blender.org/rBA45afacf7a630e7e77cdfc58c1b363e6e0e7747a5

glTF importer: use friendly filenames for temp image files

===================================================================

M	io_scene_gltf2/__init__.py
M	io_scene_gltf2/blender/imp/gltf2_blender_image.py
M	io_scene_gltf2/io/imp/gltf2_io_binary.py
M	io_scene_gltf2/io/imp/gltf2_io_gltf.py

===================================================================

diff --git a/io_scene_gltf2/__init__.py b/io_scene_gltf2/__init__.py
index ea3aa8ae..0fe7bfcb 100755
--- a/io_scene_gltf2/__init__.py
+++ b/io_scene_gltf2/__init__.py
@@ -15,7 +15,7 @@
 bl_info = {
     'name': 'glTF 2.0 format',
     'author': 'Julien Duroure, Norbert Nopper, Urs Hanselmann, Moritz Becher, Benjamin Schmithüsen, Jim Eckerlein, and many external contributors',
-    "version": (1, 2, 67),
+    "version": (1, 2, 68),
     'blender': (2, 83, 9),
     'location': 'File > Import-Export',
     'description': 'Import-Export as glTF 2.0',
diff --git a/io_scene_gltf2/blender/imp/gltf2_blender_image.py b/io_scene_gltf2/blender/imp/gltf2_blender_image.py
index a0b01aed..63ef0a92 100755
--- a/io_scene_gltf2/blender/imp/gltf2_blender_image.py
+++ b/io_scene_gltf2/blender/imp/gltf2_blender_image.py
@@ -17,6 +17,7 @@ import os
 import tempfile
 from os.path import dirname, join, isfile, basename, normpath
 import urllib.parse
+import re
 
 from ...io.imp.gltf2_io_binary import BinaryData
 
@@ -31,35 +32,35 @@ class BlenderImage():
     def create(gltf, img_idx):
         """Image creation."""
         img = gltf.data.images[img_idx]
+        img_name = img.name
 
         if img.blender_image_name is not None:
             # Image is already used somewhere
             return
 
-        tmp_file = None
+        tmp_dir = None
         try:
             if img.uri is not None and not img.uri.startswith('data:'):
                 # Image stored in a file
                 img_from_file = True
                 path = join(dirname(gltf.filename), _uri_to_path(img.uri))
-                img_name = basename(path)
+                img_name = img_name or basename(path)
                 if not isfile(path):
                     gltf.log.error("Missing file (index " + str(img_idx) + "): " + img.uri)
                     return
             else:
                 # Image stored as data => create a tempfile, pack, and delete file
                 img_from_file = False
-                img_data, img_name = BinaryData.get_image_data(gltf, img_idx)
+                img_data = BinaryData.get_image_data(gltf, img_idx)
                 if img_data is None:
                     return
-                tmp_file = tempfile.NamedTemporaryFile(
-                    prefix='gltfimg-',
-                    suffix=_img_extension(img),
-                    delete=False,
-                )
-                tmp_file.write(img_data)
-                tmp_file.close()
-                path = tmp_file.name
+                img_name = img_name or 'Image_%d' % img_idx
+                tmp_dir = tempfile.TemporaryDirectory(prefix='gltfimg-')
+                filename = _filenamify(img_name) or 'Image_%d' % img_idx
+                filename += _img_extension(img)
+                path = join(tmp_dir.name, filename)
+                with open(path, 'wb') as f:
+                    f.write(img_data)
 
             num_images = len(bpy.data.images)
             blender_image = bpy.data.images.load(os.path.abspath(path), check_existing=img_from_file)
@@ -71,9 +72,8 @@ class BlenderImage():
             img.blender_image_name = blender_image.name
 
         finally:
-            if tmp_file is not None:
-                tmp_file.close()
-                os.remove(tmp_file.name)
+            if tmp_dir is not None:
+                tmp_dir.cleanup()
 
 def _uri_to_path(uri):
     uri = urllib.parse.unquote(uri)
@@ -84,4 +84,8 @@ def _img_extension(img):
         return '.png'
     if img.mime_type == 'image/jpeg':
         return '.jpg'
-    return None
+    return ''
+
+def _filenamify(s):
+    s = s.strip().replace(' ', '_')
+    return re.sub(r'(?u)[^-\w.]', '', s)
diff --git a/io_scene_gltf2/io/imp/gltf2_io_binary.py b/io_scene_gltf2/io/imp/gltf2_io_binary.py
index 8815ed91..9057c17c 100755
--- a/io_scene_gltf2/io/imp/gltf2_io_binary.py
+++ b/io_scene_gltf2/io/imp/gltf2_io_binary.py
@@ -161,16 +161,14 @@ class BinaryData():
     def get_image_data(gltf, img_idx):
         """Get data from image."""
         pyimage = gltf.data.images[img_idx]
-        image_name = "Image_" + str(img_idx)
 
-        assert(not (pyimage.uri is not None and pyimage.buffer_view is not None))
+        assert not (
+            pyimage.uri is not None and
+            pyimage.buffer_view is not None
+        )
 
         if pyimage.uri is not None:
-            data, file_name = gltf.load_uri(pyimage.uri)
-            return data, file_name or image_name
-
-        elif pyimage.buffer_view is not None:
-            data = BinaryData.get_buffer_view(gltf, pyimage.buffer_view)
-            return data, image_name
-
-        return None, None
+            return gltf.load_uri(pyimage.uri)
+        if pyimage.buffer_view is not None:
+            return BinaryData.get_buffer_view(gltf, pyimage.buffer_view)
+        return None
diff --git a/io_scene_gltf2/io/imp/gltf2_io_gltf.py b/io_scene_gltf2/io/imp/gltf2_io_gltf.py
index 3224a4a1..88ba5356 100755
--- a/io_scene_gltf2/io/imp/gltf2_io_gltf.py
+++ b/io_scene_gltf2/io/imp/gltf2_io_gltf.py
@@ -175,7 +175,7 @@ class glTFImporter():
         buffer = self.data.buffers[buffer_idx]
 
         if buffer.uri:
-            data, _file_name = self.load_uri(buffer.uri)
+            data = self.load_uri(buffer.uri)
             if data is not None:
                 self.buffers[buffer_idx] = data
 
@@ -185,20 +185,18 @@ class glTFImporter():
                 self.buffers[buffer_idx] = self.glb_buffer
 
     def load_uri(self, uri):
-        """Loads a URI.
-        Returns the data and the filename of the resource, if there is one.
-        """
+        """Loads a URI."""
         sep = ';base64,'
         if uri.startswith('data:'):
             idx = uri.find(sep)
             if idx != -1:
                 data = uri[idx + len(sep):]
-                return memoryview(base64.b64decode(data)), None
+                return memoryview(base64.b64decode(data))
 
         path = join(dirname(self.filename), unquote(uri))
         try:
             with open(path, 'rb') as f_:
-                return memoryview(f_.read()), basename(path)
+                return memoryview(f_.read())
         except Exception:
             self.log.error("Couldn't read file: " + path)
-            return None, None
+            return None



More information about the Bf-extensions-cvs mailing list