This class was created to find a way to write/read PBM Image format.
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.Serialization.Formatters.Binary;
namespace Chico
{
[Serializable]
public sealed class CPBM
{
private bool[,] pixels;
public static readonly CPBM Null = new CPBM(0, 0);
private CPBM(int width, int height)
{
if (width <= 0 || height <= 0)
return;
this.pixels = new bool[width, height];
}
public static CPBM Load(Stream stream)
{
BinaryFormatter decompressionFormatter = new BinaryFormatter();
byte[] compressedBytes = null;
using (MemoryStream compressionReader = new MemoryStream())
{
stream.CopyTo(compressionReader);
compressedBytes = compressionReader.ToArray();
}
Array.Reverse(compressedBytes);
using (MemoryStream decompressionStream = new MemoryStream(compressedBytes.Decompress()))
return (CPBM)decompressionFormatter.Deserialize(decompressionStream);
}
public void Save(Stream stream)
{
byte[] cpbmData = null;
using (MemoryStream cpbmWriter = new MemoryStream())
{
BinaryFormatter cpbmFormatter = new BinaryFormatter();
cpbmFormatter.Serialize(cpbmWriter, this);
cpbmData = cpbmWriter.ToArray();
}
byte[] compressedCpbm = cpbmData.Compress();
Array.Reverse(compressedCpbm);
stream.Write(compressedCpbm, 0, compressedCpbm.Length);
}
public int Level { get; set; }
public int Width => this.pixels.GetLength(0);
public int Height => this.pixels.GetLength(1);
public bool GetPixel(int x, int y) => this.pixels[x, y];
public void SetPixel(int x, int y, bool value) => this.pixels[x, y] = value;
private Color GetColor(int x, int y) => this.pixels[x, y] ? Color.White : Color.Black;
public void FromBitmap(Bitmap bitmap, bool useColorCorrectionProfile = false)
{
if (bitmap == null)
return;
this.pixels = new bool[bitmap.Width, bitmap.Height];
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Color c = bitmap.GetPixel(x, y);
bool adjust = (c.R + c.G + c.B) >= Level;
if (!useColorCorrectionProfile)
this.SetPixel(x, y, !adjust);
else
this.SetPixel(x, y, adjust);
}
}
}
public void ToBitmap(string path)
{
try
{
this.ToBitmap().Save(path);
}
catch
{
return;
}
}
public static explicit operator Bitmap(CPBM cPBM) => cPBM?.ToBitmap();
private Bitmap ToBitmap()
{
Bitmap bitmap = new Bitmap(Width, Height);
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
bitmap.SetPixel(x, y, this.GetColor(x, y));
}
}
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Gif);
ms.Seek(0, SeekOrigin.Begin);
return (Bitmap)Image.FromStream(ms);
}
}
}
}