How to download Image[Call API, API returns byte[] of image] from server and show it in contentpage in xamarin forms - image

Call Rest service
Rest service returns byte[] representation of image/audio/video
convert into byte[] to image and show in content page in xamarin

First of all, you can create a function that simply makes an API request and obtains the content in the form of byte array. A simple example of HTTP request:
public static byte[] GetImageByteArray(string url)
{
try
{
using (var client = new HttpClient())
{
var uri = new Uri(url);
var response = client.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsByteArrayAsync();
return content.Result;
}
}
return null;
}
catch
{
return null;
}
}
Next, you can simply bind the output from your result into your image source and the image to your content:
var mainStack = new StackLayout();
var imageByteArray = GetImageByteArray("https://static.pexels.com/photos/34950/pexels-photo.jpg");
Image image;
if (imageByteArray != null)
{
image = new Image()
{
Source = ImageSource.FromStream(() => new MemoryStream(imageByteArray))
};
mainStack.Children.Add(image);
}
Content = mainStack;

Related

authorization required when create pdf file

I am trying to generate pdf file using c# web api using the following code :
i have tried to change in the web.config but it didn't help.
[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
I expected download pdf directly to my local disk but non worked.

Loading Images from Web Api in Xamarin.Forms

I need to load a picture from a web api backend into my Xamarin.Forms app.
The picture is stored in an Azure Blob Storage.
This is my Web Api method:
[HttpGet("{id}")]
public HttpResponseMessage Get(int id)
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("ConnectionString");
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("picturecontainer");
// Retrieve reference to a blob named "photo.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("picture");
var stream = new MemoryStream();
blockBlob.DownloadToStream(stream);
Image image = Image.FromStream(stream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Jpeg);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(memoryStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return result;
}
In my app I try to download the image bytes with the following code:
public App ()
{
_client = new HttpClient();
_client.MaxResponseContentBufferSize = 256000;
Button downloadImageBtn = new Button () {
Text = "Download Image",
};
var image = new Image() {
Source = ImageSource.FromUri (new Uri ("http://www.engraversnetwork.com/files/placeholder.jpg")),
Aspect = Aspect.AspectFit
};
downloadImageBtn.Clicked += async (object sender, EventArgs e) => {
var values = await handleClick (sender, e);
uploadPicButton.Text = values;
var imageBytes = await downloadPicture();
image.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
};
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
image,
downloadImageBtn
}
}
};
}
private async Task<byte[]> downloadPicture()
{
var uri = new Uri (string.Format (RestUrl, "5"));
//return await _client.GetByteArrayAsync (uri);
var response = await _client.GetAsync (uri);
if (response.IsSuccessStatusCode) {
var content = await response.Content.ReadAsByteArrayAsync ();
return content;
}
throw new HttpRequestException ();
}
However when I click on the button, the placeholder image disappears.
Is there a problem when sending the image from the server or when receiving it in the app?
I'd not implement downloading Images manually.
If you want to load more images and/or allow to display a placeholder while loading, I recommend the FFImageLoading library. It offers nice functionality like downloading, caching, showing placeholder and error images and most important: down sampling the image to the target size. This is always a pain on android. Its available for native UI xamarin projects and for Xamarin.Froms.
You can bind strings that contain urls directly to the Source. The code would like like:
<ffimageloading:CachedImage
Source="http://thecatapi.com/?id=MTQ5MzcyNA">
</ffimageloading:CachedImage>
After blockblob.DownloadToStream line, try to set Position of the stream to 0. I'm not familiar with Azure API, but I think it may help.
Also ,try to use ReadAsStreamAsync instead of ReadAsByteArrayAsync in your downloadPicture function. Something like this:
var responseStream = await response.Content.ReadAsStreamAsync();
byte[] buf = new byte[512];
int bufSize;
while((bufSize = (await responseStream.ReadAsync(buf, 0, buf.Length))) > 0)
{
// store the received bytes to some buffer until the file is fully downloaded
}
Do you get all your content this way?

HTTP Post Windows Phone

I'm making a call to an API that consists in a HTTP Post request. The data i want to post is an image, properly converted into a byte array.
The response is not as expected, and i want to know what is the error: is it my code or is it the API? This is the code that i'm using
Image i = new Image();
BitmapImage bi = new BitmapImage(new Uri("/Images/dmoc.jpeg", UriKind.Relative));
testImage.Source = bi;
byte[] rawimage = ImageConverter.ImageToBytes(bi);
try
{
var baseAddress = new Uri("http://private-anon-6cf48a749-yugiohprices.apiary-mock.com/");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
//HttpRequestHeader.ContentType
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpeg"));
using (var response = await httpClient.PostAsync("api/match_card_image", new ByteArrayContent(rawimage)))
{
string responseData = await response.Content.ReadAsStringAsync();
postTxt.Text = responseData;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.StackTrace);
}
where ImageConverter is my class.

Passing cookies to Image.GetInstance

Using image handler to convert relative path to absolute.
protected byte[] ConvertHTMLToPDF(string HTMLCode)
{
if (Request.Url == null)
throw new Exception();
var doc = new Document(PageSize.A4);
doc.Open();
var interfaceProps = new Hashtable();
var ih = new ImageHander {BaseUri = Request.Url.ToString()};
interfaceProps.Add("img_provider", ih);
foreach (IElement element in HTMLWorker.ParseToList(new StringReader(HTMLCode), null, interfaceProps))
{
doc.Add(element);
}
var _xmlr = new XmlTextReader(new StringReader(HTMLCode));
HtmlParser.Parse(doc, _xmlr);
var stream = new MemoryStream();
PdfWriter.GetInstance(doc, stream);
doc.Close();
return stream.ToArray();
}
class:
public class ImageHander : IImageProvider
{
public string BaseUri;
public Image GetImage(string src, Hashtable h, ChainedProperties cprops, IDocListener doc)
{
string imgPath;
if (src.ToLower().Contains("http://") == false)
imgPath = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + src;
else
imgPath = src;
return Image.GetInstance(imgPath);
}
}
imgPath at the end is correct. But it's not static file, it's url of action that returns image, so I need to pass cookies when requesting image. Is it possible?
Yes, it is possible, but you're gonna have to send the request yourself and not rely on the Image.GetInstance method. For example using the HttpClient you could send cookies along with the request:
var imageUrl = new Uri(imagePath);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
cookieContainer.Add(
new Uri(imageUrl.GetLeftPart(UriPartial.Authority)),
new Cookie("CookieName", "cookie_value")
);
var response = client.GetAsync(imageUrl).Result;
response.EnsureSuccessStatusCode();
Stream imageStream = response.Content.ReadAsStreamAsync().Result;
// You've got the Stream here, read the documentation of iTextSharp
// how to create an Image instance from a Stream:
return Image.FromStream(imageStream); // ?????
// or maybe there's a method allowing you to create an Image from byte[]
byte[] imageData = new byte[imageStream.Length];
imageStream.Read(imageData, 0, imageData.Length);
return Image.FromByteArray(imageData); // ?????
}

Convert PartialView Html to String for ITextSharp HtmlParser

I've got a partial view, i'm trying to use ITextSharp to convert the html to pdf. How can I convert the html to string so I can use ItextSharps HtmlParser?
I've tried something like this with no luck...any ideas?:
var contents = System.IO.File.ReadAllText(Url.Action("myPartial", "myController", new { id = 1 }, "http"));
I have created a special ViewResult class that you can return as the result of an Action.
You can see the code on bitbucket (look at the PdfFromHtmlResult class).
So what it basically does is:
Render the view through the Razor engine (or any other registered engine) to Html
Give the html to iTextSharp
return the pdf as the ViewResult (with correct mimetype, etc).
My ViewResult class looks like:
public class PdfFromHtmlResult : ViewResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(this.ViewName)) {
this.ViewName = context.RouteData.GetRequiredString("action");
}
if (this.View == null) {
this.View = this.FindView(context).View;
}
// First get the html from the Html view
using (var writer = new StringWriter()) {
var vwContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer);
this.View.Render(vwContext, writer);
// Convert to pdf
var response = context.HttpContext.Response;
using (var pdfStream = new MemoryStream()) {
var pdfDoc = new Document();
var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();
using (var htmlRdr = new StringReader(writer.ToString())) {
var parsed = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(htmlRdr, null);
foreach (var parsedElement in parsed) {
pdfDoc.Add(parsedElement);
}
}
pdfDoc.Close();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", this.ViewName + ".pdf");
byte[] pdfBytes = pdfStream.ToArray();
response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
}
}
}
}
With the correct extension methods (see BitBucket), etc, the code in my controller is something like:
public ActionResult MyPdf(int id) {
var myModel = findDataWithID(id);
// this assumes there is a MyPdf.cshtml/MyPdf.aspx as the view
return this.PdfFromHtml(myModel);
}
Note: Your method does not work, because you will retrieve the Html on the server, thereby you loose all cookies (=session information) that are stored on the client.

Resources