アヒルのある日

株式会社AHIRUの社員ブログです。毎週更新!社員が自由に思いついたことを書きます。

Unityでギャラリーに保存してある画像をアップロードするPluginを作成してみる(#2)

こんにちは。ちゃらいプログラマです。
前回の続きになります。今回はC#側の処理を紹介します。

PluginUploadObject.csの記述

public class PluginUploadObject : MonoBehaviour
{
    private Texture2D _texture2D = null;                // Texture2D
    private Sprite _sprite = null;                  // Sprite
    private Action<Sprite, string> _callback = null;      // コールバック
    private Vector2 _spriteSize = Vector2.zero;         // Spriteサイズ

    public void Open( Vector2 spriteSize, Action<Sprite, string> callback = null )
    {
        _callback = callback;
        _spriteSize = spriteSize;

#if UNITY_ANDROID
        using( AndroidJavaObject context = new AndroidJavaObject( "※1.UnityPluginActivity" ))
        {
            // UnityPluginActivity.java側に定義した「open」メソッドを実行する
            // 保存場所はアプリケーション専用の領域
            context.Call( "open", gameObject.name, Application.persistentDataPath );
        }
#endif
    }

    // UnityPluginActivity.java側で実行される「UnityPlayer.UnitySendMessage」メソッドの第二引数に指定されている
    // 保存されたファイルパスが渡される
    public void CallbackOpen( string saveFilePath )
    {
        if( !string.IsNullOrEmpty( saveFilePath ) && File.Exists( saveFilePath ) )
        {
            // ファイル読み込み
            using( FileStream fs = new FileStream( saveFilePath, FileMode.Open, FileAccess.Read ) )
            {
                BinaryReader br = new BinaryReader( fs );
                byte[] imageData = br.ReadBytes( (int)br.BaseStream.Length );
                br.Close();

                // Texture2D生成
                _texture2D = new Texture2D( 1, 1 );
                _texture2D.LoadImage( imageData );

                float top        = 0f;
                float left        = 0f;
                float width        = _texture2D.width;
                float height    = _texture2D.height;

                // 切り取り部分の計算
                // ※今回は正方形で表示したいので以下の処理をしている
                if( _texture2D.width > _texture2D.height )
                {
                    left    = (_texture2D.width - _texture2D.height) / 2f;
                    width    = height;
                }
                else if( _texture2D.width < _texture2D.height )
                {
                    top        = (_texture2D.height - _texture2D.width) / 2f;
                    height    = width;
                }

                // Sprite生成
                _sprite    = Sprite.Create( _texture2D, new Rect( left, top, width, height ), new Vector2( 0.5f, 0.5f ) );
            }
        }

        // コールバック実行
        _callback?.Invoke( _sprite, saveFilePath );
    }
}

PluginUploadObject は適当なゲームオブジェクトにAddして、ギャラリーを表示したいタイミングで「Open」メソッドを呼び出します。
コールバックで返却される保存されたファイルパスを元にファイルのアップロードを行ってください。

今まで、Android側はC#側で完結できていたので、楽勝だなと思っていたのですが、舐めてましたね~。。。
次回はiOS側を紹介する予定です!

では、また次回!