LoginSignup
5
4

More than 5 years have passed since last update.

TextureImporterから元画像のサイズを取得する方法について

Posted at

TextureImporterクラスの公開APIの中には元画像のサイズ取得に相応すると思われる機能が存在しません。

TextureImporter

そこで、何とか取得できないかと探してみた所、それっぽい機能を見つけたのでメモ。


どうやらTextureImporterにはinternalアクセスレベルで下記のサイズ取得関数が実装されている模様。

internal void GetWidthAndHeight(ref int width, ref int height);

こちらをリフレクションを用いて呼び出すことで取得できます。

下記のフォーラムでも同様の話題が上がっていたので、呼び出し方を参考にしつつ実装したテストコードを下記に掲載します。
Getting original size of texture asset in pixels

※内部実装のためにバージョンアップの影響で動作しなくなる可能性がある点についてはご留意下さい。

using UnityEngine;
using UnityEditor;
using System.Reflection;

public class Test
{
    /// <summary>
    /// 選択しているAssetのテクスチャサイズをログ出力
    /// </summary>
    [MenuItem("Test/GetTextureSize")]
    static void GetTextureSize()
    {
        var objs = Selection.objects;
        foreach (var obj in objs)
        {
            var path = AssetDatabase.GetAssetPath(obj);
            var importer = TextureImporter.GetAtPath(path) as TextureImporter;

            if (importer == null) { continue; }
            object[] args = new object[2] { 0, 0 };
            var method = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(importer, args);

            Debug.Log( "width : " + (int)args[0] + " height : " + (int)args[1]);
        }
    }
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4