【问题标题】:How can I manually read a PNG image file and manipulate pixels in C#?如何手动读取 PNG 图像文件并在 C# 中操作像素?
【发布时间】:2016-06-18 21:35:48
【问题描述】:

.NET 已经提供了很多类和函数来处理包括 PNG 在内的图像。喜欢Image, Bitmap, etc. classes。假设,我不想使用这些类。

如果我想手动读取/写入 PNG 图像作为二进制文件来处理像素,那么我该怎么做?

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

如何获取单个像素来操作它们?

【问题讨论】:

标签: .net image bitmap png c#-2.0


【解决方案1】:

最简单的方法是使用ReadAllBytesWriteAllBytes函数:

byte[] imageBytes = File.ReadAllBytes("D:\\yourImagePath.jpg");    // Read
File.WriteAllBytes("D:\\yourImagePath.jpg", imageBytes);           // Write

【讨论】:

    【解决方案2】:

    将图像转换为字节[]数组:

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

    将 byte[] 数组转换为 Image:

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

    如果您想使用 Pixels,请按以下方法:

     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);
                        }
                    }  
    

    【讨论】:

    • 否 @AtmaneELBOUACHRI,如果您想使用像素,最好的选择是转换为位图,而不是图像,这与询问者的旧意图相同。
    • 不确定如何回答这个问题。我已经说过我不想使用ImageBitmap 类。
    猜你喜欢
    • 2015-09-13
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 2014-07-06
    • 2010-09-16
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多