How to get image from web api url? - asp.net-web-api

I have a url that when paste it into browser address display an image.This url call a method of webapi that return an image.I need to get image code by string format and save into database .
I use this code :
var client = new HttpClient();
var barcode = client.GetAsync("https://store.zirbana.com/v2/barcode/render?text=234501").Result;
This code has result but How can i get image from this?

You can extract the content of the response as a byte array and convert that to a base64 string to be saved in the database.
public async Task<string> GetBarCode(string attachmentUrl) {
using (var client = new HttpClient()) {
using (var response = await client.GetAsync(attachmentUrl)) {
var bytes = await response.Content.ReadAsByteArrayAsync();
var base64String = Convert.ToBase64String(bytes);
return base64String;
}
}
}
If you meant interpreting the image to then you need to use a barcode reader to scan the image and get the actual code stored in the image.

Related

How to satisfy multiple byte ranges when using PushStreamContent in WebAPI?

I need to use PushStreamContent because of the source of my data (effectively have to concatenate blobs), but I also have to support requests for multiple byte ranges (arbitrary ranges not aligned to the stored blobs). What is not clear to me is if I can use PushStreamContent to generate a multipart/byteranges response, if each range needs to be separated in the response, and if so, how to do it, and how it relates to the chunked transfer encoding which PushStreamContent invokes.
You can do it using MultipartContent like this:
public class MyRangeController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
// Create a multi-part content object for the response; note that per RFC spec, subtype must be "byteranges"
// Note that the content type of the over-all response will be "multipart/byteranges"
// We choose to use a GUID string for the separator; it could be anything suitable.
var multipartContent = new MultipartContent("byteranges", Guid.NewGuid().ToString("D"));
// Create the response object and set its content
var response = new HttpResponseMessage(HttpStatusCode.PartialContent) { Content = multipartContent };
foreach (var rangeItemHeaderValue in Request.Headers.Range.Ranges)
{
// Create PushStreamContent object for our current byte range...
var pushStreamContent = new PushStreamContent((stream1, content, arg3) =>
{
// Write to stream1
stream1.Close();
});
// We need to add certain headers to each part of the response
pushStreamContent.Headers.ContentRange = new ContentRangeHeaderValue(rangeItemHeaderValue.From.Value, rangeItemHeaderValue.To.Value, /* total size of the resource */);
pushStreamContent.Headers.ContentType = new MediaTypeHeaderValue(/* Set a content type for each part of the response */);
// Add the part to the multi-part content response
multipartContent.Add(pushStreamContent);
}
return response;
}
}

How to convert from Java to Xamarin C#

Can someone help me convert the following from Java to C# (Xamarin)?
I tried a couple of different ways, but I cannot get it to work.
The code is:
HttpPost post = new HttpPost(url);
// Break out all extra HTTP header lines and add it to the HttpPost object
for (String line : contentType.replace("\r", "\n").split("\n")) {
if (line.length() > 0 && line.contains(":")) {
String[] parts = line.split(":", 2);
if (parts.length == 2) {
post.addHeader(parts[0].trim(), parts[1].trim());
}
}
}
// Create a byte array entity for the POST data, the content
// type here is only used for the postEntity object
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.setContentType("application/octet-stream");
post.setEntity(postEntity);
// Create a HttpClient and execute the HttpPost filled out above
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
// Get the response entity out of the response
HttpEntity entity = httpResponse.getEntity();
If you are stuck with
post.SetEntity(postEntity);
then it converts to:
ByteArrayEntity postEntity = new ByteArrayEntity(challenge);
postEntity.SetContentType("application/octet-stream");
post.Entity = postEntity;
When converting to Java from C# you mostly have to change the property names to start with upperCase and then if you get stuck on certain objects I would look check out the Xamarin API Docs, HttpPost class linked here.

What is the magento url for posting SOAP request

Below is my code
WebClient wc = new WebClient();
using(var response = wc.OpenRead("http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap?wsdl=1"))
{
StreamReader sr = new StreamReader(response);
string result = sr.ReadToEnd();
}
var loginRequest = string.Format(XElement.Load(AppDomain.CurrentDomain.BaseDirectory + #"XMLFiles\login.xml").ToString(),"apikey","apipassword");var loginRequest = string.Format(XElement.Load(AppDomain.CurrentDomain.BaseDirectory + #"XMLFiles\login.xml").ToString(),"admin","abcd.1234");
var response1 = wc.UploadString("", loginRequest);
My question is what should be the "address" in UploadString function so that the login request gets the desired result i.e,Magento Session id
If I use this "http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap?wsdl=1"
URL again then I get the list of wsdl services available,which is the same as in response variable.
Please Help,
Thanks.
According to the provided wsdl, the endpoint location is: http://templatebar.com/QA/performancetesting/enterprise1_10_0_2/magento/index.php/api/v2_soap/index/
(source: check the wsdl:service location for it. The url is written in the location-element)

How to retrieve photo previews in app.net

When I have an app.net url like https://photos.app.net/5269262/1 - how can I retrieve the image thumbnail of the post?
Running a curl on above url shows a redirect
bash-3.2$ curl -i https://photos.app.net/5269262/1
HTTP/1.1 301 MOVED PERMANENTLY
Location: https://alpha.app.net/pfleidi/post/5269262/photo/1
Following this gives a html page that contains the image in a form of
img src='https://files.app.net/1/60621/aWBTKTYxzYZTqnkESkwx475u_ShTwEOiezzBjM3-ZzVBjq_6rzno42oMw9LxS5VH0WQEgoxWegIDKJo0eRDAc-uwTcOTaGYobfqx19vMOOMiyh2M3IMe6sDNkcQWPZPeE0PjIve4Vy0YFCM8MsHWbYYA2DFNKMdyNUnwmB2KuECjHqe0-Y9_ODD1pnFSOsOjH' data-full-width='2048' data-full-height='1536'
Inside a larger block of <div>tags.
The files api in app.net allows to retrieve thumbnails but I somehow don't get the link between those endpoints and above urls.
The photos.app.net is just a simple redirecter. It is not part of the API proper. In order to get the thumbnail, you will need to fetch the file directly using the file fetch endpoint and the file id (http://developers.app.net/docs/resources/file/lookup/#retrieve-a-file) or fetch the post that the file is included in and examine the oembed annotation.
In this case, you are talking about post id 5269262 and the URL to fetch that post with the annotation is https://alpha-api.app.net/stream/0/posts/5269262?include_annotations=1 and if you examine the resulting json document you will see the thumbnail_url.
For completeness sake I want to post the final solution for me here (in Java) -- it builds on the good and accepted answer of Jonathon Duerig :
private static String getAppNetPreviewUrl(String url) {
Pattern photosPattern = Pattern.compile(".*photos.app.net/([0-9]+)/.*");
Matcher m = photosPattern.matcher(url);
if (!m.matches()) {
return null;
}
String id = m.group(1);
String streamUrl = "https://alpha-api.app.net/stream/0/posts/"
+ id + "?include_annotations=1";
// Now that we have the posting url, we can get it and parse
// for the thumbnail
BufferedReader br = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(streamUrl).openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.connect();
StringBuilder builder = new StringBuilder();
br = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line=br.readLine())!=null) {
builder.append(line);
}
urlConnection.disconnect();
// Parse the obtained json
JSONObject post = new JSONObject(builder.toString());
JSONObject data = post.getJSONObject("data");
JSONArray annotations = data.getJSONArray("annotations");
JSONObject annotationValue = annotations.getJSONObject(0);
JSONObject value = annotationValue.getJSONObject("value");
String finalUrl = value.getString("thumbnail_large_url");
return finalUrl;
} .......

FileStreamResult displays empty browser document when rendering image from stream in MVC3

I have a fairly simple Action in an MVC3 application that should render an image...
public FileStreamResult Photo(int id)
{
//get the raw bytes for the photo
var qry = from p in db.Photos
where p.PhotoID == id
select p.PhotoData;
var data = qry.FirstOrDefault();
var mem = new MemoryStream(data);
var fs = new FileStreamResult(mem, "image/jpeg");
return fs;
}
When i run this i get a blank document in Chrome, Firefox displays the URL in the actual document area and IE renders the raw bytes.
Chrome gives me a message: Resource interpreted as Document but transferred with MIME type image/jpeg
This suggests to me that the stream data is not being sent to the browser and it is in fact receiving an empty document, but IE suggests the opposite.
Anyone come across this before, or know how to get around it?
You don't need a stream if you already have a byte array of the photo:
public ActionResult Photo(int id)
{
var data = db.Photos.FirstOrDefault(p => p.PhotoID == id);
if (data == null)
{
return HttpNotFound();
}
return File(data.PhotoData, "image/jpeg");
}
The problem with your code is that you need to reset the memory stream at the beginning but as I said you don't need all this.

Resources