不设置readable,读取图片数据

  直接加载非Readable的Texture,是不能访问其像素数据的:

    // 加载
    var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
    var data = tex.GetPixels();

  上面的代码汇报如下错误:

    the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

  也就是说需要将Texture标记为可读状态,但是有时候在写一些图片批处理解析的时候,大量修改readable,用完以后再改回来,是非常耗时的,所以需要使用别的方式来读取Texture的像素数据。

    // 加载
    var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);

    FileStream fs = File.OpenRead(fileFullname);
    fs.Seek(0, SeekOrigin.Begin);
    byte[] image = new byte[(int)fs.Length];
    fs.Read(image, 0, (int)fs.Length);

    var texCopy = new Texture2D(tex.width, tex.height);
    texCopy.LoadImage(image);

  这样可以不修改readable,并且可以读取图像的信息。

  PS:这样读出来的数据,texture的尺寸是图片的本地尺寸,和unity import setting后的大小可能会不一样。

猜你喜欢

转载自www.cnblogs.com/sifenkesi/p/11695249.html