2016-03-04 91 views
-2

.NET已经提供了许多用于处理图像(包括PNG)的类和函数。像Image, Bitmap, etc. classes。假设,我不想使用这些类。如何手动读取PNG图像文件并在C#中操作像素?

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

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

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

+1

这一切都在规范。看看这里开始:http://stackoverflow.com/q/26456447/2564301 – usr2564301

回答

0

转换图片为byte []数组:

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

如果你想在这里与像素的工作方式如下:

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

我怎样才能掌握个别像素来操纵它们? – anonymous

+1

否@AtmaneELBOUACHRI,如果你想使用像素,最好的选择是转换为位图,而不是图像,这与asker旧意图相同。 – Sakura

+0

corse @Sakura我同意。我将编辑我的答案 – Coding4Fun

1

最简单的方法是使用ReadAllBytesWriteAllBytes功能:

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