首页 > 代码库 > 下载网页中的图片到本地
下载网页中的图片到本地
简单的一个下载如下 :
string url = "http://avatar.csdn.net/A/2/6/2_yefengzhixia.jpg"; string filepath = "D:\\pic.jpg"; WebClient mywebclient = new WebClient(); mywebclient.DownloadFile(url, filepath); MessageBox.Show("OK");
下面演示一个从网站中下载所有图片到本地:
1、界面设计:
<Grid> <DockPanel> <GroupBox x:Name="groupBox" Header="图片网址" DockPanel.Dock="Top"> <StackPanel> <StackPanel Orientation="Horizontal" Margin="10" > <Button x:Name="button" Content="查看网页中的图片" Margin="5" Click="button_Click" /> <TextBlock Text="网址:"></TextBlock> <TextBox x:Name="textBox" Text="http://www.tooopen.com/img/87.aspx" HorizontalAlignment="Left" MaxWidth="600" TextWrapping="Wrap" MinWidth="300" VerticalAlignment="Top" /> </StackPanel> <TextBlock Text="下载信息:"></TextBlock> <TextBlock Margin="10" Name="txtcount" Text="{Binding downCount}"> </TextBlock> <TextBlock Name="total"></TextBlock> <Button Click="Button_Click_1" Content="打开下载图片文件夹"></Button> </StackPanel> </GroupBox> <ListBox Name="lb"></ListBox> </DockPanel> </Grid>
2、代码
public partial class MainWindow : Window,INotifyPropertyChanged { public MainWindow() { InitializeComponent(); this.DataContext = this; } private int c; public int downCount { get { return c; } set { c = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("downCount")); } } public ObservableCollection<string> list = new ObservableCollection<string>(); public event PropertyChangedEventHandler PropertyChanged; private async void button_Click(object sender, RoutedEventArgs e) { var path = textBox.Text; if (string.IsNullOrWhiteSpace(path)) { textBox.Focus(); MessageBox.Show("请输入网站地址"); return; } HttpClient client = new HttpClient(); var str = await client.GetStringAsync(new Uri(path)); Regex rg = new Regex("<img.+?src=http://www.mamicode.com/"(.+?)\""); var mth = rg.Matches(str); WebClient wc = null; int i = 0; total.Text="共有图片:"+mth.Count; Action<string> listboxAddImgName = x => { lb.Items.Add(x); }; foreach (Match item in mth) { i++; var img = item.Groups[1].Value; string Ex = img.Substring(img.LastIndexOf(".")); string imgName = i + Ex; Task.Run(() => { wc = new WebClient(); wc.DownloadFile(img, "DownLoadImages/" + imgName); return imgName; }).ContinueWith(r=> { downCount +=1; Dispatcher.Invoke(listboxAddImgName,r.Result); }); } } private void Button_Click_1(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(Environment.CurrentDirectory+"/DownLoadImages"); } }
下载网页中的图片到本地
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。