4

Hi i try to convert my Texture 2D in Image (and i cant use a Raw Image because the resolution dont match in phones) but the problem is that Image does not have the Texture element. how Convert UnityEngine.Texture2D in Image.Sprite.

//Image Profile
protected Texture2D pickedImage;
public Texture2D myTexture2D;
public RawImage getRawImageProfile;
public RawImage getRawImageArrayProfile;

public Image getRawImageProfile2;
public Image getRawImageArrayProfile2;

 public void PickImageFromGallery(int maxSize = 256)
{
    NativeGallery.GetImageFromGallery((path) => 
    {
        if( path != null )
        {
            byte[] imageBytes = File.ReadAllBytes(path);
            pickedImage = null;
            pickedImage = new Texture2D(2, 2);
            pickedImage.LoadImage(imageBytes);
            getRawImageProfile.texture = pickedImage;
            getRawImageArrayProfile.texture = pickedImage;

            getRawImageProfile2.sprite = pickedImage; //ERROR CONVERT SPRITE
            //getRawImageArrayProfile2.texture = pickedImage;
        }

    }, maxSize: maxSize);

    byte[] myBytes;
    myBytes = pickedImage.EncodeToPNG();
    enc = Convert.ToBase64String(myBytes);       
}
  • Does the [Sprite.Create](https://docs.unity3d.com/ScriptReference/Sprite.Create.html) function work for your purposes? Basing the idea off [a similar question](https://answers.unity.com/questions/650552/convert-a-texture2d-to-sprite.html) asked on the Unity forums. – Tim Hunter Jun 19 '19 at 23:38

1 Answers1

6

Sprite.Create does exactly what you're looking for.

From the Unity docs on Sprite.Create:

Sprite.Create creates a new Sprite which can be used in game applications. A texture needs to be loaded and assigned to Create in order to control how the new Sprite will look.

In code:

public Texture2D myTexture2D; // The texture you want to convert to a sprite
Sprite mySprite; // The sprite you're gonna save to
Image myImage; // The image on which the sprite is gonna be displayed

public void FooBar()
{
    mySprite = Sprite.Create(myTexture2D, new Rect(0.0f, 0.0f, myTexture2D.width, myTexture2D.height), new Vector2(0.5f, 0.5f), 100.0f);
    myImage.sprite = mySprite; // apply the new sprite to the image

}

In the above example we take the image data from myTexture2D, and create a new Rect that is of the same size as the original texture2D, with its pivot point in the center, using 100 pixels per unit. We then apply the newly made sprite to the image.

Community
  • 1
  • 1
Remy
  • 4,843
  • 5
  • 30
  • 60
  • 1
    @JorgeEduardoAguilarDiaz Please don't forget to accept the answer if it worked for you (the little check icon next to the answer). This will ensure people facing the same problem will be able to find the solution aswel :) – Remy Jun 20 '19 at 18:25