send and receive image using flask-restful (python API) and C# client - c#

I am trying to send image to python code from Xamarin forms (cross platform), I'm using flask-restful (python API) to build web server and call it from the Xamarin app , so first I converted image to base 64:
Image2.Source = ImageSource.FromStream(() => file.GetStream());
var stream = file.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
base64 = System.Convert.ToBase64String(bytes);
and the post code in xamarin:
var imageContent = new MultipartFormDataContent
{
{ new StringContent(base64), "ImageData" }
};
var httpClient = new HttpClient();
var imageResponse = await httpClient.PostAsync("http://localhost:52524/", imageContent);
//
var resultImageContent = imageResponse.Content.ReadAsStringAsync().Result;
if (resultImageContent != null)
{
//some code here
}
now how I can receive the image from the python code.

Related

RTSP Stream not receiving frames

I am trying to use RTSPClientSharp (https://github.com/BogdanovKirill/RtspClientSharp) to receive an RTSP stream (currently testing with rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4) in which the uri works with any other RTSP stream tester I try. In my application it never receives a frame and gets stuck using "rtspClient.ConnectAsync().Wait".
Uri RTSPURL = new Uri("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4");
CancellationToken token = new CancellationToken();
var credentials = new NetworkCredential("", "");
var connectionParameters = new ConnectionParameters(RTSPURL, credentials);
connectionParameters.RtpTransport = RtpTransportProtocol.TCP;
using (var rtspClient = new RtspClient(connectionParameters))
{
rtspClient.ConnectAsync(token).Wait();
rtspClient.ReceiveAsync(token).Wait();
Console.WriteLine("Using RTSPClient");
rtspClient.FrameReceived += (sender, frame) =>
{
Console.WriteLine("Got Frame");
using (MemoryStream memStream = new MemoryStream(frame.FrameSegment.Array, 0, frame.FrameSegment.Array.Count(), true))
{
bmp = new Bitmap(memStream);
}
};
}
Any help would be greatly appreciated!
I'm not receiving any errors so I haven't tried much. Also if I remove the .Wait following the Async functions it doesn't receive any frames.

Upload multiple files using web api in c#

I wanted to make an api call equivalent to the given image (api call made from postman) using WebClient or HttpClient. I want to send a file and a text together in one single api call.
You can save image via api call by HttpClient . here is the code:
Send file to the API
var content = new ByteArrayContent(filedata);
content.Headers.ContentType = new MediaTypeHeaderValue(BE.Common.ContentType.appjson);
using (var client = new HttpClient())
{
aPIRequestfile.FileName = filename;
aPIRequestfile.UserId = CurrentSession.Instance.VerifiedUser.UserDetailId;
aPIRequestfile.ContentType = contentType;
aPIRequestfile.IsProfile = isProfile;
client.DefaultRequestHeaders.Add("FileDetails", JsonConvert.SerializeObject(aPIRequestfile));
var ApiRequest = client.PostAsync(apiUrl, content);
if (ApiRequest != null)
{
if (ApiRequest.Result.StatusCode == HttpStatusCode.OK)
{
RepsonseMsg = ApiRequest.Result.Content.ReadAsStringAsync().Result;
}
else
RepsonseMsg = BE.ResultStatus.Failed.ToString();
}
}
Receive by API
byte[] filebytes = Request.Content.ReadAsByteArrayAsync().Result;
you will receive byte and then can save it.

How to send an image base64 to server windows phone 8.1

I'm developing an application on windows phone 8.1 in c# that can take a picture and send it to a server (in base64) with a post request.
So my problem is that i can't find a method which still work for include my image base64 in the body on my request and send it to my server.
private async void validPicture_Click(object sender, RoutedEventArgs e)
{
Encode("ms-appx:///xx/xxx.jpg");
try
{
var client = new Windows.Web.Http.HttpClient();
var uri = new Uri("http://x.x.x.x:x/picture/");
string pathBase64 = Encode("ms-appx:///xx/xxx.jpg").ToString();
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("type", "recognition");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, formContent);
string content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
}
}
catch (Exception eu)
{
}
}
If you are a question or need more information please tell me.
Thanks for your time.
First of all you have to read image file from storage and convert bytes to base64 string.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(PHOTO_PATH));
byte[] rawBytes;
using (Stream stream = await file.OpenStreamForReadAsync())
{
rawBytes = new byte[stream.Length];
await stream.ReadAsync(rawBytes, 0, rawBytes.Length);
}
string base64Content = Convert.ToBase64String(rawBytes);
Then you have to make request with that content. I'm not sure how yours server accept requests but here is example of sending request with that string in content.
var httpClient = new Windows.Web.Http.HttpClient();
IBuffer content = CryptographicBuffer.ConvertStringToBinary(base64Content, BinaryStringEncoding.Utf8);
var request = new HttpBufferContent(content);
HttpResponseMessage response = await httpClient.PostAsync(new Uri(SERVER_URL), request);

Using Catchoom in C# WP8.1 project

i want to use catchoom in c# , but not able to find any sample could any one please provide any sample code if have.
i have got this sample of curl
curl -F "image=#CATask1-Correct.png" -F "token=sometoken" https://r.catchoom.com/v1/search
Can some one covert this to c# ?
I tried to convert it as shown below:
Here's my code:
public static async Task<string> Upload(byte[] image)
{
using (var client = new HttpClient())
{
// string boundary = "---XXX---";
using (var content = new MultipartFormDataContent())
{
string token = "sometoken";
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(token);
writer.Flush();
stream.Position = 0;
// adding Token and Image to the request
content.Add(new StreamContent(stream), "token");
content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
using (
var message = await client.PostAsync("https://r.catchoom.com/v1/search", content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
then I called the method in the on-click event handler:
private async void mybtn_Click(object sender, RoutedEventArgs e)
{
// converting the image to a byte array
BitmapImage bitmapImage = new BitmapImage(new Uri("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
// calling the upload method
string output = await Upload(buffer);
mytext1.Text = output;
}
but I keep getting "image is missing" error from the catchoom server although I managed to upload the image to other servers in the same way ( without the token part of course).
My question is: How to add multipule part content? what's the right boundary between the Token part and the image part in order to be recognized by catchoom?
Here is what worked for me:
public static async Task<string> Test(string token, Stream stream, string fileName)
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(token), "token");
content.Add(new StreamContent(stream), "image", fileName);
var resp = await client.PostAsync("https://r.catchoom.com/v1/search", content);
return await resp.Content.ReadAsStringAsync();
}
If you wanted to use the image you listed in your sample, here is how I would fetch it:
HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1");
return await Test("<SOME_TOKEN_VALUE>", stream, "apple.png");
However the API claims that the image is unsupported due to alpha transparency. You can find some other samples that show you how to strip alpha transparency if that is important. The above code worked fine for images that don't have alpha transparency.

get image from web service and show on Winforms

i m developing a C# Window Application which uses web service as it's back end,
how to get image from specified URL:
the image on server is in JPEG Format
var client = new RestClient();
client.BaseUrl = "http://www.*****.com/images/12345.jpg";
var request = new RestRequest();
IRestResponse response = client.Execute(request);
Using RestSharp I did it this Way
var client = new RestClient();
client.BaseUrl = "http://www.abcd.com/image1.jpg";
var request = new RestRequest();
picturebox1.Image = new Bitmap(new MemoryStream(client.DownloadData(request)));
Showing Image at Picture Box
If the client has the image URL, why not just use HTTP to download it? Or are you saying that the images will always reside on the same server that the WebService is running on, and that the WebService method should accept a URL, translate it to a local path, and return the image as a byte array?
We have a method of our WSDL WebService that does about the same thing, we don't include the protocol and host portions of the URL (they'd be redundant.)
[WebMethod]
public byte[] GetPicture(string ImageURL)
{
if (ImageURL.StartsWith("http"))
return new byte[0];
string tmp = System.Web.Hosting.HostingEnvironment.MapPath("/" + ImageURL);
string FileName = Microsoft.JScript.GlobalObject.unescape(tmp);
if (System.IO.File.Exists(FileName))
{
FileStream fs = System.IO.File.OpenRead(FileName);
byte[] buf = new byte[fs.Length];
fs.Read(buf, 0, (int)fs.Length);
fs.Close();
return buf;
}
else
return new byte[0];
}
Does that answer your question?

Categories