使用Unity3D在PC+Android端截图保存,再添加到数据库中
前提:
1.使用的工具为Unity2021+VS2019+mysql8.0
2.使用的支持包

3.Unity组件


代码
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using UnityEngine.UI;
using MySql.Data.MySqlClient;
using System.Data;
using UnityEditor;
public class ScreenShot : MonoBehaviour
{
//提示对象
public Text text;
//截图数组
private byte[] byt;
private MySqlConnection myConnnect = null;
private MySqlCommand sqlCommand = null;
//code检查编号
private int code = 1;
///
/// 保存截屏图片,并且刷新相册 Android
///
public void OnCapture_Normal_Screenshot()
{
//截图名称
string imageName = "";
//截图业务状态
string type = "Normal";
imageName = "Screenshot_" + type + "_" + GetCurTime() + ".png";
Screenshot(type, imageName);
code++;
}
///
/// 保存截屏图片,并且刷新相册 Android
///
public void OnCapture_Exception_Screenshot()
{
//截图名称
string imageName = "";
//截图业务状态
string type = "Exception";
imageName = "Screenshot_"+type+"_" + GetCurTime() + ".png";
//执行截图
Screenshot(type,imageName);
code++;
}
/// <summary>
/// 截图
/// </summary>
/// <param name="type">截图业务状态</param>
public void Screenshot(string type,string imageName) {
if (Application.platform == RuntimePlatform.Android)
{
//提示
text.text = "上报完成";
//Android版本
SaveAndroidImages(imageName);
//StartCoroutine(Android_CutImage(imageName));//保存到手机相册
}
else
{
// 编辑器下 PC平台
//地址
string path = Application.dataPath + "/ScreenShot/";
// 判断路径不存在创建路径
OnExists(path);
StartCoroutine(PC_CutImage(path+ imageName));//保存到PC平台
//提示
text.text = "上报完成";
}
//SQL_CutImage(type, imageName);//保存到MySQL数据库
}
/// <summary>
/// 保存到Android端
/// </summary>
/// <param name="imageName"></param>
/// <returns></returns>
/// <summary>
private void SaveAndroidImages(string imageName)
{
string path = Application.streamingAssetsPath;
#if UNITY_ANDROID && !UNITY_EDITOR
path = "/sdcard/DCIM/Camera"; //设置图片保存到设备的目录.
#endif
OnExists(path);//判断路径是否存在,不存在创建
string savePath = path + "/" + imageName;
try
{
Application.HasUserAuthorization(UserAuthorization.Microphone);
byt = DeCompress(ScreenCapture.CaptureScreenshotAsTexture()).EncodeToPNG();
File.WriteAllBytes(savePath, byt);
OnSaveImagesPlartform(savePath);
}
catch
{
}
}
/// <summary>
/// 保存到PC端
/// </summary>
/// <param name="path">保存地址</param>
/// <returns></returns>
//#if UNITY_EDITOR
public IEnumerator PC_CutImage(string path)
{
Debug.Log("开始执行截图保存到byte[]数组");
//等待帧结束
yield return new WaitForEndOfFrame();
Texture2D texture2D = ScreenCapture.CaptureScreenshotAsTexture();
byte[] bytes = texture2D.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
//AssetDatabase.Refresh();
byt = bytes;
}
//截屏并保存
public void SQL_CutImage(string status, string imageName)
{
//将截图存储到MySQL
//LinkedDatabase data = new LinkedDatabase();
//打开数据库
mysqlOpen();
if (myConnnect.State == ConnectionState.Open)
{
//执行sql插入
sqlCommand = new MySqlCommand();
sqlCommand.Connection = myConnnect;
sqlCommand.CommandText = "INSERT INTO check_up(`id`, `name`, `type`, `code`, `imageName`, `image`, `describe`, `createTime`) VALUES (@id,@name,@type,@code,@imageName,@image,@describe,@createTime)";
sqlCommand.Parameters.Clear();
sqlCommand.Parameters.AddWithValue(@"id", GenerateCheckCode(36));
sqlCommand.Parameters.AddWithValue(@"name", "appTest");
sqlCommand.Parameters.AddWithValue(@"type", status);
sqlCommand.Parameters.AddWithValue(@"code", "00" + code);
sqlCommand.Parameters.AddWithValue(@"imageName", imageName);
sqlCommand.Parameters.AddWithValue(@"image", new MySqlParameter("image", byt));
sqlCommand.Parameters.AddWithValue(@"describe", "测试截图存储操纵");
sqlCommand.Parameters.AddWithValue(@"createTime", DateTime.Now.ToLocalTime());
int count = sqlCommand.ExecuteNonQuery();
if (count > 0)
{
Debug.Log("数据插入成功!");
}
else
{
Debug.Log("数据插入失败!");
}
sqlCommand.Dispose();
myConnnect.Close();
}
}
///
/// 获取当前年月日时分秒,如20181001444
///
public string GetCurTime()
{
return DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
+ DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
}
/// <summary>
/// 退出
/// </summary>
public void OnApplicationQuit()
{
//退出程序
Application.Quit();
}
//打开数据库
public void mysqlOpen()
{
//定义mysql连接字符串
string constring = "data source=10.10.2.211;database=test;user id=root;password=000000;pooling=true;charset=utf8;";
//连接mysql
myConnnect = new MySqlConnection(constring);
//打开数据库连接
myConnnect.Open();
}
//关闭链接
public void OnClose()
{
sqlCommand.Dispose();
myConnnect.Close();
}
private int rep = 0;
/// 生成随机字母字符串(数字字母混和)
///
/// 待生成的位数
/// 生成的字母字符串
public string GenerateCheckCode(int codeCount)
{
string str = string.Empty;
long num2 = DateTime.Now.Ticks + this.rep;
this.rep++;
System.Random random = new System.Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
for (int i = 0; i < codeCount; i++)
{
char ch;
int num = random.Next();
if ((num % 2) == 0)
{
ch = (char)(0x30 + ((ushort)(num % 10)));
}
else
{
ch = (char)(0x41 + ((ushort)(num % 0x1a)));
}
str = str + ch.ToString();
}
return str;
}
/// <summary>
/// 判断路径不存在创建路径
/// </summary>
/// <param name="path"></param>
public void OnExists(string path) {
if (Directory.Exists(path) == false)
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// 刷新相册(不需要单独创建原生aar或jar)
/// </summary>
/// <param name="path"></param>
private void OnSaveImagesPlartform(string filePath)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string[] paths = new string[1];
paths[0] = filePath;
using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
{
Conn.CallStatic("scanFile", playerActivity, paths, null, null);
}
}
#endif
}
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public Texture2D DeCompress(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width, source.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
}
注意:要想在Android端保存到MySQL数据库需要将数据库部署到云服务器上在链接公网IP地址的数据库就可以
public static class MySqlConn{
//用于标识数据库是否连接成功
public static string connectStatus = "unload";
//charset=utf8 这句话用于解决 客户端发送中文数据到数据库的时候 中文数据变成问号的情况
//(port)端口是3306 需要在服务器中打开这个端口 不然连接不了
public static String connetStr = "server = 服务器的公网ip地址; port = 3306; User = 数据库的用户名; password = 数据库的密码; Database = 数据库名字; charset=utf8";
//实例化一个连接变量
public static MySqlConnection conn = new MySqlConnection(connetStr);
public static void Load()
{
try
{
conn.Open(); //打开连接数据库
connectStatus = "loaded"; //如果连接成功将loaded赋值给connectStatus
}
catch
{
}
}
}

浙公网安备 33010602011771号