Unity for IOS 将Texture2D图片上传到服务器

Unity for IOS 将Texture2D图片上传到服务器

这里主要说的就是图片转存、转换时,上传到服务器很容易出错,导致上传失败。主要是为了让读者避免我走过的坑

错误情况:
有的转byte[] 会出现乱码,传到服务器会出现,从客户端中检测到有潜在危险的request.form值
转码出现错误,会出现500错误

内容
介绍使用WWWForm保存表单,然后使用WWW上传数据。
Authors
俩五一十
  1. 首先将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;
    }
  1. 将Texture2D转成Base64时,先用TextureToBytes方法将图片转成byte[]
 public string ImageToBase64String(Texture2D tex)
    {
    	// 先将图片转成byte[]
        byte[] imgByte = DuplicateTexture(tex);
        //然后
        string base64String = Convert.ToBase64String(imgByte);
        return base64String;
    }
  1. 将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);
        }
    }
  1. 服务器收到Base64图片信息后,再转成
	public byte[] Base64ToImage(string imageStr)
    {
        string base64 = imageStr;
        byte[] bytes = Convert.FromBase64String(base64);
        return bytes;
    }
  1. 然后就大功告成了。这里主要说的就是图片转存、转换时很容易出错。主要是为了让读者避免我走过的坑
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值