日期:2014-05-19  浏览次数:20824 次

抓取网页图片问题
请问怎么用C#程序实现抓取网页上的图片?
然后把该图片保存为相应格式(jpg、gif…)?
可以的话麻烦给出代码~多谢啦!!!

------解决方案--------------------
http://blog.csdn.net/hertcloud/archive/2007/03/14/1528971.aspx

通过HttpWebResponse和HttpWebRequest 获取http地址上的图片
------解决方案--------------------

主要思想:
使用IE控件先显示网页,然后使用API函数将其绘画内容写入image对象,然后保存。
主要函数,传入IE控件
public static Image Capture(Control control, ImageSettingInfo imageInfo)

codeproject有个示例,可以拍摄一个很大的网页的图片,我这个只能拍摄当前显示的内容,但可以拍摄任何控件。

以下是代码:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Drawing.Imaging;

using BaseFrame.ShareFunction;

namespace BaseFrame.Images
{
/// <summary>
/// 捕获窗口的影响
/// </summary>
public sealed class CaptureImage
{
// Violates rule: StaticHolderTypesShouldNotHaveConstructors.
// Uncomment the following line to correct the violation.
private CaptureImage() { }

[DllImport( "user32.dll ")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern Boolean PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

#region 常量
/// <summary>
/// 画图开始X坐标
/// </summary>
public const int BRWTOP = 0;
/// <summary>
/// Y坐标
/// </summary>
public const int BRWLEFT = 0;
/// <summary>
/// 图片质量
/// </summary>
public const long QUALITY = 100;
/// <summary>
/// 原图大小
/// </summary>
public const double RESOLUTION = 1.0;
#endregion

//public delegate void CaptureHandler();

//public static event CaptureHandler CaptureImageEvent;

//public delegate void ThumbnailHandler();

//public static event ThumbnailHandler ThumbnailImageEvent;

public static Image Capture(Control control, ImageSettingInfo imageInfo)
{
Debug.Assert(control != null);
if (control == null)
{
throw new ArgumentNullException( "control is null ");
}
Debug.Assert(imageInfo != null);
if (imageInfo == null)
{
throw new ArgumentNullException( "imageInfo is null ");
}

IntPtr hwnd = control.Handle;
//Get bitmap to hold screen fragment.
Bitmap bm = null;

Graphics g = null;
IntPtr hdc;
//Image screenfrag = null;

Bitmap finalImage = null;

Image originalImage = null;
try
{
// 计算最终图片大小
int finalWidth = (int)((imageInfo.ImageWidth) * RESOLUTION);
int finalHeight = (int)((imageInfo.ImageHeight) * RESOLUTION);

bm = new Bitmap(finalWidth, finalHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

g = Graphics.FromImage(bm);

hdc = g.GetHdc();

// 绘画目标窗口到 hdc