Copying image from page results in black image

2019-08-09 13:35发布

问题:

I have a program that copies images from a webpage and saves them locally. On certain webpages the saved image is a completely black screen. First I thought it was a problem in the code that didn't take the good picture. So I started investigating. I went manually to those pages and tried to copy the image(right click, copy image) and it still returned a black image. Can someone tell me how can I bypass this from code? Here is the current code, which works fine for most of the pictures

IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
        IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();

        foreach (IHTMLImgElement img in doc.images)
        {
            if (img.alt != "my image alt")
                continue;
            imgRange.add((IHTMLControlElement)img);

            imgRange.execCommand("Copy", false, null);

            using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
            {
                if (bmp != null)
                {
                    bmp.Save("testimg.jpg");
                }
            }
        }

回答1:

That image has a transparent background.
Therefore, every pixel in the image is black, except that most of them are fully transparent.

Since .jpg files do not support transparency, saving it as a .jpg results in a black image.

If you save it as a .png file (which does support transparency), it should work.