2017-01-19 21 views
0

我有一个服务器客户端系统,其中服务器解析模型文件并使用套接字将顶点数据发送到客户端。当模型包含纹理时,会出现问题。我可以将纹理(png文件)读取到一个字节数组,并使用套接字将其发送到客户端。但我不知道如何从字节数组创建一个THREE.Texture是否有可能从字节数组而不是文件路径构造THREE.Texture?

所以这里是我的问题,是否有可能从字节数组构造THREE.Texture?我怎样才能实现它?

此外,您可以建议其他更好的方法从服务器发送纹理到客户端。

谢谢。

回答

1

如果你已经从WebSocket的的ByteArray还有一个更elegant-这个使用斑点解决方案:

// assuming `byteArray` came in from the websocket 
var texture = new THREE.Texture(); 
var imageBlob = new Blob([byteArray.buffer], {type: "image/png"}); 
var url = URL.createObjectUrl(imageBlob); 

var image = new Image(); 
image.src = url; 
image.onload = function() { 
    texture.image = image; 
    texture.needsUpdate = true; 
}; 

你现在有一个正确的URL(类似blob:http://example.com/$uuid)等。无论您想,您可以使用。这样做的主要好处是可以节省将数据转换为base64所需的时间,并且在尝试向您显示base64-url的数百KB字节长字符串时不会使devtools崩溃。

但是还有一个选项(不幸的是还没有得到广泛的支持):createImageBitmap()。与此同时,我会如此简单:

var texture = new THREE.Texture(); 
var imageBlob = new Blob([byteArray.buffer], {type: "image/png"}); 

createImageBitmap(imageBlob).then(function(imageBitmap) { 
    texture.image = imageBitmap; 
    texture.needsUpdate = true; 
}); 
1

好吧,经过对网络的一些研究,我发现了一种方法来做到这一点。我必须从字节数组中创建数据uri并将其传递给THREE.TextureLoader。下面是代码来做到这一点 -

 let data_uri = "data:image/png;base64," + convert_to_base64_string(my_byte_array); 

     // instantiate a loader 
     let loader_t = new THREE.TextureLoader(); 
     loader_t.load(
      // resource URL 
      data_uri, 
      // Function when resource is loaded 
      function (texture) { 


       let plane = scene.getObjectByName("test-texture"); 
       plane.material.map = texture; 

       plane.material.needsUpdate = true; 
      }, 
      // Function called when download progresses 
      function (xhr) { 
       console.log((xhr.loaded/xhr.total * 100) + '% loaded'); 
      }, 
      // Function called when download errors 
      function (xhr) { 
       console.log('An error happened'); 
      } 
     ); 
1

你必须遵循一些步骤:

将字节转换为base64:柔可以使用像https://github.com/beatgammit/base64-js

库使用Base64 DATAS创建图像:

var image = new Image(); 
image.src = "data:image/png;base64," + myBase64Datas; 

从图像创建纹理。

var texture = new THREE.Texture(); 
texture.image = image; 
image.onload = function() { 
    texture.needsUpdate = true; 
}; 

如果你有麻烦,你可以检查从字节组转换在线的base64观众这样为Base64: http://codebeautify.org/base64-to-image-converter

相关问题