简体   繁体   English

C#读取/写入像素颜色不起作用

[英]c# Read/Write pixel colors not working

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 我正在尝试创建一种简单的图像格式,该格式将每个像素的argb颜色写入文件,我使用此代码获取并设置了所有

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? 如何将图像像素的值作为RGB读取到2d数组中?

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, 但是从这个bmp文件中

I get this output: 我得到以下输出:

does someone knows how to fix this? 有人知道如何解决这个问题吗?

thanks in advance. 提前致谢。

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. 而是在最里面的循环中调用ReadLine

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. 您最好将它仅用作学习练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM