dongta1824 2016-03-04 14:27
浏览 127
已采纳

WebClient.UploadFile是一个位图?

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.
  • 写回答

1条回答 默认 最新

  • duanoucuo7045 2016-03-04 14:43
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大