i have an aspx page,there is textbox to write an url and a button to show some pictures that are in that url.I can load the url's source code to HtmlDocument.but i dont know how to load pictures from that html source code to show that pictures in my page.How can i do that ? Thanks in advance
You need to make the question more clear so that one can give you a specific answer.
HTML is a markup language which means that there are only format tags, there are no pictures embedded in a .html document. There are only links to images that are urls that can be accessed trough some address. In order to get the images you need to get that url.
If your question is how you can get the actual html from a link then refer to the following question. But, since you say that you can get the html, then you need to parse it using Regex or HTML Agility Pack.
Code to get the image:
byte[] imageData = DownloadData(Url); //DownloadData function from here
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);
stream.Close();
for method DownloadData you can use WebClient or WebRequest to get the image in a byte array:
WebRequest req = WebRequest.Create("[URL here]");
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] b;
using (BinaryReader br = new BinaryReader(stream))
{
b = br.ReadBytes(size);
br.Close();
}
return b;
Related
I did researches and fell on this solution: http://forums.xamarin.com/discussion/22682/is-there-a-way-to-turn-an-imagesource-into-a-byte-array
Initial question: http://forums.xamarin.com/discussion/29569/is-there-a-cross-platform-solution-to-imagesource-to-byte#latest
We want to upload an image through a HTTP Post, here's what we tried:
HttpClient httpClient = new HttpClient ();
byte[] TargetImageByte = **TargetImageSource**; //How to convert it to a byte[]?
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
httpClient.PostAsync ("https://api.magikweb.ca/debug/file.php", httpContent);
We also are having a hard time with the libraries we gotta include in the using clauses. It seems like using System.IO; works, but it doesn't give us access to classes like FileInfo or FileStream.
Anybody has any idea how this can be done aside from custom platform-specific converters?
Possibly a Xamarin.Forms.ImageSource function toByte()?
Lemme know if you need more information.
TargetImageSource is a Xamarin.Forms.ImageSource.
ImageSource TargetImageSource = null;
Solution (Sten was right)
The ImageSource has to originate from another type to exist, that previous type can be converted to a byte[]. In this case, I use the Xamarin.Forms.Labs to take a picture and it returns a MediaFile in which a FileStream is accessible through the Source property.
//--Upload image
//Initialization
HttpClient httpClient = new HttpClient ();
MultipartFormDataContent formContent = new MultipartFormDataContent ();
//Convert the Stream into byte[]
byte[] TargetImageByte = ReadFully(mediaFile.Source);
HttpContent httpContent = new ByteArrayContent (TargetImageByte);
formContent.Add (httpContent, "image", "image.jpg");
//Send it!
await httpClient.PostAsync ("https://api.magikweb.ca/xxx.php", formContent);
App.RootPage.NavigateTo (new ClaimHistoryPage());
The function:
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream()){
input.CopyTo(ms);
return ms.ToArray();
}
}
I think you're looking at it a bit backwards.
ImageSource is a way to provide a source image for Xamarin.Forms.Image to show some content. If you're already showing something on the screen your Image view was populated with data that came from elsewhere, such as a file or resource or stored in an array in memory... or however else you got that in the first place. Instead of trying to get that data back from ImageSource you can keep a reference to it and upload it as needed.
Maybe you can elaborate a bit on your particular need if you don't feel this solution applies to your case.
Pseudo code:
ShowImage(){
ImageSource imageSource = ImageSource.FromFile("image.png"); // read an image file
xf_Image.Source = imageSource; // show it in your UI
}
UploadImage(){
byte[] data = File.ReadAll("image.png");
// rather than
// byte[] data = SomeMagicalMethod(xf_Image.Source);
HttpClient.Post(url, data);
}
UPDATE:
Since you're taking a picture you can copy the MediaFile.Source stream into a memory stream, then you can reset the memory stream's position to point at the beginning of the stream so that you can read it once again and copy it to the http body.
Alternatively you can store the MediaFile.Source to a file and use ImageSource.FromFile to load it in the UI, and when necessary - you can copy the file's contents into an http post body.
I am currently using a function inside an ASP.Net ASMX web service to generate a System.Drawing.Image. I would like to have this image (after converting to a png or something) passed to the browser as the reply to an AJAX call. (using jQuery's $.ajax). I've been Googling but can't seem to find out how, although I'm pretty sure it's possible. Do I convert it to a Data URI somehow first, or what?
I don't think you can do that. In order to return the image, you should have a method which returns bytearray which I don't think is of any use in javascript.
My workaround is to save the image in a certain location and return the address of the image to clientside.
Update: based on the comments, you can encode the image's data to Base64 string and handle the DATA URI on your ajax callback.
You can use JSON to represent the base64Encoded data, and on the ajax calklback, you can write something like:
$("#myImage").attr("src", "data:image/png;base64,RETURNED_DATA_FROM_ASMX");
Here's a sample code to convert your image to base64 in c#:
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
To find out how to format a DATA URI, you can visit http://en.wikipedia.org/wiki/Data_URI_scheme#Format.
Scenario : ASP.NET site has a page named ShowDesign.aspx.
ASPX page has lot of controls. I have a DIV tag and I load the images in code behind. DIV is defined something like below in the ASPX.
<div id="pImageHolder" runat="server"></div>
Below is the code behind that loads images.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Loop inside PreviewImages which has lots of images.
foreach (String imgFile in this.PreviewImages)
{
Image pImage = new Image();
pImage.ImageUrl = imgFile; //URL length is longer. Do something.
this.pImageHolder.Controls.Add(pImage);
}
}
Update : Jun 1,2012 -> I have updated this question with more clarity as to what I am trying to do.
In OnInit(), I get the URL of the image (in the above loop). Every image will have unique URL.
Since the URL length of every image is longer, it doesn't display. The solution to this issue seems to be POSTING data to the form. The data that needs to be POSTED will be the URL contents.
The URL contains lot of '&' and I need to submit the contents of each '&' to the form.
Don't know if I need to use AJAX or Jquery here.
I need some help here to achieve the above.
Hope my question is clear. If not, please let me know.
According to latest comments, this question history and at the end you want post data to another url and get response html. Try this (I snipped your original url from previous question since is really big):
string strangeUrl = "http://example.com/is/m//company1/Rec-Sc-105-QL2?setAttr.safe={visible=false}&setAttr.insertedTextPlaceholder={visible=false}";
string data = strangeUrl.Substring(strangeUrl.IndexOf("?") + 1);
WebClient wc = new WebClient();
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string result = wc.UploadString("www.example.com/addres-for-post.aspx", data);
I am using crystal reports in a .NET 2.0 asp.net website to create a PDF from the report. I then want to stream the report to the browser, which I already know how to do. What I don't know how to do is target the object tag the will hold the PDF. Does someone know how to do this within HTML with javascript or any other way?
Thanks in advance for any help that can be given.
I wanted to come back and answer this after finding out what I had to do. I had to create a separate aspx page and called it PDFView.aspx. I then added the code to the PageLoad event:
if (!IsPostBack)
{
ReportDocument rpt;
rpt = (ReportDocument)Session["CrystalReport"];
System.IO.Stream myStream;
CrystalDecisions.Shared.ExportOptions myExportOptions;
myExportOptions = myReport.ExportOptions;
myExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
myExportOptions.FormatOptions = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();
CrystalDecisions.Shared.ExportRequestContext myExportRequestContext = new CrystalDecisions.Shared.ExportRequestContext();
myExportRequestContext.ExportInfo = myExportOptions;
//SetReportParameter("pPrinterFriendly", true, (ReportClass)myReport);
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
myStream = myReport.FormatEngine.ExportToStream(myExportRequestContext);
Byte[] myBuffer = new Byte[myStream.Length];
myStream.Read(myBuffer, 0, (int)myStream.Length);
System.Web.HttpContext.Current.Response.BinaryWrite(myBuffer);
System.Web.HttpContext.Current.Response.Flush();
}
I created the report object setting all parameters and datasource in the calling aspx page and the wrote the report to a session variable for retrieval when the PDFView.aspx page is loaded. I then used the code above to retrieve, execute and stream the report as a binary stream "the binary PDF" to the browsers response stream.
The PDFView.aspx page is referenced in the calling page with an object tag like this:
<object id="pdfObj" type="application/pdf" style="width:60%;height:95%;position:relative;top:2%;left:0%;right:10%;bottom:10%;margin:0px;padding:0px;border:0px;" data="PDFView.aspx"></object>
I am screen scraping a webpage and sending it as a html email.
What is the easiest/best way to manipulate the html to set full http addresses for all images and css files?
Current method is similar to (manually typed) + this is very open to error.
string html = rawHtml.replace("=\"", "=\"" + Request["SERVER_NAME"]);
.
.
Here is the current function we use to screen scrape using GET
public static string WebGet(string address)
{
string result = "";
using (WebClient client = new WebClient())
{
using (StreamReader reader = new StreamReader(client.OpenRead(address)))
{
string s = reader.ReadToEnd();
result = s;
}
}
return result;
}
It sounds like what you need is an HTML parser. Once you parse the html string with the parser, you can execute commands that easily manipulate the DOM, and thus you could find all img elements, check their src and append the Request["SERVER_NAME"] if you need to.
I don't code in ASP, but I found this:
http://htmlagilitypack.codeplex.com/
And here is a useful article I found explaining how to use it:
https://web.archive.org/web/20211020001935/https://www.4guysfromrolla.com/articles/011211-1.aspx