Convert a string to a bitmap in c#

前端 未结 3 1514
慢半拍i
慢半拍i 2021-01-24 22:21

I want to convert a string into a bitmap or something I can show in a pixelbox.

My string looks like this:

string rxstring = \"01001001002002002003003003         


        
3条回答
  •  温柔的废话
    2021-01-24 23:06

    Upon continuing review, I realized that the string your getting isn't a byte array. This creates a square Bitmap and lets you set the values pixel by pixel.

    List splitBytes = new List();
    string byteString = "";
    foreach (var chr in rsstring)
            {
                byteString += chr;
    
                if (byteString.Length == 3)
                {
                    splitBytes.Add(byteString);
                    byteString = "";
                }
            }
    
            var pixelCount = splitBytes.Count / 3;
            var numRows = pixelCount / 4;
            var numCols = pixelCount / 4;
    
            System.Drawing.Bitmap map = new System.Drawing.Bitmap(numRows, numCols);
    
            var curPixel = 0;
            for (int y = 0; y < numCols; y++)
            {
                for (int x = 0; x < numRows; x++ )
                {
                    map.SetPixel(x, y, System.Drawing.Color.FromArgb(
                        Convert.ToInt32(splitBytes[curPixel * 3]),
                        Convert.ToInt32(splitBytes[curPixel * 3 + 1]),
                        Convert.ToInt32(splitBytes[curPixel * 3 + 2])));
    
                    curPixel++;
                }
            }
            //Do something with image
    

    EDIT: Made corrections to the row/col iterations to match the image shown above.

提交回复
热议问题