将图像从C#程序发送到PHP网页进行显示

时间:2014-05-29 15:44:33

标签: c# php image

我是C#的新手,我正在使用这段代码:

//Take a snapshot from left camera and save to current directory as "snapshot.png"
            case Key.Z:
                int left = camLeft.Device.LensCorrection1;
                camLeft.Device.LensCorrection1 = 0;
                Thread.Sleep(150);
                BitmapSource bmpSource = camLeft.Device.BitmapSource as BitmapSource;
                MemoryStream ms = new MemoryStream();
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmpSource));
                encoder.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);

                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms);
                string filepath = Environment.CurrentDirectory;
                string fileName = System.IO.Path.Combine(filepath, @"snapshot.png");
                bitmap.Save(fileName, ImageFormat.Png);
                bitmap.Dispose();
                camLeft.Device.LensCorrection1 = left;
                break;

这是为相机开发的代码,按下按钮,拍摄快照并将其存储为png文件。仅此一点起作用 - 但我要做的是让它也获取图像数据并自动将其发送到PHP网页,该网页自动接收数据并显示图像(绕过必须将其存储在MySQL服务器中) 。我希望这一切都可以通过单按按钮完成 - 从拍摄快照到所有上传到要查看的网页。

所以上面的代码看起来像是在上面代码的空格之间插入新的,有问题/无效的代码:

//Take a snapshot from left camera and save to current directory as "snapshot.png"
            case Key.Z:
                int left = camLeft.Device.LensCorrection1;
                camLeft.Device.LensCorrection1 = 0;
                Thread.Sleep(150);
                BitmapSource bmpSource = camLeft.Device.BitmapSource as BitmapSource;
                MemoryStream ms = new MemoryStream();
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmpSource));
                encoder.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);

                byte[] imageBytes = ms.ToArray();
                string base64 = ImageToBase64(imageBytes);
                string base64Encoded = HttpUtility.UrlEncode(base64);
                WebClient client = new WebClient();
                client.UploadString("www.thisismydesiredurl.com", base64Encoded);                    
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms);
                string filepath = Environment.CurrentDirectory;
                string fileName = System.IO.Path.Combine(filepath, @"snapshot.png");
                bitmap.Save(fileName, ImageFormat.Png);
                bitmap.Dispose();
                camLeft.Device.LensCorrection1 = left;
                break;

ImageToBase64是一种将图像转换为base64的方法,如下所示:

public string ImageToBase64(byte[] imageBytes)
    {
            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;            
    }

附加代码用于获取图像,将其转换为字节,将其转换为base64,然后通过POST方法将字符串上传到准备接收数据的PHP页面。然后,PHP页面具有以下用于解码和显示图像的代码:

<?php
$data = $_POST['base64Encoded'];
$decodedata = urldecode($data);
$rawdata = base64_decode($decodedata);
$source = imagecreatefromstring($rawdata);
?> 

<img src= "<?php echo $source ?>" alt="test"/>

但它不起作用 - 没有显示图像,但我知道页面已启动。我错过了什么?

我也对我可能不了解的更简单/替代解决方案持开放态度。我想要的只是按一下按钮就可以在一个明确的URL上自动查看这个图像 - 这就是所有

编辑:下面提供的答案“有效”,但我总是在我的网站上得到一个破碎的图像 - 所以看起来图像正在上传并发送到网站,它只是没有被正确编码/解码。似乎无法弄清楚为什么。想法?

1 个答案:

答案 0 :(得分:3)

你这样做的方式,它永远不会起作用。当您进行HTTP POST时,服务器端脚本将用于处理它并为您提供输出。但是,当您访问http post请求之外的脚本时,将无法看到相同的输出。

您需要做的是将数据发布到图片上传脚本。该脚本应该将文件保存在服务器上并显示它。

例如:

<强> C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Drawing;
using System.Collections.Specialized;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load a image
            System.Drawing.Image myImage = GetImage("http://personal.psu.edu/tao5048/JPG.jpg");

            // 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://yoursite.com/test.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
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
    }
}

PHP test.php

<?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.');
}

// Display Image
if (file_exists('test.jpg'))
{
    echo '<img src="test.jpg" />';
}
else
{
    echo "Image not uploaded yet.";
}

?>

C#app的输出是:

enter image description here

图片上传后,如果您在浏览器中访问http://yoursite.com/test.php(例如),这就是您所看到的内容(即来自c#的上传图片,保存在服务器上,正在提供服务):

enter image description here

希望这有帮助。