0

I'm really sorry if this is similar to another question, or the question has already been answered, but I cannot make this work.

Bitmap image = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(image);
g.CopyFromScreen(ix+left, iy,0,0, new System.Drawing.Size(iw, ih), CopyPixelOperation.SourceCopy);

MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Png);
byte[] bitmapBytes = memoryStream.GetBuffer();
string bitmapString = Convert.ToBase64String(bitmapBytes, Base64FormattingOptions.InsertLineBreaks);

try
{
    System.Net.WebClient Client = new System.Net.WebClient();
    Client.Headers.Add("Content-Type", "binary/octet-stream");
    byte[] result = Client.UploadFile("http://localhost/image/index.php", "POST", bitmapString);
    string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
} catch (Exception ex)
{
    System.Diagnostics.Trace.WriteLine(ex + " BITMAPSTR: "+bitmapString);
}

I'm taking a screenshot and then I want to upload it to my server via a php file. Which is supposed to save the file, and that works if I specify an already saved file on my computer, but I cannot make it work with a bitmap.

if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "./$name");
}

How do I convert a bitmap so it works with WebClient UploadFile?

EDIT

Error thrown (translated, might not be the exact words):

System.Net.WebException: An exception occured during a WebClient-request. ---> System.ArgumentException: Invalid characters in path.
user1768788
  • 1,265
  • 1
  • 10
  • 29
  • So what *does* happen, exactly? (I would strongly avoid using `MemoryStream.GetBuffer`, by the way. Use `ToArray()` instead *or* make use of `Length` to avoid including the unused bit of the buffer) – Jon Skeet Mar 04 '16 at 14:34
  • See the edit, added the error thrown – user1768788 Mar 04 '16 at 14:38
  • 1
    Right. Now it makes perfect sense. Hint: read the documentation for the method you're calling. https://msdn.microsoft.com/en-gb/library/esst63h0(v=vs.110).aspx You probably want `UploadData` instead. (It's not clear whether you really need to base64-encode the data, btw...) – Jon Skeet Mar 04 '16 at 14:40
  • `UploadFile()` uploads a file existing on disk, its path identified by the string parameter. If you want to upload a base64-formatted string, use `UploadString()` instead. However, your PHP code doesn't seem to base64-decode the uploaded file, why do you use base64 in the first place? – CodeCaster Mar 04 '16 at 14:40
  • I'm not sure really, I'm trying to upload an image to the php server and I'm browsing around for solutions regarding converting bitmap to an uploadable state. Feel free to post solutions on how to. – user1768788 Mar 04 '16 at 14:43
  • Don't convert to base64. It make your data much bigger, therefore take lot of time to upload. – NoName Mar 04 '16 at 14:52
  • @Sakura what other option do you have for transferring binary data to remote server? – Latheesan Mar 04 '16 at 14:55
  • @Latheesan [this one](http://stackoverflow.com/questions/10237983/upload-to-php-server-from-c-sharp-client-application) for example, the data it send is about 25% smaller than the code in your answer send. – NoName Mar 04 '16 at 15:00

1 Answers1

1

Try this.

C#

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load a bitmap image here
            // your code here

            // Convert to base64 encoded string
            string base64Image = ImageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Jpeg);

            // Post image to upload handler
            using (WebClient client = new WebClient())
            {
                byte[] response = client.UploadValues("http://localhost/image/index.php", new NameValueCollection()
                {
                    { "myImageData", base64Image }
                });

                Console.WriteLine("Server Said: " + System.Text.Encoding.Default.GetString(response));
            }

            Console.ReadKey();
        }

        static System.Drawing.Image GetImage(string filePath)
        {
            WebClient l_WebClient = new WebClient();
            byte[] l_imageBytes = l_WebClient.DownloadData(filePath);
            MemoryStream l_stream = new MemoryStream(l_imageBytes);
            return Image.FromStream(l_stream);
        }

        static string ImageToBase64(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                return Convert.ToBase64String(imageBytes);
            }
        }
    }
}

PHP

// Handle Post
if (count($_POST))
{
    // Save image to file
    $imageData = base64_decode($_POST['myImageData']);

    // Write Image to file
    $h = fopen('test.jpg', 'w');
    fwrite($h, $imageData);
    fclose($h);

    // Success
    exit('Image successfully uploaded.');
}

Ref: https://stackoverflow.com/a/23937760/2332336 (one of my previous answer)

Community
  • 1
  • 1
Latheesan
  • 23,247
  • 32
  • 107
  • 201
  • "Here is a dump of your fixed code" hardly helps the OP, nor anyone else finding this question later. Please explain what you changed, why, and how that solves the problem. – CodeCaster Mar 04 '16 at 15:34