Question

I need to convert Bitmap image to line in text file. So I convert Bitmap to byte array first and then trying to convert byte array to string and then append string to line in txt file.

It must be something like:

test.txt

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

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

This code don't work, how to change it?

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);
} 
Was it helpful?

Solution

System.Text.Encoding.UTF8.GetString takes the bytes as raw Unicode and creates a string from that. Totally not what you want. Use this function instead:

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

OTHER TIPS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top