#unity 传输图片到本地服务器并生成二维码
电脑安装IIS: link.
在IE地址里输入localhost,能打开,就代表已经安装.
ZXing.dll下载(放入unity): link.
服务器端要开启管理员 权限link
##服务器端:(右键->添加->引用->程序集->System.Drawing)
###接收并保存图片:
using System;
using System.Net.Sockets;
using System.Net;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Security.AccessControl;
namespace TCP服务器端
{
class Program
{
static void Main(string[] args)
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string ImgPath = @"C:/inetpub/wwwroot";
IPAddress ipAddress = IPAddress.Parse("xxx.xx.xx.xx");//电脑ip
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1234); //1234为端口号
serverSocket.Bind(ipEndPoint);//绑定ip和端口号
serverSocket.Listen(0); //最多监听客户端个数(排队的队列数) (0为不限制) 开始监听端口号
Socket clientSocket = serverSocket.Accept();//接收一个客户端连接
//向客户端发送一条消息
string msg = "Hello Client!";
byte[] data= System.Text.Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
//接收客户端的一张图片
byte[] databuffer = new byte[1000000]; //传输图片时记得查看byte长度(一般较大)
int count = clientSocket.Receive(databuffer);//前面有数据的位数
//如何确定该数组大小
MemoryStream fs = new MemoryStream(100);
string str = System.Text.Encoding.Default.GetString(databuffer);
fs.Write(databuffer, 0, count);
fs.Flush();
Bitmap Img = new Bitmap(fs);
AddSecurityControll2File(ImgPath, Img, clientSocket);
//关闭写文件流
fs.Close();
//关闭接收数据的Socket
//clientSocket.Shutdown(SocketShutdown.Receive);
Console.ReadKey();//暂停程序,观察输出
clientSocket.Close(); //关闭与客户端连接
serverSocket .Close();//关闭服务器
}
/// <summary>
/// 为文件添加users,everyone用户组的完全控制权限
/// </summary>
/// <param name="filePath"></param>
public static void AddSecurityControll2File(string filePath, Bitmap Img, Socket socket)
{
//获取文件夹信息
DirectoryInfo dir = new DirectoryInfo(filePath);
//获得该文件夹的所有访问权限
System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
//设定文件ACL继承
InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
//添加ereryone用户组的访问权限规则 完全控制权限
FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
//添加Users用户组的访问权限规则 完全控制权限
FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
bool isModified = false;
dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
//设置访问权限
dir.SetAccessControl(dirSecurity);
Img.Save(filePath + "/BG.jpeg", ImageFormat.Jpeg);
socket.Send(System.Text.Encoding.UTF8.GetBytes("SaveFinish"));
Console.Write("保存图片BG.jpg成功!!!");
}
}
}
##客户端:
###【1】传输图片:
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System;
using System.Threading;
using System.Text;
public class Client : MonoBehaviour
{
public static IPAddress ipAddress;//服务器地址
IPEndPoint ipEndPoint; //端口号
private string ip="";
private Thread receiveThread;//接收服务器消息线程
private Socket localClient;
private byte[] byt = new byte[1024];
public CreatQR CreatQr;
private bool isFinish = false;
//访问网址
private string url="";
void Start()
{
ip = GetIPAddress();
ipAddress =IPAddress.Parse(ip);
url = "http://"+ ip+"/SendImage/DrawImage.html";
ipEndPoint = new IPEndPoint(ipAddress, 1234);
//连接至服务端
InitClientSocket();
}
void Update()
{
if (isFinish)
{
CreatQr.Start_CreatQr(url);
isFinish = false;
}
}
/// <summary>
/// 获取本机ip(用于本机做服务器时)
/// </summary>
public string GetIPAddress()
{
string IP = Network.player.ipAddress;
if (IP == null || IP == "")
{
try
{
string hostName = System.Net.Dns.GetHostName();
if (hostName != null)
{
System.Net.IPAddress[] ips = System.Net.Dns.GetHostAddresses(hostName);
if (ips.Length > 0)
{
IP = ips[0].ToString();
}
}
else
{
IP = "";
}
}
catch (Exception e)
{
IP = "";
}
}
return IP;
}
/// <summary>
/// 销毁时操作
/// </summary>
private void OnDestroy()
{
if (localClient != null)
localClient.Close();
if (receiveThread != null)
receiveThread.Abort();
}
/// <summary>
/// 客户端实例化Socket连接
/// </summary>
private void InitClientSocket()
{
localClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
//当前客户端连接的服务器地址与远程端口
localClient.Connect(ipEndPoint);
//开始接收服务器消息子线程
receiveThread = new Thread(Receive);
receiveThread.Start();
Debug.Log("客户端-->服务端完成,开启接收消息线程");
}
catch (Exception ex)
{
Debug.Log("客户端连接服务器异常: " + ex.Message);
}
}
//发送图片
public void SendMegEvent()
{
SendPhotoMessage("Assets/Textures/BG.jpg"); //unity内图片路径
}
private void SendPhotoMessage(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read);
BinaryReader stread = new BinaryReader(fs);
byte[] byt = new byte[fs.Length];
stread.Read(byt, 0, byt.Length - 1);
Debug.Log("数据长度为:" + byt.Length);
localClient.Send(byt);
fs.Close();
}
/// <summary>
/// 接收信息处理
/// </summary>
/// <param name="socketer"></param>
private void Receive()
{
Socket socket = localClient;
try
{
StringBuilder temp = new StringBuilder();
while (true)
{
int length = socket.Receive(byt);
temp.Append(Encoding.UTF8.GetString(byt, 0, length));
if (temp.ToString().Length > 0)
{
Debug.Log(temp.ToString());
if (temp.ToString() == "SaveFinish")
{
Debug.Log("传输完成");
isFinish = true;
localClient.Shutdown(System.Net.Sockets.SocketShutdown.Send);
localClient.Close();
}
temp.Remove(0, temp.ToString().Length);
}
}
}
catch (Exception e)
{
Debug.LogError("接收服务端消息的时候抛错:"+ e);
}
}
}
###【2】生成二维码:
using UnityEngine;
using UnityEngine.UI;
using ZXing;
using ZXing.QrCode;
public class CreatQR : MonoBehaviour {
//在屏幕上显示二维码
public RawImage image;
//存放二维码
Texture2D encoded;
//int Nmuber = 0;
// Use this for initialization
void Start()
{
encoded = new Texture2D(256, 256);
}
/// <summary>
/// 定义方法生成二维码
/// </summary>
/// <param name="textForEncoding">需要生产二维码的字符串</param>
/// <param name="width">宽</param>
/// <param name="height">高</param>
/// <returns></returns>
private static Color32[] Encode(string textForEncoding, int width, int height)
{
var writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width
}
};
return writer.Write(textForEncoding);
}
/// <summary>
/// 生成二维码
/// </summary>
public void Start_CreatQr(string url)
{
if (url.Length > 1)
{
//二维码写入图片
var color32 = Encode(url, 256, 256);
encoded.SetPixels32(color32);
encoded.Apply();
//生成的二维码图片附给RawImage
image.texture = encoded;
}
else
{
Debug.LogError("没有生成信息");
}
}
}
##网页(用显示照片方便生成二维码)
(保存为.html,放在C:\inetpub\wwwroot里面)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>你的照片</title>
</head>
<body>
<img src="BG.jpeg"alt="Photo" width="1080" height="1920">
</body>
</html>
##开启服务器,运行unity点击按钮运行查看效果。
ps:最近一直在想办法把传输的图片生成二维码,搜索的思路就是把图片放在网页里,用链接生成二维码。一个不成熟的小例子,小白第一次写博客,仅供参考。关于生成随机网址的网页,欢迎大佬们分享更好的想法。