使用Unity3D在PC+Android端截图保存,再添加到数据库中

前提:

  1.使用的工具为Unity2021+VS2019+mysql8.0

  2.使用的支持包

         

 

 

     3.Unity组件

  

 

  代码  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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地址的数据库就可以

  如何使用云服务器部署mysql8.0-CSDN博客

  

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
           {
 
           }
       }
   }

  

 

posted @   打工仔-也想飞  阅读(362)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示