-3

There are already lots of classes and functions supplied with the .NET to manipulate Images including PNG. Like Image, Bitmap, etc. classes. Suppose, I don't want to use those classes.

If I want to manually read/write a PNG image as a binary file to work with pixels then how can I do that?

using(FileStream fr = new FileStream(fileName, FileMode.Open)) 
{
      using (BinaryReader br = new BinaryReader(fr))
      {
          imagesBytes= br.ReadBytes((int)fr.Length);
      }  
}

How can I get hold of individual pixels to manipulate them?

Community
  • 1
  • 1
user366312
  • 16,686
  • 58
  • 210
  • 423
  • 1
    It's all in the specifications. Look here for a start: http://stackoverflow.com/q/26456447/2564301 – Jongware Mar 05 '16 at 14:47

2 Answers2

1

The easiest way is use ReadAllBytes and WriteAllBytes function:

byte[] imageBytes = File.ReadAllBytes("D:\\yourImagePath.jpg");    // Read
File.WriteAllBytes("D:\\yourImagePath.jpg", imageBytes);           // Write
Thanh Nguyen
  • 7,634
  • 12
  • 54
  • 102
0

Convert Image to byte[] array:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}

Convert byte[] array to Image:

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

If you want to work with Pixels here's how :

 Bitmap bmp = (Bitmap)Image.FromFile(filename);
                Bitmap newBitmap = new Bitmap(bmp.Width, bmp.Height);

                for (int i = 0; i < bmp.Width; i++)
                {
                    for (int j = 0; j < bmp.Height; j++)
                    {
                        var pixel = bmp.GetPixel(i, j);

                        newBitmap.SetPixel(i, j, Color.Red);
                    }
                }  
  • 1
    No @AtmaneELBOUACHRI, if you want work with pixel, best choice is convert to Bitmap, not image, which is same with asker old intent. – Thanh Nguyen Mar 05 '16 at 13:05
  • Not sure how that answers the question. I already said that I don't want to use `Image` and `Bitmap` classes. – user366312 Mar 05 '16 at 16:33