Place Image from DLL onto a web page - c#

I'm so stuck on something i thought would be easy.
I have a DLL that returns an Image object.
I just cant figure out how to display that image on a webpage.
I've tried a few ways, and google a million different variations.
Is it not possible to just bind an Image object to an element on the page like an HtmlImage or a simple img?
Or do i need to convert the Image to a Stream? or a Bitmap? I'm really stuck!
Any help appreciated.....
V

With Asp.Net WebForm, the easiest way is to create a custom ashx file.
In Visual Studio, create a new Custom Handler (I'm not sure of the name of the template in Visual Studio). This will create a .ashx file.
In the code of this handler, write something like (does not have VS under the hand to test the syntax) :
public void ProcessRequest(System.Web.HttpContext context)
{
byte[] raw;
using(var ms = new MemoryStream()){
Image myImage = GetFromDll();
myImage.Save(ms, ImageFormat.Png);
raw=ms.ToArray();
}
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(raw);
}
Then, in your browser, navigate to http://yourserver/app/yourhandler.ashx.
You can if you want add url parameter, and get it from the Request.QueryString collection

It's not as simple as binding. On the client side images are retrieved from the web server as a separate GET request, which means you have to have a URL that resolves to an image. The other option, as Asif suggested, is embedding your image in the HTML as a Base64 string, which is bad practice for shared images (see Steve B's comment).
You either have to provide an URL (route that returns the image file in MVC, or a custom page with proper content type and Response.Write in WebForms), or embed in html.
EDIT:
There is also a third option involving custom HTTP handlers. These have the advantage of bypassing the app framework and serving the content almost directly off the web server, see MSDN.

Convert your image to base64 string and then set it in the <img/> tag.
<img/> can show the image in base64 string.
Alternatively you can save the image and use the path in the <img/>.

Related

Serve Image with IHttpHandler

I am working with a web server that is only available on our internal network. I have a need to make an image it serves available to the public via our DMZ web server. The internal system has a GUI where anyone can upload any type of image so my HttpHandler must be flexible.
The bit of code I am currently using is:
WebResponse webResponse = WebRequest.Create(imagePath).GetResponse();
using (Stream stream = webResponse.GetResponseStream())
{
context.Response.Clear();
context.Response.ContentType = webResponse.ContentType;
stream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
This seems to work and it serves up images correctly on HTML pages, but when I right click in Chrome and select "Open image in new tab" I get garbled up text like this:
Any suggestions to make my code better or is this okay?
Thanks!
EDIT: Seems like this code snippet does exactly what it should do. The problem was with the internally hosted image itself. It Served the exact same garbled text even before running through this HttpHandler.
Your content type header is probably not being set correctly.
Change it to context.Response.ContentType = "image/png";, but replace "png" with whatever the image time you are loading happens to be.

Converting aspx page to image file

I have c# dynamic aspx page after new property add I create for record brochure
http://veneristurkey.com/admin/Brochure.aspx?Admin=PropertiesBrochureA4&id=36
but I want to this convert image file I am searching on internet but all with webbrowser and windows forms. I need on page load show not css type also image file. jpg, png or tiff how i can do this. i need to see sample code..
saving aspx page into an image 2
As I mentioned in my comment, your best bet is to opt for attempting to render HTML to an image.
Here is the link for a library that will allow your to render html to an image:
http://htmlrenderer.codeplex.com/
Here is code that does exactly what you're asking:
http://amoghnatu.wordpress.com/2013/05/13/converting-html-text-to-image-using-c/
Now all you have left is to get the html, since I'm assuming you don't want this to render to the browser prior to generating this image - you should look into grabbing the rendered html from the aspx page on the server prior to returning it, and then just return the image. To render a page:
https://stackoverflow.com/a/647866/1017882
Sorted.
If you do not mind using a commandline tool you can have a look at wkhtmltopdf. The package include a wkhtmltoimage component that can be used to convert HTML to image, using
wkhtmltoimage [URL] [Image Path]
Codaxy also wrote a wkhtmltopdf c# wrapper available through the NuGet package manager. I'm not sure if the wkhtmltoimage component was included, but it should be easy enough to figure out how they wrap the wkhtml components.
i fixed my problem with screenshot machine API they are my code..
public void resimyap()
{
var procad = WS.Satiliklars.Where(v => v.ForSaleID == int.Parse(Request.QueryString["id"])).FirstOrDefault();
var imageBytes = GetBytesFromUrl("http://api.screenshotmachine.com/?key=xxxxxx&size=F&url=http://xxxxxxx.com/a4.aspx?id=" + procad.ForSaleID);
string root = Server.MapPath("~/");
// clean up the path
if (!root.EndsWith(#"\"))
root += #"\";
// make a folder to store the images in
string fileDirectory = root + #"\images\a4en\";
// create the folder if it does not exist
if (!System.IO.Directory.Exists(fileDirectory))
System.IO.Directory.CreateDirectory(fileDirectory);
WriteBytesToFile( fileDirectory + + procad.ForSaleID + ".png", imageBytes);
Yes i also try wkhtmltopdf c# wrapper but in pdf or image converting time my computer fan goin crayz. also i must upload server exe file and my hosting firm didnt support them

How to Fetch and Display an Image from the Database in ASP.Net and C#

There are so many good tutorials out there about inserting an image inside a table in a database, using the FileUpload controller.
Yet I cannot find a good tutorial about how to fetch these images and display them.
When I used to store the image name or path in the database (as a Varchar), It would be very simple by doing something like this...
HTML/ASP:
<img src="" runat="server" id="myImage" />
C#:
myImage.Src = myReader.getValue(0).toString();
The Result:
<img src="/Images/pic.png" runat="server" id="myImage" />
And Voila, the picture will be displayed.
But Now I would like to fetch uploaded images, not a path, means the type of the table column is IMAGE.
Some tutorials will eventually lead to display a picture in FULL SCREEN.
I do not want that, I simply want to fetch and display the image the same way it is displayed in the previous example, with a given size and place inside my web page.
Why am I uploading images to the database? Because these images are "Profile Pictures", not public pictures, I do not want a guest to simply browse for /Images/ to find all the pictures of my web site, public and private.
First of all, to do what you want, I would just copy the file to a temporary location and use that location for the "src" attribute. Later, you could delete the file. The much more complicated way is to create an aspx page that writes the image to the webpage as a binary stream. This page would grab the image from the database and just write the stream out in the response. You would then use this aspx page in the src attribute of your image. However, storing the image path in the database and actual file on the file system doesn't mean that the folder has to be browse-able or public. You can turn directory browsing off for example.
Create a custom IHttpHandler implementation that can serve your images from your database. You could, for example, get the bytes into a stream and copy that stream to the output of the web response.
Here is a simple example:
public class MyImageHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
Stream yourStream = ...; // This is where you get your data from your database
ctx.Response.ContentType = "image/jpeg";
yourStream.CopyTo(ctx.Response.OutputStream);
}
}
Then you need to configure it to respond to the URLs you wish.
You could either use the Web.config file to do this
Or create an .ashx file and have it point to your own HTTP handler
If you have any questions about it, just write a comment.
You will need an aspx page reading the image from the database and returning the raw bytes.
Here's a quick sketch how to do this:
byte[] data = (byte[])myReader.getValue(0);
Response.ContentType = "image/jpeg"; //or whatever your used image type is
Response.OutputStream.Write(data, 0, data.Length);
Response.End();
An alternative would be to implement a custom HttpHandler for this.
The other part is "calling" this page from your img tags with a parameter specifying the image id:
myImage.Src = "/image.aspx?id=" + myReader.getValue(0).toString();

How to get raw page source (not generated source) from c#

The goal is to get the raw source of the page, I mean do not run the scripts or let the browsers format the page at all. for example: suppose the source is <table><tr></table> after the response, I don't want get <table><tbody><tr></tr></tbody></table>, how to do this via c# code?
More info: for example, type "view-source:http://feeds.gawker.com/kotaku/full" in the browser's address bar will give u a xml file, but if you just call "http://feeds.gawker.com/kotaku/full" it will render a html page, what I want is the xml file. hope this is clear.
Here's one way, but it's not really clear what you actually want.
using(var wc = new WebClient())
{
var source = wc.DownloadString("http://google.com");
}
If you mean when rendering your own page. You can get access the the raw page content using a ResponseFilter, or by overriding page render. I would question your motives for doing this though.
Scripts run client-side, so it has no bearing on any c# code.
You can use a tool such as Fiddler to see what is actually being sent over the wire.
disclaimer: I think Fiddler is amazing

How do i URL rewrite an image properly? C# ASP.NET

I tried several ways to URL rewrite. The first way the image mime was clobbered and was consider an octet stream which didnt allow me to view the image in a browser (unless it was using img src). The 2nd way i wasnt convince it worked. Firefox displayed the img but said the length was 0 (i think it only worked bc it was in my cache).
How do i properly rewrite the image /abc/id/title.png to the internal location /static/user/name/id.png
In ASP.NET I might do something like this:
Response.Clear();
Response.ContentType = profile.AvatarMimeType;
Response.BinaryWrite(profile.Avatar.ToArray());
Where profile.AvatarMimeType is an appropriate mime type for a gif, jpeg, or png.
And where profile.Avatar.ToArray() is a binary content from the db sent out as an array of data!

Categories