Unity for IOS uploads Texture2D images to the server
The main point here is that when images are dumped and converted, it is easy to make mistakes when uploading to the server, resulting in upload failure. Mainly to let readers avoid the pit I walked through
Error situation:
Some garbled characters will appear when converting to byte[], and it will appear when it is transmitted to the server. A potentially dangerous request.form value is detected from the client.
An error occurs in transcoding, and a 500 error will appear.
-
content
- Introduced to use WWWForm to save the form, and then use WWW to upload data. Authors
- two fifty
- First convert Texture2D to byte[], the following code is how to convert to 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;
}
- When converting Texture2D to Base64, first use the TextureToBytes method to convert the image into byte[]
public string ImageToBase64String(Texture2D tex)
{
// 先将图片转成byte[]
byte[] imgByte = DuplicateTexture(tex);
//然后
string base64String = Convert.ToBase64String(imgByte);
return base64String;
}
- Store the image information of Base64 in 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);
}
}
- After the server receives the Base64 image information, it converts it into
public byte[] Base64ToImage(string imageStr)
{
string base64 = imageStr;
byte[] bytes = Convert.FromBase64String(base64);
return bytes;
}
- And then you're done. The main point here is that it is easy to make mistakes when transferring and converting pictures. Mainly to let readers avoid the pit I walked through