RawImage.texture to Texture2D

Th title is the summary. I wan’t to know if it’s possible to convert the RawImage output texture to Texture2D? If so, then how?

What are you trying to achieve? To take the Texture, out of the Raw Image component and to place it/use it as a Texutre2D?

Its pretty easy actually:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Switch_Image : MonoBehaviour {
	public RawImage Test;
	public Texture2D TheTexture;
	void Start () {
		TheTexture = Test.texture as Texture2D;
	}

You can always try to use as Something in this case as Texture2D that will try to convert it. In this case it works.

Unity 2018+

public static class TextureExtentions
     {
         public static Texture2D ToTexture2D(this Texture texture)
         {
             return Texture2D.CreateExternalTexture(
                 texture.width,
                 texture.height,
                 TextureFormat.RGB24,
                 false, false,
                 texture.GetNativeTexturePtr());
         }
     }

Usage:

Texture2D texture2D = your_texture.ToTexture2D();

You can print the type of your RawImage.texture. Maybe the type is rendertexture. You may need more steps to convert to Texture2d.

Uploading Raw image (UI) to server;

public RawImage profileImage;
private Texture2D textureImg;

public void UploadImage()
{
    StartCoroutine(Upload());

}

IEnumerator Upload()
{
    textureImg = profileImage.texture as Texture2D;

    WWWForm form = new WWWForm();
  
    byte[] imgByte = textureImg.EncodeToPNG();

    Debug.Log(profileImage);
    form.AddBinaryData("myimage", imgByte, "imageFromUnity.png", "image/png");

    UnityWebRequest www = UnityWebRequest.Post("url", form);
    www.chunkedTransfer = false;
    yield return www.SendWebRequest();
    Debug.Log(www.downloadHandler.text);

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log("Form upload complete! " + www.downloadHandler.text);

    }
}