Created
January 17, 2014 09:20
-
-
Save GRGSIBERIA/8470512 to your computer and use it in GitHub Desktop.
スクリーンショットを撮ってJSに投げる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Text; | |
using System; | |
using System.IO; | |
using System.Collections.Generic; | |
using System.Security.Cryptography; | |
using System.Linq; | |
public class ScreenShotScript : MonoBehaviour | |
{ | |
void Start() | |
{ | |
} | |
// スクリーンショットを撮ってバイナリを返す | |
byte[] CaptureScreenShot() | |
{ | |
// テクスチャの作成 | |
var render_tex = new RenderTexture(Screen.width, Screen.height, 24); | |
var tex2d = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); | |
// レンダーテクスチャの設定 | |
camera.targetTexture = render_tex; | |
camera.Render(); | |
RenderTexture.active = render_tex; | |
tex2d.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); // 実質的にここで撮影する | |
// 撮影し終わったので後処理する | |
camera.targetTexture = null; | |
RenderTexture.active = null; | |
Destroy(render_tex); | |
return tex2d.EncodeToPNG(); | |
} | |
// 特定の文字列をMD5に変換して返す | |
string EncodeMD5(string name) | |
{ | |
var crypt = new MD5CryptoServiceProvider(); | |
var name_bytes = Encoding.UTF8.GetBytes(name); | |
var crypted_bytes = crypt.ComputeHash(name_bytes); // ここで時間をハッシュに変える | |
crypt.Clear(); | |
return BitConverter.ToString(crypted_bytes).ToLower().Replace("-", ""); | |
} | |
// ファイル名を生成する | |
string GenerateFileName() | |
{ | |
string key_name = System.DateTime.Now.ToString() + Time.realtimeSinceStartup; // 現在の時間と起動時間からファイル名を生成する | |
return EncodeMD5(key_name) + ".png"; // 最後にSHA2に変換する | |
} | |
// アップロードするよー | |
Dictionary<string, string> UploadFile(byte[] png) | |
{ | |
const string s3_url = "http://s3-ap-northeast-1.amazonaws.com/fukuwarai/images/"; | |
var file_name = GenerateFileName(); | |
// パラメータの設定 | |
var parameters = new Dictionary<string, string>(); | |
parameters["fname"] = file_name; | |
parameters["data"] = Convert.ToBase64String(png); | |
parameters["url"] = s3_url + file_name; | |
// 送信してURLを返す | |
return parameters; | |
} | |
void Capture() | |
{ | |
captureFlag = true; | |
} | |
void Update() | |
{ | |
} | |
bool captureFlag = false; | |
// ここじゃないとうまくキャプチャできないらしい | |
void LateUpdate() | |
{ | |
if (captureFlag) | |
{ | |
var png = CaptureScreenShot(); | |
var parameters = UploadFile(png); | |
var object_string = parameters["url"] + "!" + parameters["fname"] + "!" + parameters["data"]; | |
Application.ExternalCall("ShowTweetButton", object_string); | |
captureFlag = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment