Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c# - Saving images from a WebBrowser Control

The following code runs, but the Bitmap generated is shifted down about half an inch and cutoff at the bottom. I checked the image width and height and it is creating an image of the correct size, just the image contents are shifted down and cutoff. I'm stumped... any ideas?

    using mshtml;
    using System.Drawing;
    using System.Runtime.InteropServices;

    [ComImport, InterfaceType((short)1), Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
    private interface IHTMLElementRenderFixed
    {
        void DrawToDC(IntPtr hdc);
        void SetDocumentPrinter(string bstrPrinterName, IntPtr hdc);
    }

    public Bitmap GetImage(string id)
    {
        HtmlElement e = webBrowser1.Document.GetElementById(id);
        IHTMLImgElement img = (IHTMLImgElement)e.DomElement;
        IHTMLElementRenderFixed render = (IHTMLElementRenderFixed)img;

        Bitmap bmp = new Bitmap(img.width, img.height);
        Graphics g = Graphics.FromImage(bmp);
        IntPtr hdc = g.GetHdc();
        render.DrawToDC(hdc);
        g.ReleaseHdc(hdc);

        return bmp;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are doing is rendering the image as it is rendered by the browser with all the styles. I don't know if this is what your realy want? If you only want to download the image then it is easier to solve it with a web request as described in hte other answers.

If you realy want to render than the first step is to change

Bitmap bmp = new Bitmap(img.width, img.height);

to

Bitmap bmp = new Bitmap(e.OffsetRectangle.Width, e.OffsetRectangle.Height);

Now you get the complete rendered web browser image.

If you want a perfect solution even for big images you also have to scroll around and get the image tile by tile.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...