从图库中选择图像,我可以上传流,但收到错误“参数无效”。尝试在 WCF 中转换为图像时。
Android 代码创建到 REST 服务的连接并将图像上传为 Byte[]:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 6, out);
DefaultHttpClient httpClient = new DefaultHttpClient();
byte[] sendData = out.toByteArray();
HttpPost postRequest = new HttpPost("http://www.thehost.dk/MobileService/Service.svc/uploadpicture/");
ByteArrayBody bab = new ByteArrayBody(sendData, "picture.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
postRequest.setEntity(reqEntity);
httpClient.execute(postRequest);
WCF C# 代码接收流并尝试转换为图像,但收到错误:
public void UploadPicture(Stream imageData)
{
try
{
byte[] image = StreamToBytes(imageData);
ImageConverter imageConverter = new ImageConverter();
Image img = imageConverter.ConvertFrom(image) as Image; <-- Exception happens here
SaveImage(img);
}
catch (Exception ex)
{
Log(ex.ToString());
}
}
private byte[] StreamToBytes(Stream stream)
{
byte[] output = new byte[0];
byte[] stream_array = new byte[0];
byte[] buffer = new byte[1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
stream_array = new byte[output.Length + read];
output.CopyTo(stream_array, 0);
Array.Copy(buffer, 0, stream_array, output.Length, read);
output = stream_array;
}
return output;
}
我究竟做错了什么?