11
2014
Image To Grayscale Script
Quick test trying to convert this Basic256 script into Unity c# (trying to keep it close to original code..)
maybe still some problems as the output seems darker than the example..
http://rosettacode.org/wiki/Grayscale_image#BASIC256
Source C# (Image2Grayscale.cs)
// Original source: http://rosettacode.org/wiki/Grayscale_image#BASIC256
using UnityEngine;
using System.Collections;
public class Image2Grayscale : MonoBehaviour
{
string fileName = "BASIC256_greyscale_Mona_Lisa";
Texture2D graph;
void Start ()
{
LoadImage();
ConvertToGrayscale();
}
void LoadImage()
{
graph = Resources.Load(fileName, typeof(Texture2D)) as Texture2D;
}
void ConvertToGrayscale()
{
Color32[] pixels = graph.GetPixels32();
for (int x=0;x<graph.width;x++)
{
for (int y=0;y<graph.height;y++)
{
Color32 pixel = pixels[x+y*graph.width];
int p = ( (256 * 256 + pixel.r) * 256 + pixel.b) * 256 + pixel.g;
int b = p % 256;
p = Mathf.FloorToInt(p / 256);
int g = p % 256;
p = Mathf.FloorToInt (p / 256);
int r = p % 256;
float l = (0.2126f*r/255f) + 0.7152f*(g/255f) + 0.0722f*(b/255f);
Color c = new Color(l,l,l,1);
graph.SetPixel(x,y,c);
}
}
graph.Apply(false);
var bytes = graph.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "ImageSaveTest.png", bytes);
}
}
Related Posts
Leave a comment
Recent posts
- LudumDare59 : Signal
- Unity Editor: Tree Generator
- Leaf/Foliage Generator Tools (Runs in Browser)
- Testing Unity AI Beta
- Ways to Support UnityCoder Development
- Using UI Slider to Create 5-Star Rating Element
- Game Music Library For Unity (editor plugin)
- Fontastic : Easily Test Fonts in Unity Editor!
- GeoTiff Importer & Terrain Generator for Unity
- Create Baked DropShadow for UI images
- .JP2 Ortho Image Converter to PNG/JPG/TIFF
- Convert LAS/LAZ/PLY pointclouds to GLTF (GLB) Point Meshes (standalone converter)
Recent Comments
- on Sprite Sheet Flip Book Shader
- on Sprite Sheet Flip Book Shader
- on [Asset Store] PolygonCollider2D Optimizer
- on Trajectory Test Scene 2.0
- on Vector3 maths for dummies!
- on UnityHub 3.6.0: Remove Version Control & Cloud Dashboard columns
- on Using RenderDoc with Unity (graphics debugger)
- on UI Scroll View automatic Content height
Coin:
CUgDSbRqFcAumDSAcdKDvuXsw26VdkJe8C8WGUQHBAGS
An article by











