Skip to content

Instantly share code, notes, and snippets.

@bradmartin333
Created March 28, 2022 20:10
Show Gist options
  • Save bradmartin333/cc044f0eb5dddca2eb5efbe884dacb4f to your computer and use it in GitHub Desktop.
Save bradmartin333/cc044f0eb5dddca2eb5efbe884dacb4f to your computer and use it in GitHub Desktop.
Encode an image as a single line string
static double _Scale = 0.03;
static void Main(string[] args)
{
byte[] r1 = Zip(EncodeBitmap(new Bitmap(@"C:\Users\brad.martin\Desktop\highMag.jpg")));
Bitmap bmp = DecodeBitmap(Unzip(r1));
bmp.Save(@"C:\Users\brad.martin\Desktop\test.png");
Console.WriteLine(Convert.ToBase64String(r1));
Console.ReadKey();
}
static string EncodeBitmap(Bitmap bmp)
{
bmp = new Bitmap(bmp, new Size((int)(bmp.Width * _Scale), (int)(bmp.Height * _Scale)));
StringBuilder sb = new StringBuilder();
for (int j = 0; j < bmp.Height; j++)
{
for (int i = 0; i < bmp.Width; i++)
sb.Append((char)Map(bmp.GetPixel(i, j).R));
sb.Append('~');
}
return sb.ToString();
}
static Bitmap DecodeBitmap(string data)
{
string[] lines = data.Split('~');
Bitmap bmp = new Bitmap(lines[0].Length - 1, lines.Length - 1);
for (int j = 0; j < bmp.Height; j++)
for (int i = 0; i < bmp.Width; i++)
{
int val = Map(lines[j][i] - '0', inv: true);
if (val < 0) val = 0;
bmp.SetPixel(i, j, Color.FromArgb(255, val, val, val));
}
return bmp;
}
static int Map(double value, double fromLow = 0, double fromHigh = 255, double toLow = 0, double toHigh = 125, bool inv = false)
{
if (inv)
{
fromHigh = toHigh;
toHigh = 255;
}
return (int)((value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow);
}
public static void CopyTo(Stream src, Stream dest)
{
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
dest.Write(bytes, 0, cnt);
}
public static byte[] Zip(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
CopyTo(msi, gs);
return mso.ToArray();
}
}
public static string Unzip(byte[] bytes)
{
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
CopyTo(gs, mso);
return Encoding.UTF8.GetString(mso.ToArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment