2010-06-20 6 views
2

J'essaye de créer par programme un bitmap à partir d'un tableau qui contient des données de couleur. Avec le code ci-dessous, je reçois trois images déformées en double côte à côte lorsqu'elles sont affichées dans une image. Quelqu'un peut-il me dire où ça ne va pas?Comment créer par programme un bitmap 24bpp à partir d'une matrice de couleurs?

public Bitmap CreateBM(int[,] imgdat) 
    { 
     Bitmap bitm = new Bitmap(imgdat.GetUpperBound(1) + 1, imgdat.GetUpperBound(0) + 1, PixelFormat.Format24bppRgb); 
     BitmapData bitmapdat = bitm.LockBits(new Rectangle(0, 0, bitm.Width, bitm.Height), ImageLockMode.ReadWrite, bitm.PixelFormat); 
     int stride = bitmapdat.Stride; 

     byte[] bytes = new byte[stride * bitm.Height]; 
     for (int r = 0; r < bitm.Height; r++) 
     { 
      for (int c = 0; c < bitm.Width; c++) 
      { 
       Color color = Color.FromArgb(imgdat[r, c]); 
       bytes[(r * bitm.Width) + c * 3] = color.B; 
       bytes[(r * bitm.Width) + c * 3 + 1] = color.G; 
       bytes[(r * bitm.Width) + c * 3 + 2] = color.R; 
      } 
     } 


     System.IntPtr scan0 = bitmapdat.Scan0; 
     Marshal.Copy(bytes, 0, scan0, stride * bitm.Height); 
     bitm.UnlockBits(bitmapdat); 

     return bitm; 
    } 
} 

Répondre

5

Vous voulez augmenter l'indice par stride chaque ligne au lieu de simplement par bitm.Width.

bytes[(r * stride) + c * 3] = color.B; 
bytes[(r * stride) + c * 3 + 1] = color.G; 
bytes[(r * stride) + c * 3 + 2] = color.R; 
+0

Merci! C'est ce qu'il a fait. –

Questions connexes