2012年01月31日

[Unity] Android端末で外部画像を読み込む(インターネット、アセット内、SDカード)

Android端末で外部画像を表示する方法の備忘メモ。

まずはプロジェクトの構成↓

20120131unity_texture1.png

3種類の外部画像の読み込みをします。
上から、

・Cube1 = インターネットから取得
・Cube2 = Assets/Resources から取得(メモリ節約のため)
・Cube3 = Android端末内(SDカード)から取得

です。

オブジェクトに適用しているプログラムはCube1とCube2がJavaScript(main.js)、
Cube3がC#(LoadImage.cs)です。
プログラムと一緒に解説も載せました。

-------------------------------------------------------------------------
main.js↓
function Start () {
// ■ Cube1
// 外部画像(インターネット)の読み込み
// 【参考】http://unity3d.com/support/documentation/ScriptReference/WWW.html
var imgWWW : WWW = new WWW("http://a0.twimg.com/profile_images/1726614905/2011-12-31_09.44.31_normal.jpg");
// 取得完了まで待つ
yield imgWWW;
// オブジェクトに読み込んだテクスチャを適用
GameObject.Find("Cube1").gameObject.renderer.material.mainTexture = imgWWW.texture;

// ■ Cube2
// 外部画像(アセット内部)の読み込み
// 【参考】http://unity3d.com/support/documentation/ScriptReference/Resources.Load.html
// Assets/Resource ディレクトリにあるファイルを読み込み、オブジェクトのテクスチャとして適用
GameObject.Find("Cube2").gameObject.renderer.material.mainTexture = Resources.Load("image");
}
-------------------------------------------------------------------------

LoadImage.cs↓

using UnityEngine;
using System.Collections;
using System.IO;

public class LoadImage : MonoBehaviour {
void Start () {
// ■ Cube3
Texture2D tex = new Texture2D(0, 0);
// 【参考】http://blogs.yahoo.co.jp/nanashi_hippie/52586913.html
// 画像を読み込む
tex.LoadImage(LoadBytes("mnt/sdcard/image.jpg"));
// オブジェクトに読み込んだテクスチャを適用
GameObject.Find("Cube3").gameObject.renderer.material.mainTexture = tex;
}

/**
* パス指定で画像を読み込む
* SDカードのパス = /mnt/sdcard/...
* よくあるエラー(UnauthorizedAccessException: Access to the path "/mnt/sdcard/image.jpg" is denied.)
* が出たら、PlayerSetting で Force SD-Card Permission をオンにする!
**/
byte[] LoadBytes(string path) {
FileStream fs = new FileStream(path, FileMode.Open);
BinaryReader bin = new BinaryReader(fs);
byte[] result = bin.ReadBytes((int)bin.BaseStream.Length);
bin.Close();
return result;
}
}
-------------------------------------------------------------------------

Cube3で言っているパーミッションエラー(UnauthorizedAccessException)対策については、
PlayerSettingにあるこのチェックボタンです↓

20120131unity_texture3.png

Android端末に出力した結果です。
3つとも、ちゃんと表示されました。

20120131unity_texture2.png
posted by be-style at 20:59| Comment(0) | Unity
この記事へのコメント
コメントを書く
お名前:

メールアドレス:

ホームページアドレス:

コメント: [必須入力]