WebClient.UploadFile растровое изображение?

Мне очень жаль, если это похоже на другой вопрос, или на вопрос уже дан ответ, но я не могу сделать эту работу.

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

Я делаю скриншот, а затем я хочу загрузить его на свой сервер через файл php. Который должен сохранить файл, и это работает, если я указываю уже сохраненный файл на моем компьютере, но я не могу заставить его работать с растровым изображением.

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

Как преобразовать растровое изображение, чтобы оно работало с WebClient UploadFile?

РЕДАКТИРОВАТЬ

Ошибка выдана (переведено, возможно, нет точных слов):

System.Net.WebException: An exception occured during a WebClient-request. ---> System.ArgumentException: Invalid characters in path.

0

Решение

Попробуй это.

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 (один из моих предыдущих ответов)

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector