- Home /
How to convert texture2D to image in C#
Hello, I am trying to use Aforge for Computer Vision with the unity webcam. I need to turn a texture2D into a C# image file, and I don't know how to do it. Based on some looking aroudn the net, I wrote the following functions. However, I am apparently missing a dll: gdiplus.dll , which I am starting to think doesn't exist on the OSX operating system. How else can I convert texture2D into an Image?
And I am surprised there isn't some code already available to do this.
# region texture2image
public static System.Drawing.Image Texture2Image(Texture2D texture)
{
if (texture == null)
{
return null;
}
//Save the texture to the stream.
byte[] bytes = texture.EncodeToPNG();
//Memory stream to store the bitmap data.
MemoryStream ms = new MemoryStream(bytes);
//Seek the beginning of the stream.
ms.Seek(0, SeekOrigin.Begin);
//Create an image from a stream.
System.Drawing.Image bmp2 = System.Drawing.Bitmap.FromStream(ms);
//Close the stream, we nolonger need it.
ms.Close();
ms = null;
return bmp2;
}
#endregion
# region image2texture
public static Texture2D Image2Texture(System.Drawing.Image im)
{
if (im == null)
{
return new Texture2D(4,4);
}
//Memory stream to store the bitmap data.
MemoryStream ms = new MemoryStream();
//Save to that memory stream.
im.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//Go to the beginning of the memory stream.
ms.Seek(0, SeekOrigin.Begin);
//make a new Texture2D
Texture2D tex = new Texture2D(im.Width, im.Height);
tex.LoadImage(ms.ToArray());
//Close the stream.
ms.Close();
ms = null;
//
return tex;
}
#endregion
Answer by Eric5h5 · Apr 22, 2012 at 09:33 AM
It's not a matter of OS X...you can't use System.Drawing, that's not in Mono. You don't need that anyway, just use File.WriteAllBytes for the PNG data. Look at the code example in the docs for EncodeToPNG.
Answer by Soldeplata · Mar 25, 2016 at 05:50 PM
Hi, I will answer to this question:
"How to convert texture2D to image in Unity using C#"
Image pictureInScene;
byte[] temp= File.ReadAllBytes ("pathTo/image.png");
Texture2D tempPic= new Texture2D (2, 2);
fotillo.LoadImage (temp);
pictureInScene.sprite = Sprite.Create (tempPic, new Rect (0, 0, 128, 128), new Vector2 ());//set the Rect with position and dimensions as you need
Don't forget to use texture.Apply() if you modify the pixels of the Texture2D
Answer by Bunny83 · Apr 22, 2012 at 11:26 AM
A quick search on google and the AForge forums gives me this:
From the first link it seems it's possible to use "some" parts of the framework, but you have to compile them yourself for mono.
Your answer
Follow this Question
Related Questions
Making Images Fade In and Out 5 Answers
How do I iterate over a large Texture2d quickly? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers