Web From 擷圖

2013年3月14日 星期四

今天主管要評估一個需求,那就是可不可以做跟PChome一樣,可以把網頁畫面擷取下來存成圖檔 於是就展開了一段漫長的尋找,雖然網路上也一些api可以用,但我還是找到方法 原理:先載入要擷圖的url,在利用window.from的WebBrowser元件來將網頁轉成圖片 來看一下code 吧

protected void btn1_Click(object sender, EventArgs e)
{
string url = "http://tw.yahoo.com";
Bitmap bitmap = new Bitmap(CaptureWebPage(url));
Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
bitmap.Dispose();
Response.End();
}

public System.Drawing.Bitmap CaptureWebPage(string URL)
{
// create a hidden web browser, which will navigate to the page
System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser();
// we don't want scrollbars on our image
web.ScrollBarsEnabled = false;
// don't let any errors shine through
web.ScriptErrorsSuppressed = true;
// let's load up that page!
web.Navigate(URL);

// wait until the page is fully loaded
while (web.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
System.Threading.Thread.Sleep(1500); // allow time for page scripts to update
// the appearance of the page

// set the size of our web browser to be the same size as the page
int width = web.Document.Body.ScrollRectangle.Width;
int height = web.Document.Body.ScrollRectangle.Height;
web.Width = width;
web.Height = height;
// a bitmap that we will draw to
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
// draw the web browser to the bitmap
web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height));

return bmp; // return the bitmap for processing
}


執行後會發生"無法產生 ActiveX 控制項 '8856f961-340a-11d0-a96b-00c04fd705a2',因為目前的執行緒不是在單一執行緒 Apartment。" 的問題 “



解決方法,可以至.aspx 加入 AspCompat=”ture



<%@ Page Title="首頁" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default"  AspCompat="true"%>

0 意見: