Unity for IOS 将Texture2D图片上传到服务器
这里主要说的就是图片转存、转换时,上传到服务器很容易出错,导致上传失败。主要是为了让读者避免我走过的坑
错误情况:
有的转byte[] 会出现乱码,传到服务器会出现,从客户端中检测到有潜在危险的request.form值
转码出现错误,会出现500错误
-
内容
- 介绍使用WWWForm保存表单,然后使用WWW上传数据。 Authors
- 俩五一十
- 首先将Texture2D 转成byte[],下面的代码是如何转换成byte[]
private byte[] TextureToBytes(Texture2D imageSource)
{
RenderTexture renderTex = RenderTexture.GetTemporary(imageSource.width,imageSource.height, 0,RenderTextureFormat.Default,RenderTextureReadWrite.Linear);
Graphics.Blit(imageSource, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(imageSource.width, imageSource.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
byte[] bytes = readableText.EncodeToPNG();
return bytes;
}
- 将Texture2D转成Base64时,先用TextureToBytes方法将图片转成byte[]
public string ImageToBase64String(Texture2D tex)
{
// 先将图片转成byte[]
byte[] imgByte = DuplicateTexture(tex);
//然后
string base64String = Convert.ToBase64String(imgByte);
return base64String;
}
- 将Base64的图片信息存储到WWWForm中
public IEnumerator UploadFile3(Texture2D tex)
{
string fileName = "image.png";
string imageStr = ImageToBase64String(tex);
WWWForm form = new WWWForm();
// fileName为图片转为Base64的字符串
form.AddField("image", imageStr);
// fileName为图片名称
form.AddField("fileName", fileName);
// 这里的URL就是服务器接收图片信息的地址(我这里使用的是webservice)
WWW www = new WWW(url, form);
yield return www;
if (www.error != null)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.text);
}
}
- 服务器收到Base64图片信息后,再转成
public byte[] Base64ToImage(string imageStr)
{
string base64 = imageStr;
byte[] bytes = Convert.FromBase64String(base64);
return bytes;
}
- 然后就大功告成了。这里主要说的就是图片转存、转换时很容易出错。主要是为了让读者避免我走过的坑