将位图写入文件中的文本行(C#)

时间:2014-03-13 07:00:06

标签: c# file bitmap .net-3.5

我需要将Bitmap图像转换为文本文件中的行。 所以我首先将Bitmap转换为字节数组,然后尝试将字节数组转换为字符串,然后将字符串追加到txt文件中的行。

必须是这样的:

  

test.txt

     

3 34 25 245 ... 24 2 1#1st image

     

73 32 2 2 4 ... 12 2 5#2nd image

此代码不起作用,如何更改?

public static void SaveImgAsText(Bitmap img, string path)
{ 
    // Specify a pixel format.
    PixelFormat pxf = PixelFormat.Format24bppRgb;

    // Lock the bitmap's bits.
    Rectangle rect = new Rectangle(0, 0, img.Width, img.Height);
    BitmapData bmpData =
    img.LockBits(rect, ImageLockMode.ReadWrite,
                 pxf);

    // Get the address of the first line.
    IntPtr ptr = bmpData.Scan0;

    // Declare an array to hold the bytes of the bitmap. 
    // int numBytes = bmp.Width * bmp.Height * 3; 
    int numBytes = bmpData.Stride * img.Height;
    byte[] rgbValues = new byte[numBytes];

    // Copy the RGB values into the array.
    Marshal.Copy(ptr, rgbValues, 0, numBytes);

    string result = System.Text.Encoding.UTF8.GetString(rgbValues);
} 

2 个答案:

答案 0 :(得分:1)

System.Text.Encoding.UTF8.GetString将字节作为原始Unicode,并从中创建一个字符串。完全不是你想要的。请改用此功能:

    public static string ByteArrayToDecimalString(byte[] ba)
    {
        StringBuilder hex = new StringBuilder();
        string format = "{0}";
        foreach (byte b in ba)
        {
            hex.AppendFormat(format, b);
            format = " {0}";
        }
        return hex.ToString();
    }

答案 1 :(得分:0)