Reputation: 3274
I'm trying to upload an image from my Windows Store App (Windows Phone 8.1) to hosting (using PHP) but always when I "uploaded" the image, and I check its result the "image" it's a corrupted file. I think it's related to the byte array conversion but I haven't found another way to do it. This is my code:
C# Code:
byte[] ConvertBitmapToByteArray()
{
WriteableBitmap bmp = bitmap;
using (Stream stream = bmp.PixelBuffer.AsStream())
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
public async Task<string> Upload()
{
try
{
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent())
{
byte[] data = ConvertBitmapToByteArray();
content.Add(new StreamContent(new MemoryStream(data)), "userfile", fileNewImage);
using (
var message =
await client.PostAsync("http://xplace.com/uploadtest.php", content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
catch (Exception ex)
{
return null;
}
}
PHP code:
<?php
header('Content-Type: application/json');
$uploaddir = getcwd();
$uploadfile = $uploaddir . "/" . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo '{"result": "sucessfull"}';
} else {
echo '{"result": "-1"}';
}
?>
I wish someone could give me an idea about what I my mistake and how to fix it. Thanks in advance for your worthy knowledge.
Upvotes: 2
Views: 200
Reputation: 2466
You need to pass your byte[] data
through a BitmapEncoder
to convert it into a common image format (e.g. BMP, PNG, JPEG) before uploading. At the moment you are just sending the raw ARGB pixel data with no information about how it should be interpreted.
For example, to encode as a BMP:
...
byte[] data = bitmap.PixelBuffer.ToArray();
using (var stream = new InMemoryRandomAccessStream())
{
// encoder *outputs* to stream
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
// encoder's input is the bitmap's pixel data
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, data);
await encoder.FlushAsync();
content.Add(new StreamContent(stream.AsStream()), "userfile", fileNewImage);
...
}
Upvotes: 1