LoginSignup
4
2

More than 3 years have passed since last update.

【Unity】RawImageのTextureをPNGにエンコードする方法

Last updated at Posted at 2020-08-04

uGUIでおなじみRawImageから取り出したTextureをPNGにエンコードする方法の備忘録です。

TextureをTexture2Dに変換してPNGにエンコード

RawImageからtextureプロパティでTextureを取得できます。

var texture = _rawImage.texture;

しかし、EncodeToPNGメソッドはTexture2Dクラスにしか実装されていないのでTextureからTexture2Dへの変換を試みます。1

RenderTextureに変換後Texture2Dへ

単純なキャストでは変換できません。

var tex = (Texture2D)texture;

以下のエラーが出ます。

InvalidCastException: Specified cast is not valid.

先人の方々はRenderTextureを一枚噛ませて変換しているようなので、それに従います。

var tex = _rawImage.texture;
var sw = tex.width;
var sh = tex.height;
var result = new Texture2D(sw, sh, TextureFormat.RGBA32, false);
var currentRT = RenderTexture.active;
var rt = new RenderTexture(sw, sh, 32);

// RawImageのTextureをRenderTextureにコピー
Graphics.Blit(tex, rt);
RenderTexture.active = rt;

// RenderTextureのピクセル情報をTexture2Dにコピー
result.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
result.Apply();
RenderTexture.active = currentRT;

// PNGにエンコード完了
var bytes = result.EncodeToPNG();

無事にTextureからPNGのバイト配列に変換できるました。

余談

フォーラムでも同様の議論がされていました。

以下のやり方が提案されていましたが、僕の環境では動きませんでした。

public static Texture2D ToTexture2D(Texture texture)
{
    return Texture2D.CreateExternalTexture(
        texture.width,
        texture.height,
        TextureFormat.RGB24,
        false, false,
        texture.GetNativeTexturePtr());
}

UnityEditor上でしか試していないけどエラーが出ました。

Unable to retrieve image reference

環境

  • Unity2019.4.4f1

参考


  1. Textureクラスを直接PNGにエンコード出来ればよいのですが、、、 

4
2
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
4
2