Solved

convert html string to an image dynamically (continue2)

Posted on 2009-05-13
8
773 Views
Last Modified: 2012-05-06
I want to use following code (see also related question)  to creata dynamically an image from html.
How do I change it so that it works for web application (C#)?


[STAThread()]  << -- attribute
protected void Page_Load(object sender, EventArgs e)
{
 System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
      wb.Size = new System.Drawing.Size(1024, 768);
      wb.ScrollBarsEnabled = false;
 
      wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(delegate(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) {
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(wb.ClientRectangle.Width, wb.ClientRectangle.Height);
        wb.DrawToBitmap(bmp, new System.Drawing.Rectangle(0,0, bmp.Width, bmp.Height));
        bmp.Save(@"c:\foo.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
      });
      wb.Navigate(@"file://c:\my.html");
      //wb.Navigate("http://www.google.com"); 
 
}

Open in new window

0
Comment
Question by:johnkainn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 15

Expert Comment

by:oobayly
ID: 24380430
What do you mean by "so that it works"? Are you wanting to use the page to save the image on the webserver, or return the resulting image to the client?

If it's the latter, you could modify the code to write the bitmap to a member variable. Then poll the result until it's valid & write it to the response.

I'd suggest saving local copies of the image, and check for them first. That way you don't have to recreate the image each time.
private Bitmap bmp;
 
[STAThread()]  << -- attribute
protected void Page_Load(object sender, EventArgs e) {
  System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser(); 
  wb.Size = new System.Drawing.Size(1024, 768);
  wb.ScrollBarsEnabled = false;
 
  wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(delegate(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) {
    bmp = new System.Drawing.Bitmap(wb.ClientRectangle.Width, wb.ClientRectangle.Height);
    wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(delegate(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) {
      System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(wb.ClientRectangle.Width,  wb.ClientRectangle.Height);
      wb.DrawToBitmap(bmp, new System.Drawing.Rectangle(0,0, bmp.Width, bmp.Height));
  });
  wb.Navigate(@"file://c:\my.html");
 
  // Wait for the download to complete 
  while (bmp == null){
    Thread.Sleep(50);
  }
  
  // Write to a PNG (stream needs to be seekable)
  MemoryStream ms = new MemoryStream();
  bmp.Save(ms, ImageFormat.Png);
  
  // Send the image to the client
  Response.ContentType = "image/png";
  ms.WriteTo(Response.OutputStream);
  
  ms.Dispose();
  bmp.Dispose();
}

Open in new window

0
 

Author Comment

by:johnkainn
ID: 24383145
I want to save the image to a webserver.
I get an error using System.Windows.Forms.WebBrowser
( The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)  )
How should I write it so it works for web application?
0
 
LVL 23

Expert Comment

by:Tony McCreath
ID: 24384649
I've been trying to get this to work.

The STAThread attribute didn't work for me so I added AspCompat="true" to the Page....

<%@ Page ... AspCompat="true"  %>

And you need to add a reference the System.Windows.Forms

At the moment I can't get the Navigate(url) to trigger anything. I've added event handers to DocumentCompleted, ProgressChanged and StatusTextChanged. non of them fire.

oobayly, your version of the code has nested DocumentCompleted events, is this correct?


		System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
		wb.Size = new System.Drawing.Size(1024, 768);
		wb.ScrollBarsEnabled = false;
 
		wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.DocumentCompleted);
 
		wb.ProgressChanged += new WebBrowserProgressChangedEventHandler(wb_ProgressChanged);
 
		wb.StatusTextChanged += new EventHandler(wb_StatusTextChanged);
 
		wb.Navigate(url);
 
		// Wait for the download to complete 
		while (this.bmp == null)
			Thread.Sleep(50);
 
 
		// Write to a JPG (stream needs to be seekable)
		MemoryStream ms = new MemoryStream();
		bmp.Save(ms, ImageFormat.Jpeg);
 
		// Send the image to the client
		this.Response.ContentType = "image/jpg";
		ms.WriteTo(this.Response.OutputStream);
 
		ms.Dispose();
		bmp.Dispose();

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Assisted Solution

by:oobayly
oobayly earned 200 total points
ID: 24386480
@Tiggerito
Nope, that was a mistake. Didn't have VS on the machine, so used Notepad2, and didn't catch that.

I've had a browse through my code & found this class. It doesn't seem to work with some sites though, but it is a start.
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
 
public class WebScreenshot {
  private Bitmap bmp;
  private Size size;
 
  [DefaultValue(typeof(Size), "1024,768")]
  public Size Size {
    get { return size; }
    set { size = value; }
  }
  
  public Bitmap GetScreenshot(string uri) {
    return GetScreenshot(new Uri(uri));
  }
 
  public Bitmap GetScreenshot(Uri uri) {
    /* Start the GetScreenshot method in a single-apartment thread
     * Pass the Uri as the parameter
     * Wait for the thread to join to make the method act synchronously
     */
    Thread td = new Thread(new ParameterizedThreadStart(GetScreenshot));
    td.SetApartmentState(ApartmentState.STA);
    td.Start(uri);
    td.Join();
 
    return bmp;
  }
 
  private void GetScreenshot(object uri) {
    // Create the browser object using the desired size
    WebBrowser wb = new WebBrowser();
    wb.Size = size;
    wb.ScrollBarsEnabled = false;
 
    // Navigate to the Uri & wait for it to finish downloading
    wb.Navigate(uri as Uri);
    while (wb.ReadyState != WebBrowserReadyState.Complete) {
      System.Windows.Forms.Application.DoEvents();
    }
 
    // Draw the rendered html to the bitmap
    bmp = new System.Drawing.Bitmap(wb.ClientRectangle.Width, wb.ClientRectangle.Height);
    wb.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
  }
 
  public WebScreenshot() : this(new Size(1024, 768)) { }
 
  public WebScreenshot(int width, int height) : this(new Size(width, height)) { }
  
  public WebScreenshot(Size size) {
    this.size = size;
  }
}

Open in new window

0
 

Author Comment

by:johnkainn
ID: 24394855
Thanks. Unfortunately I am getting errors when I try to run this code.

0
 
LVL 23

Expert Comment

by:Tony McCreath
ID: 24395173
johnkainn,

could you explain what the errors are!
0
 

Author Comment

by:johnkainn
ID: 24405765
I get following errors:
1)  Error    18    The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?)

2) Error    17    The name 'WebBrowserReadyState' does not exist in the current context    

3) Error    16    The type or namespace name 'Uri' could not be found (are you missing a using directive or an assembly reference?)    

4) Error    15    The type or namespace name 'WebBrowser' could not be found (are you missing a using directive or an assembly reference?)    






0
 
LVL 23

Accepted Solution

by:
Tony McCreath earned 300 total points
ID: 24405913
Th first error is that you havent included a reference to the System.Windows.Forms dll.

Add a reference to it. You should see menu options at the project level.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question