Pull to refresh

Скачиваем альбомы из Picasa

Reading time12 min
Views1.1K
Собственно все довольно просто:

1. Качаем и ставим Google API [Google.GData.Client.dll, Google.GData.Extensions.dll, Google.GData.Photos.dll]

2. Создаем новый проект на C# (я использую WinForms)
3. Заведем класс основной логики:



using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Extensions.MediaRss;
using Google.GData.Photos;
using System.Drawing;

namespace PicasaAlbumDownloader.Classes
{
  class MainLogic
  {
    private WebClient webClient = new WebClient();

    //Загружаем Альбомы в Список
    public AtomEntryCollection LoadAlbumList(string Login)
    {
      AlbumQuery aQuery = new AlbumQuery(PicasaQuery.CreatePicasaUri(Login));
      PicasaService pService = new PicasaService("PicasaService");
      AtomFeed kResultFeed = pService.Query(aQuery);

      return kResultFeed.Entries;
    }

    //Загружаем превью в ListView
    public ListViewItem[] LoadThumbnailsForListView(string Login, string AlbumTitle)
    {
      ListViewItem[] listViewItems = new ListViewItem[] {};

      AlbumQuery aQuery = new AlbumQuery(PicasaQuery.CreatePicasaUri(Login));
      PicasaService pService = new PicasaService("PicasaService");
      AtomFeed kResultFeed = pService.Query(aQuery);

      for (int i = 0; i < kResultFeed.Entries.Count; i++)
      {
        if (kResultFeed.Entries[i].Title.Text != AlbumTitle) continue;

        PicasaEntry picasaEntry = (PicasaEntry) kResultFeed.Entries[i];
        AtomEntry atomEntry = kResultFeed.Entries[i];

        if (!picasaEntry.IsAlbum) continue;

        AtomLinkCollection atomLinkCollection = atomEntry.Links;

        if (atomLinkCollection != null)
        {
          if (atomLinkCollection[1] != null)
          {
            if (!String.IsNullOrEmpty(atomLinkCollection[1].AbsoluteUri))
            {
              int LastSlash =
                atomLinkCollection[1].AbsoluteUri.LastIndexOf('/') + 1;

              listViewItems =
                LoadThumbsForAlbum(Login,
                atomLinkCollection[1].AbsoluteUri.Substring(LastSlash));
            }
          }
        }

        break;
      }

      return listViewItems;
    }

    //Загружаем превьюшки рисунков
    public static ListViewItem[] LoadThumbsForAlbum(string Login, string AlbumName)
    {
      AlbumQuery aQuery = new AlbumQuery(PicasaQuery.CreatePicasaUri(Login, AlbumName));
      PicasaService pService = new PicasaService("PicasaService");
      aQuery.KindParameter = "";

      AtomFeed kResultFeed = pService.Query(aQuery);

      ListViewItem[] listViewItems = new ListViewItem[kResultFeed.Entries.Count];
      for (int i = 0; i < kResultFeed.Entries.Count; i++)
      {
        PicasaEntry entry = kResultFeed.Entries[i] as PicasaEntry;

        if (entry != null)
        {
          PicasaEntry picasaEntry = kResultFeed.Entries[i] as PicasaEntry;
          AtomEntry atomEntry = kResultFeed.Entries[i];

          string PictureTitle = atomEntry.Title.Text;
          ThumbnailCollection thumbnailCollection = entry.Media.Thumbnails;
          MediaThumbnail Picture = thumbnailCollection[0];

          string BigPhoto = Picture.Attributes["url"].ToString();
          if (picasaEntry != null)
          {
            if (picasaEntry.IsPhoto)
            {
              BigPhoto = picasaEntry.Content.Src.Content;
            }
          }

          listViewItems[i] = new ListViewItem(PictureTitle, BigPhoto);
        }
      }

      return listViewItems;
    }

    //Загружаем Данные в PictureBox
    public Image DownloadPicture(string PictureUrl)
    {
      Image image = null;
      webClient = new WebClient();

      Stream PictureRaw = webClient.OpenRead(PictureUrl);
      image = Image.FromStream(PictureRaw);

      PictureRaw.Close();
      PictureRaw.Dispose();

      return image;
    }

    /// <summary>
    /// Качаем Файлы.
    /// </summary>
    /// <param name="FromUrl">From URL.</param>
    /// <param name="FullName">The full name.</param>
    public void DownloadFile(string FromUrl, string FullName)
    {
      if (File.Exists(FullName)) File.Delete(FullName);
      if (File.Exists(FullName)) return;

      webClient = new WebClient();
      webClient.DownloadFile(new Uri(FromUrl), FullName);
      webClient.Dispose();
    }

    //Проверяем все ли загружено, ставим флаги
    public static bool CheckIntArrayOfDownloads(int[] Array)
    {
      for (int i = 0; i < Array.Length; i++)
      {
        if (Array[i] == 0) return true;
      }

      return false;
    }

    //Парсим путь для загрузки
    public static string GetFullName(string DownloadPath, string album_image_to_parse)
    {
      int LastSlash = album_image_to_parse.LastIndexOf('/') + 1;
      string FileName = album_image_to_parse.Substring(LastSlash);
      string FullName = String.Concat(DownloadPath, @"\", FileName);

      return FullName;
    }
  }
}

* This source code was highlighted with Source Code Highlighter.


4. Создаем формочку главного окна.

На форме у меня используются:

txtLogin — текстовое поле
btnLogin — кнопка загрузки списка альбомов
pctTitle — лейбл для вывода заголовка
album_list — листбокс для вывода списка альбомов
pictureBox1 — отображаем картинку
albumThumbs — листвью для показа превьюшек но пока вывожу только названия файлов.

pictureMenu (вешается на картинку) и albumMenu (вешается на список альбомов) — контекстные менюшки.

5. Код формы:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Google.GData.Client;
using PicasaAlbumDownloader.Classes;

namespace PicasaAlbumDownloader
{
  public partial class MainForm : Form
  {
    private readonly MainLogic MainLogic = new MainLogic();
    private Image CurrentPhoto { get; set; }
    private readonly List<String> album_big_images = new List<string>();

    public MainForm()
    {
      InitializeComponent();
    }

    //Загружаем Лист Альбомов
    private void btnLogin_Click(object sender, EventArgs e)
    {
      AtomEntryCollection AlbumListAtomFormat = null;

      //Пробуем подгрузить список
      try
      {
        AlbumListAtomFormat = MainLogic.LoadAlbumList(txtLogin.Text);
      }
      catch (GDataRequestException)
      {
        MessageBox.Show("Видимо Вы не соеденились с интернетом");
      }

      //Если ничего не получили
      if (AlbumListAtomFormat == null) return;

      try
      {
        album_list.Items.Clear();

        //Начинаем заполнение листа
        album_list.BeginUpdate();

        foreach (AtomEntry entry in AlbumListAtomFormat)
        {
          album_list.Items.Add(entry.Title.Text);
        }

        album_list.EndUpdate();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }

    }

    //Выбираем Альбом
    private void album_list_SelectedIndexChanged(object sender, EventArgs e)
    {
      albumThumbs.Clear();
      album_big_images.Clear();

      ListViewItem[] listViewItems =
        MainLogic.LoadThumbnailsForListView(txtLogin.Text,
                          album_list.SelectedItem.ToString());

      //Добавим ключи больших картинок на будущее....
      foreach (ListViewItem listViewItem in listViewItems)
      {
        album_big_images.Add(listViewItem.ImageKey);
      }

      //подключим таки наши названия и ключи
      albumThumbs.Items.AddRange(listViewItems);
    }

    //Смотрим картинки
    private void albumThumbs_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (albumThumbs.SelectedItems.Count == 0) return;

      string PictureTitle = albumThumbs.SelectedItems[0].Text;
      string PictureUrl = albumThumbs.SelectedItems[0].ImageKey;

      pctTitle.Text = PictureTitle;
      Image TempImage = MainLogic.DownloadPicture(PictureUrl);

      if (TempImage != null)
      {
        CurrentPhoto = TempImage;
        pictureBox1.Image = TempImage;
      }
      else
      {
        MessageBox.Show("не удалось загрузить картинку попробуйте еще раз");
      }
    }

    //Сохраняем Картинку
    private void mnuPictureboxSave_Click(object sender, EventArgs e)
    {
      if (CurrentPhoto == null) return;

      SaveFileDialog saveFileDialog = new SaveFileDialog
                        {
                          DefaultExt = "jpg",
                          Filter = "Jpeg File (*.jpg)|*.jpg)"
                        };

      DialogResult SaveDialog = saveFileDialog.ShowDialog(this);
      if (SaveDialog != System.Windows.Forms.DialogResult.OK) return;
      if (File.Exists(saveFileDialog.FileName)) File.Delete(saveFileDialog.FileName);

      CurrentPhoto.Save(saveFileDialog.FileName);
    }

    //Сохраняем весь Альбом
    private void menuDownloadAllAlbum_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
      DialogResult dialogResult = folderBrowserDialog.ShowDialog(this);

      if (DialogResult.OK != dialogResult) return;

      string DownloadPath = folderBrowserDialog.SelectedPath;
      int[] DownloadedFiles = new int[album_big_images.Count];

      for (int i = 0; i < album_big_images.Count; i++)
      {
        string FullName = MainLogic.GetFullName(DownloadPath, album_big_images[i]);
        MainLogic.DownloadFile(album_big_images[i], FullName);
        DownloadedFiles[i] = 0;
      }

      do
      {
        for (int i = 0; i < album_big_images.Count; i++)
        {
          string FullName = MainLogic.GetFullName(DownloadPath, album_big_images[i]);
          if (File.Exists(FullName)) DownloadedFiles[i] = 1;
        }

        Application.DoEvents();
      }
      while (MainLogic.CheckIntArrayOfDownloads(DownloadedFiles));

      MessageBox.Show("Весь Альбом Скачен!");
    }

    //Проверяем есть ли картинка для сохранения
    private void pictureMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
    {
      mnuPictureboxSave.Enabled = CurrentPhoto != null;
    }

    //Проверяем а если загруженные альбомы
    private void albumMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
    {
      albumMenu.Enabled = albumThumbs.SelectedItems.Count != 0;
    }
  }
}

* This source code was highlighted with Source Code Highlighter.


P.S

Текстовое поле логин вернее назвать галерея,
просто когда делал проект думал нужен будет логин.

Скачать исходники проекта
Tags:
Hubs:
Total votes 42: ↑29 and ↓13+16
Comments23

Articles