Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Last active April 21, 2020 11:02
Show Gist options
  • Select an option

  • Save openroomxyz/2cac97fed69359408d3aae1b6728eb8c to your computer and use it in GitHub Desktop.

Select an option

Save openroomxyz/2cac97fed69359408d3aae1b6728eb8c to your computer and use it in GitHub Desktop.
Uniy : How to compute pixel level Max on two PNG Images or on Two Texture2D of same size and generate resulting Texture2D or .png image?
class ImageFilePixelLevelOperation_Max
{
//Public functions
public static bool compute(string path_a, string path_b, string path_out)
{
if(!System.IO.File.Exists(path_a)) { return false; }
if(!System.IO.File.Exists(path_b)) { return false; }
Texture2D tex1 = ImageFilePixelLevelOperation_Max.LoadPNG(path_a);
Texture2D tex2 = ImageFilePixelLevelOperation_Max.LoadPNG(path_b);
Texture2D result;
if (ImageFilePixelLevelOperation_Max.compute(in tex1, in tex2, out result))
{
ImageFilePixelLevelOperation_Max.Save_Texture2D(result, path_out);
return true;
}
return false;
}
public static bool compute(in Texture2D tex1, in Texture2D tex2, out Texture2D result)
{
if (ImageFilePixelLevelOperation_Max.Combine(in tex1, in tex2, out result, ImageFilePixelLevelOperation_Max.MaxColor))
{
return true;
}
return false;
}
//Private functions
private static Texture2D LoadPNG(string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (System.IO.File.Exists(filePath))
{
fileData = System.IO.File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
return tex;
}
private static void Save_Texture2D(in Texture2D tex, string path)
{
byte[] bytes = tex.EncodeToPNG();
System.IO.File.WriteAllBytes(path, bytes);
}
private static bool Combine(in Texture2D tex1, in Texture2D tex2, out Texture2D result, System.Func<Color, Color, Color> f)
{
if (Texture2d_isSameSize(in tex1, in tex2))
{
Color[] colors_1 = tex1.GetPixels();
Color[] colors_2 = tex2.GetPixels();
Color[] colors_result = new Color[colors_1.Length];
result = new Texture2D(tex1.width, tex1.height);
for (int i = 0; i < colors_result.Length; i++)
{
colors_result[i] = f(colors_1[i], colors_2[i]);
}
result.SetPixels(colors_result);
result.Apply();
return true;
}
result = null;
return false;
}
private static bool Texture2d_isSameSize(in Texture2D a, in Texture2D b) { return ((a.width == b.width) && (a.height == b.height)); }
private static Color MaxColor(Color a, Color b) { return new Color(Mathf.Max(a.r, b.r), Mathf.Max(a.g, b.g), Mathf.Max(a.b, b.b), Mathf.Max(a.a, b.a)); }
}
if(ImageFilePixelLevelOperation_Max.compute(@"C:\Users\x\Desktop\x\0.png", @"C:\Users\x\Desktop\x\99.png", @"C:\Users\x\Desktop\x\out.png"))
{
Debug.Log("sucess");
}
else
{
Debug.Log("Something was wrong!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment