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);
Related
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 trying to download and save file, on android device. It's works fine on PC, but i have a visual bug at my android phone. Look at screen please
My code:
It's how i download and serialize it
Icon = Sprite.Create(texture2dd, new Rect(0.0f, 0.0f, texture2dd.width, texture2dd.height), new Vector2(0.5f, 0.5f), 100.0f);
byte[] texturebytes = Icon.texture.GetRawTextureData();
File.WriteAllText(Application.persistentDataPath + "/icon", Encoding.Default.GetString(texturebytes));
File.WriteAllText(Application.persistentDataPath + "/iconinfo", Icon.texture.width + "###" + Icon.texture.height);
And thi is how I try to load it later:
string[] info = File.ReadAllText(path + "info").Split(new string[] { "###" }, StringSplitOptions.None);
int width, height;
int.TryParse(info[0], out width);
int.TryParse(info[1], out height);
byte[] bytesIcon = Encoding.Default.GetBytes(File.ReadAllText(path));
Texture2D iconText = new Texture2D(width, height, TextureFormat.ARGB32, false);
iconText.LoadRawTextureData(bytesIcon);
iconText.Apply();
return Sprite.Create(iconText, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));
I think problem in Encoding type, but i tryed all Encoding types, and it's still don't work, and load some bug-texture.
Instead of using GetRawTextureData() and LoadRawTextureData you should save it actually as a .png or .jpg format! The "RawTextureData" is very huge compared to the pure .jpg or .png file data.
Instead use EncodeToPNG (or EncodeToJPG if the quality is not that important - than remember to also adopt the file ending) and LoadImage.
Additionally LoadImage actually "knows" the image size (because it is encoded into the png or jpg file) so there is no need for your iconinfo file at all!
Something like
// ...
Icon = Sprite.Create(texture2dd, new Rect(0.0f, 0.0f, texture2dd.width, texture2dd.height), Vector2.one * 0.5f, 100.0f);
byte[] texturebytes = Icon.texture.EncodeToPNG();
File.WriteAllText(Application.persistentDataPath + "/icon.png", Encoding.Default.GetString(texturebytes));
// ...
(Maybe also checkout this answer for other ways to write the file.)
and
// ...
byte[] bytesIcon = Encoding.Default.GetBytes(File.ReadAllText(path));
// as the example in the documentation states:
// Texture size does not matter, since
// LoadImage will replace it with incoming image size.
Texture2D iconText = new Texture2D(2, 2);
iconText.LoadImage(bytesIcon);
// Also from the documentation:
// Texture will be uploaded to the GPU automatically; there's no need to call Apply.
return Sprite.Create(iconText, new Rect(0, 0, iconText.width, iconText.height), Vector2.one * 0.5f);
And yes another issue might still be that you used Encoding.Default (see here) so maybe you should also use a fixed encoding like Encoding.UTF8.
Though for loading the file I would actually prefere to use a UnityWebRequest which can be also used for a file from the local filestorage!
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));
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;
}
Im trying to load an image that has background transparency that will be layered over another texture. When i try and load it, all i get is a white screen. The texture is 512 by 512, and its saved in photoshop as a 24 bit PNG (standard PNG specs in the Photoshop Save for Web and Devices config window). Any idea why its not showing? The texture without transparency shows without a problem. Here is my loadTextures method:
public void loadGLTexture(GL10 gl, Context context) {
//Get the texture from the Android resource directory
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.m1);
Bitmap normalScheduleLines = BitmapFactory.decodeResource(context.getResources(), R.drawable.m1n);
//Generate texture pointers...
gl.glGenTextures(3, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[1]);
//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
//Bind our normal schedule bus map lines
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, normalScheduleLines, 0);
normalScheduleLines.recycle();
}
It was actually the automatically generated mipmaps that was preventing the PNG from being displayed. I changed
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
to
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
and sure enough, it worked. Not sure why it doesn't like the PNG with alpha but when i do find out i will post here.