OOIII/

Unity通过php上传截屏分享

最近做了一个kinect扣人像与背景融合后拍照上传的项目,拍照还好,上传也没问题,只是服务器的接受处理就不是我的强项了,网上一找正好找到一个现成的,转来备用。

1、
Unity通过截屏保存图片,同时将图片的二进制数据(byte[] bytes = tex.EncodeToJPG();)Post给PHP.

using UnityEngine;using System.Collections;using System.Net.Sockets;using System.Net;using System.Text;using System;public class Upload : MonoBehaviour{    public string url = "http://b.ooiii.com/x/upload/unityupload.php";    string picpath = "http://b.ooiii.com/x/upload/dest_page.html";    public Texture2D xiangkuang;    //此处与pad UDP通讯,后来反映过来,其实每次都是一样的数据。。    void ToPad(byte[] bytes)    {        UdpClient udpClient = new UdpClient();        //广播 33333端口        IPEndPoint IP = new IPEndPoint(IPAddress.Broadcast, 33333);        udpClient.Send(bytes, bytes.Length, IP);        udpClient.Close();    }    void Update()    {        if (Input.GetKeyDown(KeyCode.Space))        {            StartCoroutine(ScreenShot());        }    }    IEnumerator GetScreen()    {        Texture2D t2d = new Texture2D(Screen.width, Screen.height);        t2d.ReadPixels(new Rect(0,0, Screen.width, Screen.height),0,0,false);        t2d.Apply();        //此处是线性缩放图片至1920*1080尺寸        //http://wiki.unity3d.com/index.php/TextureScale        TextureScale.Bilinear(t2d,1920,1080);        Texture2D tt = Tcombine(xiangkuang,t2d);        tt.Apply();        //合并背景图后图片很大,所以改用压缩比高的jpg格式。        byte[] bytes = tt.EncodeToJPG();        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);        string str = Convert.ToInt64(ts.TotalSeconds).ToString();       string path = Application.persistentDataPath + "/" + str + ".jpg";        System.IO.File.WriteAllBytes(path, bytes);        WWWForm form = new WWWForm();        form.AddBinaryData("post", bytes,str+".jpg");        WWW www = new WWW(url, form);        yield return www;        if (!string.IsNullOrEmpty(www.error))        {            print(www.error);        }        else        {            byte[] bs = Encoding.UTF8.GetBytes(picpath);            ToPad(bs);        }        Destroy(tt,20);    }    //与背景图合并    Texture2D Tcombine(Texture2D t1, Texture2D t2)    {        Texture2D newt2d = new Texture2D(1920,1080); ;        for (int y = 0; y < t1.height; y++)        {            for (int x = 0; x < t1.width; x++)            {                Color PixelColorFore = t1.GetPixel(x, y) * t1.GetPixel(x, y).a;                Color PixelColorBack = t2.GetPixel(x, y) * (1 - t1.GetPixel(x, y).a);                newt2d.SetPixel(x, y, PixelColorBack + PixelColorFore);            }        }        return newt2d;    }}

2、UnityUpload.php 把接收到的二进制数据保存成jpg文件,转base64,并打开temp.html,将图片的路径写入文件中另存为dest_page.html.
UnityUpload.php:

<?phpfunction Create($myFile){	$temp_file = "temp.html";	$dest_file = "dest_page.html";		$fp = fopen($temp_file, "r"); 	$str = fread($fp, filesize($temp_file));		$str = str_replace("[src=]", $myFile, $str);	fclose($fp);		$handle = fopen($dest_file, "w");	fwrite($handle, $str); 	fclose($handle);}?><?php function base64_encode_image ($filename=string) {    if ($filename) {        $imgbinary = fread(fopen($filename, "r"), filesize($filename));        return 'src="data:image/png;base64,'%20.%20base64_encode($imgbinary).'"';    }}?><?php$file_path="upload/"; if(is_dir($file_path)!=TRUE) mkdir($file_path,0664) ; $name = $file_path.$_FILES['post']['name'];     if (!file_exists("{$name}"))      {		move_uploaded_file($_FILES["post"]["tmp_name"],"{$name}");      }$myFile=base64_encode_image($name);Create($myFile);?>

3、temp.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maxinum-scale=1.0, user-scalable=no"><title>volkswagen</title><style>body,p{	margin:0px;	padding:0px;}</style><script type="text/javascript">window.onload = function(){	var obj = document.getElementById("img");	var height = document.body.scrollHeight-obj.height;	var margin = Math.floor(height/2);	obj.style.marginTop = margin+"px";}</script></head><body style="background-color:#184695; margin:0px; padding:0px;"><p><img [src=]  width="100% " height="100%" id="img" style="margin-top:30px;display:block;"></p></body></html>

文中部分代码根据我的项目做了修改。
参考:http://blog.csdn.net/he_wen_jian/article/details/41687033

留下一条评论

暂无评论