Reputation: 75
I am trying to create a simple image format, which writes for every pixel the argb color to a file, I used this code to get and set all
List<Color> pixels = new List<Color>();
Bitmap img = new Bitmap("*imagePath*");
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
Color pixel = img.GetPixel(i,j);
pixels.Add(pixel);
}
}
from:
How can I read image pixels' values as RGB into 2d array?
And then I write every pixel on a new line:
foreach(Color p in pixels)
{
streamWriter.WriteLine(p.ToArgb)
}
streamWriter.Close();
and then if I try to read it:
OpenFileDialog op = new OpenFileDialog();
op.ShowDialog();
StreamReader sr = new StreamReader(op.FileName);
int x = 1920;
int y = 1080;
Bitmap img = new Bitmap(x,y);
for (int i = 0; i < img.Width; i++)
{
string rl = sr.ReadLine();
for (int j = 0; j < img.Height; j++)
{
img.SetPixel(i, j, Color.FromArgb(Int32.Parse(rl)));
}
}
pictureBox1.Image = img;
but from this bmp file,
I get this output:
does someone knows how to fix this?
thanks in advance.
Upvotes: 0
Views: 782
Reputation: 21917
When you write the pixels, you are writing each one in a separate line. However, when reading, you are reading a single line per column, and then using that same color value for every row of the column.
instead, call ReadLine
inside the innermost loop.
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
string rl = sr.ReadLine();
img.SetPixel(i, j, Color.FromArgb(Int32.Parse(rl)));
}
}
Needless to add, this image format is incredibly inefficient in terms of space, and in it's current implementation also in read and write performance. You would be wise to use it only as a learning exercise.
Upvotes: 3