Is there a way to import a texture in a specific format? - unity3d

I'm trying to load a rendered image from Blender into Unity. But I saved the image with a color depth of 16 bits per channel, and now I want to have the same accuracy inside Unity. However, when I put the texture on a material and zoom in a bit, it looks like this:
As far as I can tell, this is only 8 bits per channel. What fixed it for me was overriding the format in the Texture Import Settings (from the default RGBA Compressed DXT5 to RGBA64, because my image also has an alpha channel):
And now the image looks nice again:
However, I would like to be able to import the image at runtime. So far I've been doing it like this:
Texture2D tex = new Texture2D(0, 0);
byte[] bytes = File.ReadAllBytes(path);
tex.LoadImage(bytes);
The problem is that, according to the documentation for Texture2D.LoadImage, "PNG files are loaded into ARGB32 format" by default. And even if I set the format when creating the Texture2D, it seems to get overitten when I call LoadImage ("After LoadImage, texture size and format might change").
Is there a way to import an image in a specific format (at runtime)? Thanks in advance

Subclass AssetPostprocessor:
public class MyPostProcessor : AssetPostprocessor {
public void OnPreprocessTexture() {
if (assetPath.Contains("SomeFileName")) {
TextureImporter textureImporter = (TextureImporter)assetImporter;
TextureImporterPlatformSettings settings = new TextureImporterPlatformSettings();
settings.textureCompression = TextureImporterCompression.Uncompressed;
settings.format = TextureImporterFormat.RGBA64;
textureImporter.SetPlatformTextureSettings(settings);
}
}
}

Related

Automatic texture importer not assigning alpha in Unity

I have written a custom texture importer, and put it in my Editor folder inside the Assets folder, which is supposed to apply my custom settings automatically when a new texture is imported to the project.
This is my code:
'''
public class TexturePostProcessor : AssetPostprocessor
{
void OnPostprocessTexture(Texture2D texture)
{
TextureImporter importer = assetImporter as TextureImporter;
importer.textureType = TextureImporterType.Default;
TextureImporterPlatformSettings settings = importer.GetPlatformTextureSettings("WebGL");
settings.overridden = true;
settings.name = "WebGL";
settings.maxTextureSize = 1024;
settings.format = TextureImporterFormat.DXT5Crunched;
settings.compressionQuality = 50;
settings.allowsAlphaSplitting = false;
importer.SetPlatformTextureSettings(settings);
}
}
'''
The issue i have is, when the texture is imported, it doesn't get the alpha channel, but if I manually right click and re-import the texture, then the alpha is applied. You can see that in below image:
Re-importing is not an option though because our textures will be coming in from external sources automatically, so it needs to have the correct alpha and format the first time.
Can someone point me in the right direction please?

How to change texture format from Alpha8 to RGBA in Unity3d?

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.

Alternative to AssetDatabase.LoadAssetAtPath for any path?

Currently I am using the following piece of code to load Textures from image files.
Texture my_pic = (Texture) AssetDatabase.LoadAssetAtPath(path, typeof(Texture));
Unfortunately this method doesn't work if the target path isn't in the Asset/ folder. I was wondering how I would load an image, given some absolute path of the form
/Users/Alan/SomeFolder/SomePic.png
(note that I am currently writing a custom Unity editor plugin by extending EditorWindow if that matters)
AssetDatabase is an Editor-only class.
Furthermore, it can only read assets in the /Assets directory (you know, the ones that are known to the asset database).
If you want to read any file on the file system, you need to use the System.IO classes.
Here is some code that will open a unity file dialog, and load the selected texture into a material of the attached object.
string path = EditorUtility.OpenFilePanel("Load an image", "", "png");
if (string.IsNullOrEmpty(path)) {
return;
}
// Load the images bytes from file (this is a synchronous call!)
byte[] bytes = null;
try {
bytes = System.IO.File.ReadAllBytes(path);
} catch (System.Exception e) {
Debug.LogError(e.Message);
return;
}
// Load the bytes into a Unity Texture2D
Texture2D _tex = new Texture2D(2,2);
_tex.LoadImage(bytes);
// Apply this texture to the object
Renderer r = (target as Component).gameObject.GetComponent<Renderer>();
if (r != null) {
r.material.SetTexture("_MainTex", _tex);
}
The last part, just for demonstration, will work only on a script derived from Editor because it uses target to find the attached renderer. It's up to you to decide what to do with the texture in your EditorWindow script.
Also, remember to explicitly call DestroyImmediate on your texture when you no longer need it, as you may end up with a memory leak in your editor code.
You can use UnityWebRequestTexture
var www = UnityWebRequestTexture.GetTexture("file:///Users/Alan/SomeFolder/SomePic.png");
www.SendWebRequest();
while(!www.isDone)
continue;
var texture = DownloadHandlerTexture.GetContent(www);

How to get the path and file size of some Unity built-in assets?

Background
I am developing a Unity editor plugin that enables users to send a selected image file to a REST API endpoint in the cloud for processing (e.g. adding transforms and optimizations). The plugin also shows a comparison of the selected image's details before and after processing (e.g. width/height/size before vs after).
The user selects the desired image through the following piece of code:
selected_texture = (Texture2D) EditorGUI.ObjectField(drawing_rect, selected_texture, typeof(Texture2D), false);
Once its selected, I can then get the respective file size by doing this:
file_size = new FileInfo(AssetDatabase.GetAssetPath(selected_texture)).Length;
Problem
This works for most textures selected, but I encounter an error when I choose a built-in Unity texture. Any guidance would be greatly appreciated.
FileNotFoundException: Could not find file 'Resources/unity_builtin_extra'
There are two built-in asset-librarys in Unity:
BuiltIn-Library in "Resources/unity_builtin_extra": contains UGUI sprite、Default-Material、Shader and so on.
BuiltIn-Library in "Library/unity default resources": contains built-in 3D mesh and OnGUI assets.
If you are using AssetDatabase.GetAssetPath, you will always get one or another path above.
To solve the problem, you need do something like below code:
public const string BuiltinResources = "Resources/unity_builtin_extra";
public const string BuiltinExtraResources = "Library/unity default resources";
public static bool IsBuiltInAsset(string assetPath)
{
return assetPath.Equals(BuiltinResources) || assetPath.Equals(BuiltinExtraResources);
}
public static long GetTextureFileLength(Texture texture)
{
string texturePath = AssetDatabase.GetAssetPath(texture);
if (IsBuiltInAsset(texturePath))
{
/*
* You can get all built-in assets by this way.
*
var allAssets = AssetDatabase.LoadAllAssetsAtPath(BuiltinResources);
var allExtraAssets = AssetDatabase.LoadAllAssetsAtPath(BuiltinExtraResources);
*/
// not supportted
// return -1;
// using MemorySize
return Profiler.GetRuntimeMemorySizeLong(texture);
}
else
{
return new FileInfo(texturePath).Length;
}
}

Unity 5.1 Distorted image after download from web

When I load my png after compressing with tiny png, they get distorted( all purple and transparent)
http://s22.postimg.org/b39g0bhn5/Screen_Shot_2015_06_28_at_10_39_50_AM.png
the background for example should be blue
http://postimg.org/image/fez234o6d/
this only happens when i use pictures that got compressed by tinypng.com
and only after i updated to unity 5.1.
Im downloading the image with WWW class and loading texture using Texture2D.
is this problem known to anyone?
I had exactly the same issue. I was able to solve it using the following code
mat.mainTexture = new Texture2D(32, 32, TextureFormat.DXT5, false);
Texture2D newTexture = new Texture2D(32, 32, TextureFormat.DXT5, false);
WWW stringWWW = new WWW(texture1URL);
yield return stringWWW;
if(stringWWW.error == null)
{
stringWWW.LoadImageIntoTexture(newTexture);
mat.mainTexture = newTexture;
}
The key seemed to be using DXT5 as the texture format, and using the method LoadImageIntoTexture(...);