LoginSignup
35

More than 5 years have passed since last update.

【Unity】pngファイルを読み込み同サイズのTexture2Dを生成する

Last updated at Posted at 2016-02-16

はじめに

pngを読み込んで同サイズのTexture2Dを生成する方法を調べてみました.

pngファイルからTexture2Dを作成

pngを動的に読み込む方法を調べていたところ、解説してくれているブログがありました.

UnityでPNGファイルを動的に読み込む方法

ここを見ると以下のようなソースコードが載っているはずです.

***.cs
byte[] ReadPngFile(string path){
    FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
    BinaryReader bin = new BinaryReader(fileStream);
    byte[] values = bin.ReadBytes((int)bin.BaseStream.Length);

    bin.Close();

    return values;
}

Texture ReadTexture(string path, int width, int height){
    byte[] readBinary = ReadPngFile(path);

    Texture2D texture = new Texture2D(width, height);
    texture.LoadImage(readBinary);

    return texture;
}

ただし、このコードだけではTexture2Dを作成するときにwidthとheightの値が必要になります.
そこで、pngファイルから画像サイズを取得する方法を調べてみました

バイナリから画像サイズを取得する

PNGについて によれば
画像の幅は 16バイト~19バイト(長さ4バイト)
画像の高さは20バイト~23バイト(長さ4バイト)
に格納されているそうです.

これを参考に以下のようなコードを書いてみました.
width(画像の幅)とheight(画像の高さ)を取得するコードです.

***.cs
  int pos = 16; // 16バイトから開始

  int width = 0;
  for (int i = 0; i < 4; i++)
  {
    width = width * 256 + readBinary[pos++];
  }

  int height = 0;
  for (int i = 0; i < 4; i++)
  {
    height = height * 256 + readBinary[pos++];
  }

pngファイルパスからTexture2Dを生成

以上を踏まえると pngファイルパスからpngファイルと同サイズのTexture2Dを生成するコードは以下のようになると思います.

***.cs
public static Texture2D ReadPng(string path)
{
  byte[] readBinary = ReadPngFile(path);

  int pos = 16; // 16バイトから開始

  int width = 0;
  for (int i = 0; i < 4; i++)
  {
    width = width * 256 + readBinary[pos++];
  }

  int height = 0;
  for (int i = 0; i < 4; i++)
  {
    height = height * 256 + readBinary[pos++];
  }

  Texture2D texture = new Texture2D(width, height);
  texture.LoadImage(readBinary);

  return texture;
}

参考

UnityでPNGファイルを動的に読み込む方法
http://macomu.sakura.ne.jp/blog/?p=55

PNGについて
http://homepage2.nifty.com/sophia0/png.html

PNG ファイルフォーマット
http://www.setsuki.com/hsp/ext/png.htm

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
35