Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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]);
        }
    }
}
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away