Search code examples
c#image-processingscreenshot

C# convert screenshot data


I would need to take a screenshot, if easy to without saving it. I would sent the image data directly to a PHP script. Because I don't have this PHP script at the moment, so I search for the easiest way of format in which I should convert the screenshot data. For debugging reasons until I've got my PHP script I would like to convert a picture of these data on my client side using C#.

My code at the moment for taking a screenshot and convert it (I'm not sure if I can convert the output in my logfile back into a picture):

     internal static byte[] ImageToByteArray(Image img)
    {
        byte[] byteArray = new byte[0];
        MemoryStream stream = new MemoryStream();
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();
        byteArray = stream.ToArray();
        return byteArray;
    }

   public static string TakeScreenshot()
       {

           String filepath = @"C:\log2.txt";

           Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);

           Graphics graphics = Graphics.FromImage(bitmap);

           graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
           graphics.Dispose();
           bitmap.Save("C:\\temp.png");


           Image img = (Image)bitmap;
           string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
           System.IO.File.AppendAllText(filepath, str);
           //just for debugging
           return "OH";
       }

Main question at the moment, is there any way to get a picture back from my converted code (log2.txt).


Solution

  • This line of code:

    string str = System.Text.Encoding.Default.GetString(ImageToByteArray(img));
    

    Will almost certainly not do what you want it to do. It will try to interpret your byte array as a string in whatever is the default character encoding on your machine. If the default is something like UTF-8 or any multibyte character set, then it's quite likely to fail. Even if the default encoding is a single-byte character set, it could create a string that can't be reliably turned back into the original byte array.

    If you really want to store the byte array as text, you can call Convert.ToBase64String:

    string str = Convert.ToBase64String(ImageToByteArray(img));
    

    If you read that string back from the file into str, you can rebuild the byte array with:

    byte[] imageBytes = Convert.FromBase64String(str);
    

    Another advantage in your particular case is that there are PHP functions for dealing with base 64 strings.