Capture 截圖工具類
using UnityEngine;
using System.Collections;
public struct ShotRect
{
public int w;//width
public int h;//hight
public float x;
public float y;
}
/// <summary>
/// 截屏
/// 注意:須等到當(dāng)前幀結(jié)束后調(diào)用
/// yield return new WaitForEndOfFrame();
/// Capture.ScreenShot();
/// </summary>
public class Capture {
/// <summary>
/// 屏幕截屏
/// </summary>
public static Texture2D ScreenShot(int width,int height)
{
Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);
texture.ReadPixels(new Rect(0f, 0f, width,height), 0, 0);//從屏幕的左下角開始讀取一個寬為width,高為height的圖片
texture.Apply();
return texture;
}
/// <summary>
/// 相機(jī)截屏
/// </summary>
/// <param name="camera">相機(jī)</param>
/// <param name="width">截圖區(qū)域?qū)?lt;/param>
/// <param name="height">截圖區(qū)域高</param>
/// <returns></returns>
public static Texture2D CameraShot(Camera camera,int width,int height)
{
RenderTexture cameraRenderTex = camera.targetTexture;
RenderTexture renderTex;
if (cameraRenderTex == null) {
renderTex = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32);
}
else {
renderTex = new RenderTexture(cameraRenderTex.width, cameraRenderTex.height, cameraRenderTex.depth);
}
Texture2D dest = new Texture2D(width, height, TextureFormat.RGB24, false);
camera.targetTexture = renderTex;
camera.Render();
RenderTexture.active = renderTex;
dest.ReadPixels(new Rect(0f, 0f, width, height),0, 0);
dest.Apply();
RenderTexture.active = null;
camera.targetTexture = null;
renderTex.Release();
return dest;
}
/// <summary>
/// 確定截圖區(qū)域的方法
/// </summary>
/// <param name="uicamera"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static ShotRect GetShotArea(Camera uicamera, Transform a, Transform b)
{
ShotRect r;
//轉(zhuǎn)換為屏幕坐標(biāo)
Vector2 v1 = uicamera.WorldToScreenPoint(a.position);
Vector2 v2 = uicamera.WorldToScreenPoint(b.position);
//確定屏幕讀取的起始坐標(biāo)
r.x = (v1.x > v2.x) ? v2.x : v1.x;
r.y = (v1.y > v2.y) ? v2.y : v1.y;
//計(jì)算截圖區(qū)域的寬和高
r.w = int.Parse(Mathf.Abs(v1.x - v2.x).ToString("F0"));
r.h = int.Parse(Mathf.Abs(v1.y - v2.y).ToString("F0"));
return r;
}
#region 指定區(qū)域截圖示例
//IEnumerator Shot()
//{
// ShotRect _rect = Capture.GetShotArea(_camera, p1, p2);
// yield return new WaitForEndOfFrame();
// Texture2D texture = new Texture2D(_rect.w, _rect.h, TextureFormat.RGB24, false);
// texture.ReadPixels(new Rect(_rect.x, _rect.y, _rect.w, _rect.h), 0, 0);
// texture.Apply();
// _image.texture = texture;
//}
#endregion
}
QR_Code 上傳服務(wù)器生成二維碼類
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.UI;
using LitJson;
using SimpleJson;
using ZXing;
using ZXing.QrCode;
public class QR_Code : MonoBehaviour
{
public static QR_Code instance;
private string Lastresult;
private Texture defaultQRCodeTexture;
private void Awake()
{
instance = this;
projectName = Configs.Instance.LoadText("QRCode", "projectName");
ip = Configs.Instance.LoadText("QRCode", "ip");
port = Configs.Instance.LoadText("QRCode","port");
}
private static Color32[] Encode(string textForEncoding, int width, int height)
{
BarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new
QrCodeEncodingOptions
{
Height = height,
Width = width
}
};
return
writer.Write(textForEncoding);
}
private void ShowSaveInfo(RawImage qrcodeImage)
{
string textForEncoding = Lastresult;
if (textForEncoding != null)
{
Texture2D encoded = new Texture2D(256, 256);
Color32[] color32 = Encode(textForEncoding, encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
qrcodeImage.texture = encoded;
Resources.UnloadUnusedAssets();
GC.Collect();
}
else
{
qrcodeImage.texture = defaultQRCodeTexture;
}
}
//string url = "http://sq.gzcloudbeingbu.com/Webpage/MyScreenshots.aspx";
public void UpLoad(byte[] bytes, string timestamp, RawImage qrcodeImage)
{
//StartCoroutine(UploadPNG(bytes, timestamp, action));
StartCoroutine(UpLoadImg(bytes, timestamp, qrcodeImage));
}
#region can
public static JsonObject StringToJsonObj(string str)
{
JsonObject player_obj = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(str);
return player_obj;
}
public static JsonArray StringToJsonArr(string str)
{
JsonArray player_obj = (JsonArray)SimpleJson.SimpleJson.DeserializeObject(str);
return player_obj;
}
#endregion
private string projectName = "";
// string ip = "";
private string ip = "";
private string port;
private IEnumerator UpLoadImg(byte[] bytes, string timestamp, RawImage qrcodeImage)
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "/" + timestamp + ".png";
byte[] bs = bytes;
WWWForm form = new WWWForm();
form.AddBinaryData("file", bs, "project:" + projectName + ",file:" + fileName, "image/png");
WWW www = new WWW("http://" + ip + ":" + port + "/upload/img_upload", form);
Debug.Log("http://" + ip + ":" + port + "/upload/img_upload");
Debug.Log(form);
yield return www;
if (www.error != null)
{
Debug.Log(www.error);
yield return null;
}
else
{
JsonObject re = StringToJsonObj(www.text);
Lastresult = re["url_src"].ToString();
Debug.Log(Lastresult);
ShowSaveInfo(qrcodeImage);
//Debug.Log(re["url_src"].ToString());
yield return null;
}
}
public static long GetTimeStamp(bool bflag = true)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
long ret;
if (bflag)
ret = Convert.ToInt64(ts.TotalSeconds);
else
ret = Convert.ToInt64(ts.TotalMilliseconds);
return ret;
}
}
GetCamera 獲取外置攝像頭
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System;
public class GetCamera : MonoBehaviour
{
public Camera mCamera;
private WebCamTexture webTex;
/// <summary>
/// 攝像機(jī)的圖像數(shù)據(jù) - 進(jìn)行展示
/// </summary>
public RawImage cameraImage;
/************** 截圖操作 *************/
/// <summary>
/// 攝像相機(jī)
/// 倒計(jì)時Image
/// 倒計(jì)時存儲的圖像
/// 倒計(jì)時進(jìn)行的延遲的秒數(shù)
/// 截圖區(qū)域:0 - StartPoint, 1 - EndPoint
/// 截圖保存圖像
/// </summary>
public Camera _camera;
public Image countDownImage;
public Sprite[] Countdowns;
public float timing = 0.2f;
public Transform[] transforms;
public RawImage _test;
/*************** 上傳服務(wù)器 **************/
/// <summary>
///寬,高
///開始截圖的位置跟結(jié)束截圖的位置
///生成二維碼的RawImage
/// 截圖區(qū)域:0 - StartPoint, 1 - EndPoint
/// </summary>
int width, height;
Vector3 startPos, endPos;
public RawImage qr_RawImage;
public Transform [] qr_transforms;
private void Start()
{
Init();
}
private void Update()
{
if (Input.GetKeyDown("q"))
{
CameraShor();
}
if (Input.GetKeyDown("w"))
{
BackPhoto();
}
if (Input.GetKeyDown("e"))
{
Save();
}
if (Input.GetKeyDown("m"))
{
StartCoroutine(Getwindowresult());
}
}
private void Init()
{
_test.gameObject.SetActive(false);
StartCallCamera();
}
/// <summary>
/// 上傳服務(wù)器截圖
/// </summary>
/// <param name="action"></param>
public void Save()
{
startPos = mCamera.WorldToScreenPoint(qr_transforms[0].position);
endPos = mCamera.WorldToScreenPoint(qr_transforms[1].position);
width = int.Parse(Mathf.Abs(startPos.x - endPos.x).ToString("F0"));
height = int.Parse(Mathf.Abs(startPos.y - endPos.y).ToString("F0"));
//計(jì)算鼠標(biāo)劃定范圍的長和寬~~
//Debug.Log(w);
//Debug.Log(h);
StartCoroutine(GetCapture());
}
/// <summary>
/// 開啟攝像頭
/// </summary>
private void StartCallCamera()
{
StartCoroutine("CallCamera");
}
/// <summary>
/// 關(guān)閉攝像頭
/// </summary>
private void StopCallCamera()
{
if (webTex != null)
{
webTex.Stop();
}
}
/// <summary>
/// 重新拍照
/// </summary>
private void BackPhoto()
{
_test.gameObject.SetActive(false);
StartCallCamera();
}
/// <summary>
/// 拍照截圖
/// </summary>
private void CameraShor()
{
StopCallCamera();
StartCoroutine("Shot");
}
/// <summary>
/// 調(diào)用攝像頭
/// </summary>
/// <returns></returns>
IEnumerator CallCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (webTex != null)
webTex.Stop();
WebCamDevice[] devices = WebCamTexture.devices;
string deviceName = devices[0].name;
//設(shè)置攝像機(jī)攝像的區(qū)域
webTex = new WebCamTexture(deviceName, 1920, 1080, 60);
cameraImage.texture = webTex;
webTex.Play();//開始攝像
}
}
/// <summary>
/// 拍照截圖
/// </summary>
/// <returns></returns>
IEnumerator Shot()
{
if (Countdowns.Length != 0)
{
///倒計(jì)時
for (int i = 0; i < Countdowns.Length; i++)
{
countDownImage.sprite = Countdowns[i];
yield return new WaitForSeconds(timing);
}
}
ShotRect _shotRect = Capture.GetShotArea(_camera, transforms[0], transforms[1]);
yield return new WaitForEndOfFrame();
Texture2D texture = new Texture2D(_shotRect.w, _shotRect.h, TextureFormat.RGB24, false);
texture.ReadPixels(new Rect(_shotRect.x, _shotRect.y, _shotRect.w, _shotRect.h), 0, 0, false);
texture.Apply();
_test.gameObject.SetActive(true);
_test.texture = texture;
StartCoroutine(DownLoadTexture(texture,"Start"));
}
/// <summary>
/// 將圖片保存在本地
/// </summary>
/// <param name="image"></param>
/// <param name="DownLoadName"> 保存在本地的名字 </param>
/// <returns></returns>
IEnumerator DownLoadTexture(Texture2D image, string DownLoadName)
{
Texture2D tempImage = null;
tempImage = image;
if (tempImage != null)
{
byte[] data = tempImage.EncodeToPNG();
File.WriteAllBytes(Application.streamingAssetsPath + "/" + DownLoadName + ".png", data);
}
yield return new WaitForEndOfFrame();
}
/// <summary>
/// 截圖上傳
/// </summary>
/// <returns></returns>
IEnumerator GetCapture()
{
//等待所有的攝像機(jī)跟GUI渲染完成
yield return new WaitForEndOfFrame();
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
//----------------------------------------------------------------------------計(jì)算區(qū)域----------------------------------------------------
float vx = (startPos.x > endPos.x) ? endPos.x : startPos.x; //取較小的x,y作為起始點(diǎn)
float vy = (startPos.y > endPos.y) ? endPos.y : startPos.y;
tex.ReadPixels(new Rect(vx, vy, width, height), 0, 0, true);
//-----------------------------------------------------------------------------------------------------------------------------------------
byte[] imagebytes = tex.EncodeToPNG();//轉(zhuǎn)化為png圖
string timestamp = QR_Code.GetTimeStamp().ToString();
//string filename = Application.streamingAssetsPath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + timestamp + ".png";
//Debug.Log(string.Format("截屏了一張照片: {0}", filename));
//File.WriteAllBytes(filename, imagebytes);
QR_Code.instance.UpLoad(imagebytes, timestamp, qr_RawImage);
}
IEnumerator Getwindowresult()
{
int width = 1080;
int height = 1920;
byte[] bytes = GetPhotoPixel(webTex);//資源
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
yield return new WaitForSeconds(0.01f);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
//img.sprite = sprite;
StartCoroutine(DownLoadTexture(texture, "Artwork"));
yield return new WaitForSeconds(0.01f);
Resources.UnloadUnusedAssets(); //一定要清理游離資源。
}
//獲取像素
private byte[] GetPhotoPixel(WebCamTexture ca)
{
Texture2D texture = new Texture2D(ca.width, ca.height);
int y = 0;
while (y < texture.height)
{
int x = 0;
while (x < texture.width)
{
UnityEngine.Color color = ca.GetPixel(x, y);
texture.SetPixel(x, y, color);
++x;
}
++y;
}
texture.Apply();
// texture.name = name ;
byte[] pngData = GetJpgData(texture);
return pngData;
}
//控制照片大小
private byte[] GetJpgData(Texture2D te)
{
byte[] data = null;
int quelity = 75;
while (quelity > 20)
{
data = te.EncodeToJPG(quelity);
int size = data.Length / 1024;
if (size > 30)
{
quelity -= 5;
}
else
{
break;
}
}
return data;
}
/// <summary>
/// 程序退出
/// </summary>
private void OnApplicationQuit()
{
StopCallCamera();
}
}