How do I get image from http url, my url is like:
"http://accd.com/abc.htm",
how do I get image from it?
So
public static BitmapImage Base64StringToBitmap(string source)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
return img;
}
You can use the web client like this :
var webClient = new WebClient();
webClient.DownloadStringAsync(new Uri("http://accd.com/abc.htm"));
webClient.DownloadStringCompleted += (sender, eventArgs) => (eventArgs.Result); //Here is your base 64 image code, you can use the Base64StringToBitmap function
May be with using a webclient
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("your http url"), wc);
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(e.Result);
imgLogoData.Source = bitmapImage;
imgLogoData.Height = 200;
}
catch (Exception ex)
{
MessageBox.Show(AppResources.resErrorOccured);
ExceptionHelper.WriteLog(ex);
}
}
And to convert a Base64 string to BitmapImage just follow this method
public static BitmapImage base64image(string base64string)
{
byte[] fileBytes = Convert.FromBase64String(base64string);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
So that, for an Image declared in xaml like this
Add an image to your XAML, such as this:
<Image x:Name="imgLogoData" Height="50" Width="50" />
You can then set the source, like this:
imgLogoData.Source = base64image(yourBase64string);
Related
I am new to xamarin forms. I implement a simple program where the image is capture from the camera and convert into base64 string and send it to the server like below.
private async void AddNewPhoto(object sender, EventArgs e)
{
MemoryStream memoryStream = new MemoryStream();
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.GetStream().CopyTo(memoryStream);
return stream;
});
paths.Enqueue(filePath);
imgPaths.Add(file);
val.Add(img.Source);
// Set StackLayout in XAML to the class field
parent = headerStack1;
parent.Children.Add(img);
}
async void btnSubmitClicked(object sender, EventArgs args)
{
if (paths.Count > 0)
{
string URL1 = "";
string basicDomain1 = AppConstant.ComplaintsUploadImageURL + PhoneNo + "~secretcode-" +
secretCode;
MultipartFormDataContent form1 = new MultipartFormDataContent();
DependencyService.Get<IHudService>().ShowHud("Loading");
List<string> pathItems = new List<string>();
for each (MediaFile ph in imgPaths)
{
var fileName = filePath.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var file = ph;
var upfilebytes = File.ReadAllBytes(file.Path);
var base64 = Convert.ToBase64String(upfilebytes);
var content = new StringContent(base64);
form1.Add(content, "image_64string");
Dictionary<string, string> UploadJson = new Dictionary<string, string>();
UploadJson.Add("image_txt", imgText);
form1.Add(new StringContent(UploadJson["image_txt"]), "image_txt");
form1.Add(new StringContent("jpg"), "image_extension");
var response_ = await this.apiService.PostImageRequest(form1, URL1, basicDomain1);
if (!response_.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert("Error", response_.Message, "Network Problem!!");
return;
}
}
}
}
But it shows the error "Can not access the closed stream." How to fix this error?
ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>
Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image
I am getting the following error when trying to upload video to Facebook from my web application:
"(OAuthException - #352) (#352) Sorry, the video file you selected is in a format that we don't support"
public void uploadVideoToFaceBook(string accessToken, string videoURL, string videoTitle)
{
byte[] stream = DownloadVideoAsByte(videoURL);
var mediaObject = new FacebookMediaObject
{
FileName = videoTitle,
ContentType = "video/mp4"
};
mediaObject.SetValue(stream);
try
{
var fb = new FacebookClient(accessToken);
dynamic result = fb.Post("me/videos",
new
{
message = "my first photo upload using Facebook SDK for .NET",
file = mediaObject
});
var videoId = (string)result["vid"];
}
catch (FacebookApiException ex)
{
throw;
}
}
Note: DownloadVideoAsByte() returns byte[] from azure blob. following is the code:
public byte[] DownloadVideoAsByte(string videoUrl)
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(videoUrl);
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
System.IO.Stream dataStream = httpResponse.GetResponseStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(dataStream);
String data = streamReader.ReadToEnd();
byte[] buffer = new byte[data.Length];
for (int i = 0; i < data.Length; i++)
buffer[i] = (byte)data[i];
dataStream.Close();
streamReader.Close();
return buffer;
}
Any help in this regard shall be appreciated.
I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?
Update-
This is what I ended up implementing:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(profile.Avatar));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "avatar.png";
return result;
You can set the response content to a StreamContent object:
var fileStream = new FileStream(path, FileMode.Open);
var resp = new HttpResponseMessage()
{
Content = new StreamContent(fileStream)
};
// Find the MIME type
string mimeType = _extensions[Path.GetExtension(path)];
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
While this has been marked as answered, it wasn't quite what I wanted, so I kept looking. Now that I've figured it out, here's what I've got:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
Granted, that's for getting an image through a URL. If you just want to grab an image off the file server, I'd imagine you replace this line:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
With this:
using (Bitmap image = new Bitmap(myFilePath))
EDIT: Never mind, this is for regular MVC. for Web API, I have this:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
Which is quite similar to what OP has.
I did this exact thing. Here is my code:
if (!String.IsNullOrWhiteSpace(imageName))
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(uploadPath, imageName));
var image = System.Drawing.Image.FromFile(savedFileName);
if (ImageFormat.Jpeg.Equals(image.RawFormat))
{
// JPEG
using(var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Png.Equals(image.RawFormat))
{
// PNG
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Gif.Equals(image.RawFormat))
{
// GIF
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Gif);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
}
And then on the client:
var client = new HttpClient();
var imageName = product.ImageUrl.Replace("~/Uploads/", "");
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Properties.Settings.Default.DeviceMediaPath + "\\" + imageName);
var response =
client.GetAsync(apiUrl + "/Image?apiLoginId=" + apiLoginId + "&authorizationToken=" + authToken +
"&imageName=" + product.ImageUrl.Replace("~/Uploads/","")).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
using (var ms = new MemoryStream(data))
{
using (var fs = File.Create(path))
{
ms.CopyTo(fs);
}
}
result = true;
}
else
{
result = false;
break;
}
This task is much easily achieved without using WebAPI. I would implement a custom HTTP handler for a unique extension, and return the binary response there. The plus is that you can also modify the HTTP Response headers and content type, so you have absolute control over what is returned.
You can devise a URL pattern (defining how you know what image to return based on its URL), and keep those URLs in your API resources. Once the URL is returned in the API response, it can be directly requested by the browser, and will reach your HTTP handler, returning the correct image.
Images are static content and have their own role in HTTP and HTML - no need to mix them with the JSON that is used when working with an API.
I'm using FileResult as a return value for a function in MVC that returns a PDF file.
What return type should I use in Web Forms?
Thanks
public FileResult PrintPDFVoucher(object sender, EventArgs e)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
outputDoc.Save(memory, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
var result = new FileContentResult(memory.GetBuffer(), "text/pdf");
result.FileDownloadName = "file.pdf";
return result;
}
In ASP.NET Webforms you'll need to write the file to the Response stream manually. There is no result abstraction in webforms.
Response.ContentType = "Application/pdf";
//Write the generated file directly to the response stream
Response.BinaryWrite(memory);//Response.WriteFile(FilePath); if you have a physical file you want them to download
Response.End();
This code is not tested, but this should get you in the general direction.
Classic ASP.NET doesn't have the idea of a return type. The way to approach this would be to create an custom .ashx page/handler to serve up the file.
Your code behind for this file should look something similar to:
public class Download : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
PdfDocument outputDoc = new PdfDocument();
PdfDocument pdfDoc = PdfReader.Open(
Server.MapPath(ConfigurationManager.AppSettings["Template"]),
PdfDocumentOpenMode.Import
);
MemoryStream memory = new MemoryStream();
try
{
//Add pages to the import document
int pageCount = pdfDoc.PageCount;
for (int i = 0; i < pageCount; i++)
{
PdfPage page = pdfDoc.Pages[i];
outputDoc.AddPage(page);
}
//Target specifix page
PdfPage pdfPage = outputDoc.Pages[0];
XGraphics gfxs = XGraphics.FromPdfPage(pdfPage);
XFont bodyFont = new XFont("Arial", 10, XFontStyle.Regular);
//Save
Response.ContentType = ""text/pdf"";
Response.AppendHeader("Content-Disposition","attachment; filename=File.pdf");
outputDoc.Save(Response.OutputStream, true);
gfxs.Dispose();
pdfPage.Close();
}
finally
{
outputDoc.Close();
outputDoc.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}