Browse Source

Fixes writing satellite images extension, fixes #217

Vicente Penades 1 year ago
parent
commit
d5b92d5e62

+ 17 - 0
src/SharpGLTF.Core/Memory/MemoryImage.cs

@@ -307,6 +307,23 @@ namespace SharpGLTF.Memory
                 throw new InvalidOperationException("Image format not recognized.");
             }
         }
+        
+        /// <summary>
+        /// If the given path ends with an image extension, it removes the extension.
+        /// </summary>
+        /// <param name="path">A file path</param>
+        /// <returns>a trimmed path if it had an image extension, or the original path.</returns>
+        public static string TrimImageExtension(string path)
+        {
+            if (path == null) return null;
+
+            foreach (var ext in new string[] { ".jpg",".jpeg",".png",".dds",".webp",".ktx2" })
+            {
+                if (path.EndsWith(ext, StringComparison.OrdinalIgnoreCase)) return path.Substring(0, path.Length - ext.Length);
+            }
+
+            return path;
+        }
 
         #endregion
 

+ 6 - 3
src/SharpGLTF.Core/Schema2/gltf.Images.cs

@@ -218,10 +218,13 @@ namespace SharpGLTF.Schema2
             Memory.MemoryImage._Verify(imimg, nameof(imimg));
 
             if (string.IsNullOrWhiteSpace(AlternateWriteFileName))
-            {
-                satelliteUri = System.IO.Path.ChangeExtension(satelliteUri, imimg.FileExtension);
+            {            
+                // at this point satelliteUri should not have an image extension,
+                // but it's better to ensure the path is sanitized.
+                satelliteUri = Memory.MemoryImage.TrimImageExtension(satelliteUri);
+                satelliteUri += "." + imimg.FileExtension;
             }
-            else
+            else // using a custom user-provided alternate file path
             {
                 satelliteUri = AlternateWriteFileName;
                 if (satelliteUri.EndsWith(".*"))

+ 17 - 0
tests/SharpGLTF.Core.Tests/Schema2/LoadAndSave/RegressionTests.cs

@@ -112,5 +112,22 @@ namespace SharpGLTF.Schema2.LoadAndSave
             var gltf = ModelRoot.Load(ResourceInfo.From("cube-integer-min-max-bounds.gltf"));
             Assert.That(gltf, Is.Not.Null);
         }
+
+        [Test]
+        public void SaveToPathWithExtraDots()
+        {
+            // https://github.com/vpenades/SharpGLTF/issues/217
+
+            var path1 = TestFiles.GetSampleModelsPaths().First(item => item.EndsWith("BoxTextured.gltf"));
+
+            var model = ModelRoot.Load(path1);                       
+            
+
+            var attachmentPath = AttachmentInfo.From("BoxTextured.xyz.gltf").WriteObject(f => model.Save(f));
+
+            var texturePath = attachmentPath.Directory.GetFiles("BoxTextured.xyz.png").FirstOrDefault();
+
+            Assert.That(texturePath.Name, Is.EqualTo("BoxTextured.xyz.png"));
+        }
     }
 }