I am trying to load a texture(and create a sprite from it eventually) from disk but sprite renders as low resolution image.
What I am doing:
-> Download the image from url. Once the image is downloaded, I save the texture as png to disk so that next time it doesn't requires a download.
WWW www = new WWW(url);
yield return www;
if (www.isDone)
{
if (string.IsNullOrEmpty(www.error))
{
Sprite img = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
reward.RewardSprite = img;
byte[] bytes = www.texture.EncodeToPNG();
FileManager.SaveRewardImage(reward.rewardId, bytes);
}
else
{
Debug.Log(www.error);
}
}
-> Load from disk
string path = string.Format("Cache\\Venue\\{0}", nameWithoutExtension);
return Resources.Load<Texture2D>(path);
The first time when the texture loads from url, its resolution seems fine(because its the original one). When it loads from cache, it attenuates to a lower one.
Can someone tell me what am I missing, or even if there is way around it?
Thanks in advance.
You can overload your texture in your sprite creation in the same way that you do with the rectangle and specify in TextureFormat the format you need:
Sprite img = Sprite.Create(
new Texture2D (www.texture.width, www.texture.height, TextureFormat format, bool mipmap),
new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0, 0));
Related
When I used 5.01KB of texture 'Texture2D.LoadTexture()' I expected about 8KB.
but this memory alloc is 2.8MB
why texture alloc memory is more size?
Sample Code
private Texture2D[] m_SaveTextures = null;
public void Start()
{
string path = "../Directory/";
m_SaveTextures = new Texture2D[]
{
GetTexture(path + "Red.png"),
GetTexture(path + "Green.png"),
GetTexture(path + "Blue.png"),
GetTexture(path + "Black.png")
};
}
private Texture2D GetTexture(string path)
{
if (!File.Exists(path)) return null;
var texture = new Texture2D(1, 1, TextureFormat.ARGB32, false)
{
name = Path.GetFileNameWithoutExtension(path)
};
texture.LoadImage(File.ReadAllBytes(path));
return texture;
}
Example image..
Unity Profiler check image
Because png is a compressed image file, but the texture you are loading it into is not. TextureFormat.ARGB32 is not a compressed format, so the memory cost is 32 bits per pixel.
You can lower the memory footprint by using one of the compressed formats, like DXT5, if your target platform supports it.
I have been trying to change the format from a camera that give a texture in Alpha8 to RGBA and have been unsuccessful so far.
This is the code I've tried:
public static class TextureHelperClass
{
public static Texture2D ChangeFormat(this Texture2D oldTexture, TextureFormat newFormat)
{
//Create new empty Texture
Texture2D newTex = new Texture2D(2, 2, newFormat, false);
//Copy old texture pixels into new one
newTex.SetPixels(oldTexture.GetPixels());
//Apply
newTex.Apply();
return newTex;
}
}
And I'm calling the code like this:
Texture imgTexture = Aplpha8Texture.ChangeFormat(TextureFormat.RGBA32);
But the image gets corrupted and isn't visible.
Does anyone know how to change this Alpha8 to RGBA so I can process it like any other image in OpenCV?
A friend provided me with the answer:
Color[] cs =oldTexture.GetPixels();
for(int i = 0; i < cs.Length; i++){//we want to set the r g b values to a
cs[i].r = cs[i].a;
cs[i].g = cs[i].a;
cs[i].b = cs[i].a;
cs[i].a = 1.0f;
}
//set the pixels in the new texture
newTex.SetPixels(cs);
//Apply
newTex.Apply();
This will take alot of resources but it will work for sure.
If you know a better way to make this change please add an answer to this thread.
I'm using Unity and using an Image object to display an image by loading its bytes (coming from a JSON request) in a Texture2D object, but the resulting image is blurry and pixelated, in a very low quality. This is the code:
Texture2D myTexture = new Texture2D(2, 2, TextureFormat.ARGB32, false);
myTexture.filterMode = FilterMode.Point;
myTexture.LoadImage(Bytes);
myImage.GetComponent<RawImage>().texture = myTexture;
And the output looks like this:
Any idea on how to improve the quality on this? There should be a way to make it look better, if I import an asset into Unity (image) and set it with filter mode Point, it actually looks pretty good, but in this case, it just makes it worse. The original image is pretty detailed:
Try with image exact width and hight in
Texture2D myTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);
or
Texture2D myTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
In one application (Server), I am capturing the display:
public byte[] GetFrame()
{
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
byte[] bytes = tex.GetRawTextureData();
Destroy(tex);
return bytes;
}
I send this frame over the network to another application (Client), which loads the received frame and puts it as texture on a plane or whatever (some other 3D primitive):
void DisplayFrame(byte[] frame)
{
Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
texture.LoadRawTextureData(frame);
texture.Apply();
GetComponent<Renderer>().material.mainTexture = texture;
ScreenUpdate = true;
Destroy(texture);
}
This works and the image is displayed as I expected. However, when watching the RAM, I notice that the Client RAM goes nuts... over 8GB.
The interesting thing is that if I set frame = null; after calling Destroy(texture); in DisplayFrame on the Client, the user only sees a black screen.
I don't understand what is happening here... It's as if the frame is staying in memory and each new received frame just increases the memory used.
Does anyone have any ideas?
It turns out that if I move the Destroy(texture); from the bottom of DisplayFrame(byte[] frame) to the top of the function, the memory leak is resolved.
It's as if Destroy is being blocked because the texture is still being applied to the material when the next iteration comes around. I'm not clear on the issue here, so if someone with more knowledge could chip in, that would be great.
Surprisingly in Unity, for years the only way to simply scale an actual PNG is to use the very awesome library http://wiki.unity3d.com/index.php/TextureScale
Example below
How do you scale a PNG using Unity5 functions? There must be a way now with new UI and so on.
So, scaling actual pixels (such as in Color[]) or literally a PNG file, perhaps downloaded from the net.
(BTW if you're new to Unity, the Resize call is unrelated. It merely changes the size of an array.)
public WebCamTexture wct;
public void UseFamousLibraryToScale()
{
// take the photo. scale down to 256
// also crop to a central-square
WebCamTexture wct;
int oldW = wct.width; // NOTE example code assumes wider than high
int oldH = wct.height;
Texture2D photo = new Texture2D(oldW, oldH,
TextureFormat.ARGB32, false);
//consider WaitForEndOfFrame() before GetPixels
photo.SetPixels( 0,0,oldW,oldH, wct.GetPixels() );
photo.Apply();
int newH = 256;
int newW = Mathf.FloorToInt(
((float)newH/(float)oldH) * oldW );
// use a famous Unity library to scale
TextureScale.Bilinear(photo, newW,newH);
// crop to central square 256.256
int startAcross = (newW - 256)/2;
Color[] pix = photo.GetPixels(startAcross,0, 256,256);
photo = new Texture2D(256,256, TextureFormat.ARGB32, false);
photo.SetPixels(pix);
photo.Apply();
demoImage.texture = photo;
// consider WriteAllBytes(
// Application.persistentDataPath+"p.png",
// photo.EncodeToPNG()); etc
}
Just BTW it occurs to me I'm probably only talking about scaling down here (as you often have to do to post an image, create something on the fly or whatever.) I guess, there would not often be a need to scale up in size an image; it's pointless quality-wise.
If you're okay with stretch-scaling, actually there's simpler way by using a temporary RenderTexture and Graphics.Blit. If you need it to be Texture2D, swapping RenderTexture.active temporarily and read its pixels to Texture2D should do the trick. For example:
public Texture2D ScaleTexture(Texture src, int width, int height){
RenderTexture rt = RenderTexture.GetTemporary(width, height);
Graphics.Blit(src, rt);
RenderTexture currentActiveRT = RenderTexture.active;
RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width,rt.height);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
tex.Apply();
RenderTexture.ReleaseTemporary(rt);
RenderTexture.active = currentActiveRT;
return tex;
}