PhotosSearch() public method

Search for a set of photos, based on the value of the PhotoSearchOptions parameters.
public PhotosSearch ( PhotoSearchOptions options ) : Photos
options PhotoSearchOptions The parameters to search for.
return Photos
コード例 #1
1
ファイル: Program.cs プロジェクト: jjbott/SyncTool
        static void Main(string[] args)
        {
            Flickr flickr = new Flickr(FlickrKey.Key, FlickrKey.Secret);
            Auth auth = null;
            if (File.Exists("key.txt"))
            {
                using (var sr = new StreamReader("key.txt"))
                {
                    flickr.OAuthAccessToken = sr.ReadLine();
                    flickr.OAuthAccessTokenSecret = sr.ReadLine();
                }

            }

            if (!string.IsNullOrEmpty(flickr.OAuthAccessToken) &&
                 !string.IsNullOrEmpty(flickr.OAuthAccessTokenSecret))
            {
                auth = flickr.AuthOAuthCheckToken();
                int g = 56;
            }
            else
            {
                var requestToken = flickr.OAuthGetRequestToken("oob");
                var url = flickr.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Delete);
                Process.Start(url);

                var verifier = Console.ReadLine();

                OAuthAccessToken accessToken = flickr.OAuthGetAccessToken(requestToken, verifier);
                flickr.OAuthAccessToken = accessToken.Token;
                flickr.OAuthAccessTokenSecret = accessToken.TokenSecret;

                using (var sw = new StreamWriter("key.txt", false))
                {
                    sw.WriteLine(flickr.OAuthAccessToken);
                    sw.WriteLine(flickr.OAuthAccessTokenSecret);
                }

                auth = flickr.AuthOAuthCheckToken();
                int y = 56;
            }

            var baseFolder = @"D:\MyData\Camera Dumps\";

            var ex = new PhotoSearchExtras();
            var p = flickr.PhotosSearch(new PhotoSearchOptions(auth.User.UserId){Extras = PhotoSearchExtras.DateTaken | PhotoSearchExtras.PathAlias, });
            var sets = flickr.PhotosetsGetList();
            foreach (var set in sets)
            {
                var setDir = Path.Combine(baseFolder, set.Title);
                if ( Directory.Exists(setDir) )
                {
                    var setPhotos = flickr.PhotosetsGetPhotos(set.PhotosetId, PhotoSearchExtras.DateTaken | PhotoSearchExtras.MachineTags | PhotoSearchExtras.OriginalFormat | PhotoSearchExtras.DateUploaded);
                    foreach(var setPhoto in setPhotos)
                    {
                        if (Math.Abs((setPhoto.DateUploaded - setPhoto.DateTaken).TotalSeconds) < 60)
                        {
                            // Suspicious
                            int s = 56;
                        }

                        string ext = ".jpg";
                        if (setPhoto.OriginalFormat != "jpg")
                        {
                            int xxx = 56;
                        }
                        var filePath = Path.Combine(setDir, setPhoto.Title + ext);

                        if (!File.Exists(filePath))
                        {
                            // try mov
                            filePath = Path.Combine(setDir, setPhoto.Title + ".mov");

                            if (!File.Exists(filePath))
                            {
                                Console.WriteLine("not found " + filePath);
                            }
                        }

                        Console.WriteLine(filePath);
                        if ( File.Exists(filePath))
                        {
                            DateTime dateTaken;
                            if (!GetExifDateTaken(filePath, out dateTaken))
                            {
                                var fi = new FileInfo(filePath);
                                dateTaken = fi.LastWriteTime;
                            }

                            if (Math.Abs((dateTaken - setPhoto.DateTaken).TotalSeconds) > 10)
                            {
                                int hmmm = 56;
                            }
                        }
                    }
                }
            }
            //@"D:\MyData\Camera Dumps\"

            int z =  56;
        }
コード例 #2
0
ファイル: FlickrImageService.cs プロジェクト: pebblecode/raci
 public IEnumerable<FlickrImage> GetImages(string tags)
 {
     Flickr.CacheDisabled = true;
     var flickr = new Flickr("340b341adedd9b2613d5c447c4541e0f");
     flickr.InstanceCacheDisabled = true;
     var options = new PhotoSearchOptions { Tags = tags, PerPage = 2  };
     var photos = flickr.PhotosSearch(options);
     return photos.Select(i =>
     {
         using (var client = new WebClient())
         {
             var data = client.DownloadData(i.Medium640Url);
             using (var memoryStream = new MemoryStream(data))
             {
                 var bitmap = new Bitmap(memoryStream);
                 return new FlickrImage
                            {
                                Url = i.Medium640Url,
                                Image = new Bitmap(bitmap),
                                Encoded = Convert.ToBase64String(memoryStream.ToArray())
                            };
             }
         }
     });
 }
コード例 #3
0
ファイル: Flickr.cs プロジェクト: xuchuansheng/GenXSource
	public List<string[]> GetPhotos( string apiKey, string tags )
	{
		FlickrNet.Flickr.CacheDisabled = true;
		FlickrNet.Flickr flickr = new FlickrNet.Flickr( apiKey );

		FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions();
		options.Tags = tags;
		options.Extras = FlickrNet.PhotoSearchExtras.All;
		options.PerPage = 343;
		options.Text = tags;
		options.TagMode = FlickrNet.TagMode.AllTags;

		List<string[]> photos = new List<string[]>();

		foreach ( FlickrNet.Photo photo in flickr.PhotosSearch( options ).PhotoCollection )
		{
			photos.Add( new string[] {
                    photo.MediumUrl,
                    photo.WebUrl,
                    photo.Title,
                    System.Xml.XmlConvert.ToString( photo.DateTaken, System.Xml.XmlDateTimeSerializationMode.Utc ),
                    photo.OwnerName,
                    photo.Latitude.ToString(),
                    photo.Longitude.ToString() } );
			//                try { photos.Add( new Photo( photo, "{0}" ) ); }
			//                catch { }
		}

		return photos;
	}
コード例 #4
0
ファイル: Flickr.cs プロジェクト: Shine6Z/GenXSource
    public List <string[]> GetPhotos(string apiKey, string tags)
    {
        FlickrNet.Flickr.CacheDisabled = true;
        FlickrNet.Flickr flickr = new FlickrNet.Flickr(apiKey);

        FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions();
        options.Tags    = tags;
        options.Extras  = FlickrNet.PhotoSearchExtras.All;
        options.PerPage = 343;
        options.Text    = tags;
        options.TagMode = FlickrNet.TagMode.AllTags;

        List <string[]> photos = new List <string[]>();

        foreach (FlickrNet.Photo photo in flickr.PhotosSearch(options).PhotoCollection)
        {
            photos.Add(new string[] {
                photo.MediumUrl,
                photo.WebUrl,
                photo.Title,
                System.Xml.XmlConvert.ToString(photo.DateTaken, System.Xml.XmlDateTimeSerializationMode.Utc),
                photo.OwnerName,
                photo.Latitude.ToString(),
                photo.Longitude.ToString()
            });
            //                try { photos.Add( new Photo( photo, "{0}" ) ); }
            //                catch { }
        }

        return(photos);
    }
コード例 #5
0
        private void FindUserButton_Click(object sender, EventArgs e)
        {
            // First page of the users photos
            // Sorted by interestingness

            Flickr flickr = new Flickr(ApiKey.Text);
            FoundUser user;
            try
            {
                user = flickr.PeopleFindByUserName(Username.Text);
                OutputTextbox.Text = "User Id = " + user.UserId + "\r\n" + "Username = "******"\r\n";
            }
            catch (FlickrException ex)
            {
                OutputTextbox.Text = ex.Message;
                return;
            }

            PhotoSearchOptions userSearch = new PhotoSearchOptions();
            userSearch.UserId = user.UserId;
            userSearch.SortOrder = PhotoSearchSortOrder.InterestingnessDescending;
            PhotoCollection usersPhotos = flickr.PhotosSearch(userSearch);
            // Get users contacts
            ContactCollection contacts = flickr.ContactsGetPublicList(user.UserId);
            // Get first page of a users favorites
            PhotoCollection usersFavoritePhotos = flickr.FavoritesGetPublicList(user.UserId);
            // Get a list of the users groups
            //PublicGroupInfoCollection usersGroups = flickr.PeopleGetPublicGroups(user.UserId);

            int i = 0;
            foreach (Contact contact in contacts)
            {
                OutputTextbox.Text += "Contact " + contact.UserName + "\r\n";
                if (i++ > 10) break; // only list the first 10
            }

            i = 0;
            //foreach (PublicGroupInfo group in usersGroups)
            //{
            //    OutputTextbox.Text += "Group " + group.GroupName + "\r\n";
            //    if (i++ > 10) break; // only list the first 10
            //}

            i = 0;
            foreach (Photo photo in usersPhotos)
            {
                OutputTextbox.Text += "Interesting photo title is " + photo.Title + " " + photo.WebUrl + "\r\n";
                if (i++ > 10) break; // only list the first 10
            }

            i = 0;
            foreach (Photo photo in usersFavoritePhotos)
            {
                OutputTextbox.Text += "Favourite photo title is " + photo.Title + " " + photo.WebUrl + "\r\n";
                if (i++ > 10) break; // only list the first 10
            }
        }
コード例 #6
0
        private IEnumerable<ResponseMessage> FlickrHandler(IncomingMessage message, string matchedHandle)
        {
            string searchTerm = message.TargetedText.Substring(matchedHandle.Length).Trim();

            if (string.IsNullOrEmpty(searchTerm))
            {
                yield return message.ReplyToChannel($"Please give me something to search, e.g. {matchedHandle} trains");
            }
            else
            {
                yield return message.IndicateTypingOnChannel();
                string apiKey = _configReader.GetConfigEntry<string>("flickr:apiKey");

                if (string.IsNullOrEmpty(apiKey))
                {
                    _statsPlugin.IncrementState("Flickr:Failed");
                    yield return message.ReplyToChannel("Woops, looks like a Flickr API Key has not been entered. Please ask the admin to fix this");
                }
                else
                {
                    var flickr = new Flickr(apiKey);

                    var options = new PhotoSearchOptions { Tags = searchTerm, PerPage = 50, Page = 1};
                    PhotoCollection photos = flickr.PhotosSearch(options);

                    if (photos.Any())
                    {
                        _statsPlugin.IncrementState("Flickr:Sent");

                        int i = new Random().Next(0, photos.Count);
                        Photo photo = photos[i];
                        var attachment = new Attachment
                        {
                            AuthorName = photo.OwnerName,
                            Fallback = photo.Description,
                            ImageUrl = photo.LargeUrl,
                            ThumbUrl = photo.ThumbnailUrl
                        };

                        yield return message.ReplyToChannel($"Here is your picture about '{searchTerm}'", attachment);
                    }
                    else
                    {
                        _statsPlugin.IncrementState("Flickr:Failed");
                        yield return message.ReplyToChannel($"Sorry @{message.Username}, I couldn't find anything about {searchTerm}");
                    }
                }
            }
        }
コード例 #7
0
        private void GetPictures(string tag)
        {
            PhotoSearchOptions options = new PhotoSearchOptions();
            options.PerPage = 18;
            options.Page = 1;
            options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
            options.MediaType = MediaType.Photos;
            options.Extras = PhotoSearchExtras.All;
            options.Tags = tag;

            Flickr flickr = new Flickr(flickrKey, sharedSecret);
            PhotoCollection photos = flickr.PhotosSearch(options);

            ThumbnailsList.DataSource = photos;
            ThumbnailsList.DataBind();
        }
コード例 #8
0
        public static void GetImages(string searchTerm)
        {
            Flickr fl = new Flickr("8704e391e50a52774ee2bf393c35b10c");

            PhotoSearchOptions opt = new PhotoSearchOptions();
            opt.Text = searchTerm;
            opt.PerPage = 10;
            opt.Page = 1;
            var photos = fl.PhotosSearch(opt);
            foreach (Photo p in photos)
            {
                System.Drawing.Image img = DownloadImage(p.LargeUrl);

                SurfaceWindow1.AddImage(img, System.Windows.Media.Colors.Transparent);
            }
        }
コード例 #9
0
ファイル: FlickrTests.cs プロジェクト: G-Rad/nzblog
        public void ApiSpike_GetInfo()
        {
            var client = new Flickr(Settings.Flickr.ApiKey, Settings.Flickr.SharedSecret);
            client.InstanceCacheDisabled = true;

            var photos = client.PhotosSearch(new PhotoSearchOptions(Settings.Flickr.UserId, "blog"));

            var result = new List<Tuple<string,string>>();

            foreach (var photo in photos)
            {
                var info = client.PhotosGetInfo(photo.PhotoId, photo.Secret);
                result.Add(new Tuple<string, string>(info.Title, info.Description));
            }

            Assert.That(result, Is.Not.Empty);
        }
コード例 #10
0
        private void GetPhotoButton_Click(object sender, EventArgs e)
        {
            Flickr flickr = new Flickr(ApiKey.Text, SharedSecret.Text, AuthToken.Text);

            Auth auth = flickr.AuthCheckToken(AuthToken.Text);

            PhotoSearchOptions options = new PhotoSearchOptions(auth.User.UserId);
            options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
            options.PerPage = 1;

            PhotoCollection photos = flickr.PhotosSearch(options);

            Flickr.FlushCache(flickr.LastRequest);

            Photo photo = photos[0];

            webBrowser1.Navigate(photo.SmallUrl);

            OldTitle.Text = photo.Title;
            PhotoId.Text = photo.PhotoId;
        }
コード例 #11
0
        public void ImportSearchResults(Flickr flickr, string userId, string searchTerm)
        {
            var results = flickr.PhotosSearch(new PhotoSearchOptions()
            {
                 SafeSearch = SafetyLevel.Safe,
                 IsCommons = true,
                 Tags = searchTerm,
                 Extras = PhotoSearchExtras.Tags,
                 Page = 0,
                 PerPage = 50
            });
            var user = userRepository.Load(userId);
            foreach (var image in results)
            {
                Console.WriteLine("Found {0} with ({1})", image.Title, string.Join(",", image.Tags.ToArray()));

                Console.WriteLine("Downloading image data");

                WebRequest request = WebRequest.Create(image.MediumUrl);
                Byte[] content = null;
                using (var response = request.GetResponse())
                {
                    content = new Byte[response.ContentLength];
                    var stream = response.GetResponseStream();
                    BinaryReader reader = new BinaryReader(stream);
                    content = reader.ReadBytes((int)response.ContentLength);
                }

                imageUploadService.UploadUserImage(user,
                        image.Title,
                        image.Tags.ToArray(),
                        content);

                Console.WriteLine("Downloaded image data");
            }
            documentSession.SaveChanges();
        }
コード例 #12
0
ファイル: FlickrMiddleware.cs プロジェクト: irmbrady/noobot
        private IEnumerable<ResponseMessage> FlickrHandler(IncomingMessage message, string matchedHandle)
        {
            string searchTerm = message.TargetedText.Substring(matchedHandle.Length).Trim();

            if (string.IsNullOrEmpty(searchTerm))
            {
                yield return message.ReplyToChannel($"Please give me something to search, e.g. {matchedHandle} trains");
            }
            else
            {
                yield return message.ReplyToChannel($"Ok, let's find you something about '{searchTerm}'");
                string apiKey = _configReader.GetConfig().Flickr?.ApiKey;

                if (string.IsNullOrEmpty(apiKey))
                {
                    yield return message.ReplyToChannel("Woops, looks like a Flickr API Key has not been entered. Please ask the admin to fix this");
                }
                else
                {
                    var flickr = new Flickr(apiKey);

                    var options = new PhotoSearchOptions { Tags = searchTerm, PerPage = 50, Page = 1};
                    PhotoCollection photos = flickr.PhotosSearch(options);

                    if (photos.Any())
                    {
                        int i = new Random().Next(0, photos.Count);
                        Photo photo = photos[i];
                        yield return message.ReplyToChannel(photo.LargeUrl);
                    }
                    else
                    {
                        yield return message.ReplyToChannel($"Sorry @{message.Username}, I couldn't find anything about {searchTerm}");
                    }
                }
            }
        }
コード例 #13
0
        public object Any(Search request)
        {
            ///

            var results = new List <Comment>();

            FlickrNet.Flickr flickr = new FlickrNet.Flickr();
            flickr.ApiKey    = "e3fc3cc5de2994589d1e8337a5d245e6";
            flickr.ApiSecret = "0678d10c68219c84";

            var options = new PhotoSearchOptions {
                Tags = request.Keyword, PerPage = 20, Page = 1
            };
            PhotoCollection photos = flickr.PhotosSearch(options);

            foreach (Photo photo in photos)
            {
                results.Add(new Comment {
                    Description = photo.Title, Provider = "Flickr"
                });
            }

            return(results);
        }
コード例 #14
0
ファイル: FlickrService.cs プロジェクト: cmeigs/SkiChair
        /*
         * public bool SetFlickrAuthentication(string flickrAuth)
         * {
         *  try
         *  {
         *      flickr.AuthToken = flickrAuth;
         *      return true;
         *  }
         *  catch (Exception ex)
         *  {
         *      return false;
         *  }
         * }
         */

        /// <summary>
        /// this method will populate a generic list of type photograph given a product ID
        /// </summary>
        /// <param name="productType"></param>
        /// <returns>Generic list of type Photograph</returns>
        public List <Photograph> GetFlickrPhotographListByProductType(Utility.SkiChairProduct productType)
        {
            try
            {
                List <Photograph> flickrImageInfoList = new List <Photograph>();

                PhotoSearchOptions searchOptions = new PhotoSearchOptions();
                //searchOptions.GroupId = Utility.FlickrGroupID;
                searchOptions.UserId    = Utility.FlickrUserID;
                searchOptions.Extras    = PhotoSearchExtras.Tags;
                searchOptions.Tags      = productType.ToString();
                searchOptions.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
                PhotoCollection photoCollection = flickr.PhotosSearch(searchOptions);

                foreach (Photo photo in photoCollection)
                {
                    flickrImageInfoList.Add(new Photograph(photo.PhotoId, photo.ThumbnailUrl, photo.MediumUrl, photo.Title));
                }

                return(flickrImageInfoList);
            }
            catch (Exception ex)
            {
                System.IO.StreamWriter sw = System.IO.File.AppendText(ConfigurationManager.AppSettings["ErrorLogPath"].ToString() + "SkiChairErrorLogFile.txt");
                try
                {
                    string logLine = System.String.Format("{0:G}: {1}.", System.DateTime.Now, "Error: " + ex.Message);
                    sw.WriteLine(logLine);
                }
                finally
                {
                    sw.Close();
                }
                return(null);
            }
        }
コード例 #15
0
        public ActionResult Index(Models.FlickrSearchModel model, string paging)
        {
            string searchText = model.SearchText;
            int curPage = model.Page;
            int nextPage = curPage;

            switch (paging)
            {
                case "next":
                    nextPage++;
                    break;
                case "previous":
                    nextPage--;
                    break;
            }

            Flickr flickr = new Flickr(apiKey);
            var options = new PhotoSearchOptions { Tags = searchText, PerPage = 12, Page = nextPage };
            PhotoCollection photos = flickr.PhotosSearch(options);
            model.Photos = photos;
            model.Page = nextPage;

            return View(model);
        }
コード例 #16
0
        public ActionResult Create(Destino Destino,string Button, Map map)
        {
            var idViaje = Convert.ToInt32(Request["idViaje"]);

            if (Button == "Agregar Destino")
            {
                IRepositorio<Destino> repo = new DestinoRepositorio();
                IRepositorio<Viaje> repoViaje = new ViajeRepositorio();
                Destino.Viaje = repoViaje.GetById(idViaje);
                PhotoSearchOptions options = new PhotoSearchOptions();
                options.Extras |= PhotoSearchExtras.Geo;
                options.Tags = map.Name;
                options.HasGeo = true;
                options.PerPage = 24;
                Flickr flickr = new Flickr("3de826e278b4988011ef0227585a7838", "81a96df44a82b16c");
                photos = flickr.PhotosSearch(options);
                foreach (Photo photo in photos)
                {
                    if (Destino.Url != null)
                    {
                        if (Destino.Url.CompareTo(photo.SmallUrl) == 0)
                        {
                            Destino.Latitud = photo.Latitude;
                            Destino.Longitud = photo.Longitude;
                            Destino.Nombre = photo.Title;
                        }
                    }else
                    {
                        ModelState.AddModelError(string.Empty,"Es Necesario que escoja una foto!");
                        return View();
                    }
                }
                repo.Save(Destino);
                int id2 = idViaje;
                ViewData["idViaje"] = id2;
                return RedirectToAction("Index", "Destino", new { idViaje = id2 });
            }
            else {
                int i = 0;
                PhotoSearchOptions options = new PhotoSearchOptions();
                //options.BoundaryBox = new BoundaryBox(-1.7, 54.9, -1.4, 55.2); // Roughly Newcastle upon Type, England
                //options.BoundaryBox = BoundaryBox.World;
                options.Extras |= PhotoSearchExtras.Geo;
                options.Tags = map.Name;
                options.HasGeo = true;
                options.PerPage = 24;

                Flickr flickr = new Flickr("18ead65365e9b505cc7f97abd38a33fe", "1b0f7df21b450da8");

                photos = flickr.PhotosSearch(options);
                foreach (Photo photo in photos)
                {
                    ViewData["Message"] = String.Format("Lugares de \"{0}\".", map.Name);
                    ViewData.Add(("Message" + i), photo.SmallUrl);
                    i++;
                }
                int id2 = idViaje;
                ViewData["idViaje"] = id2;

                return View();
            }
        }
コード例 #17
0
        public async Task<HttpResponseMessage> PostImage([ValueProvider(typeof(HeaderValueProviderFactory<string>))]
          string sessionKey)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // Read the file

            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);


                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                using (var db = new BGNewsDB())
                {
                    var user = db.Users.FirstOrDefault(x => x.SessionKey == sessionKey);
                    if (user == null)
                    {
                        return Request.CreateResponse(HttpStatusCode.Unauthorized);
                    }

                    try
                    {
                        // Read the form data.
                        await Request.Content.ReadAsMultipartAsync(provider);

                        // This illustrates how to get the file names.
                        foreach (MultipartFileData file in provider.FileData)
                        {
                            Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                            Trace.WriteLine("Server file path: " + file.LocalFileName);
                            string fileName = file.LocalFileName;
                            Flickr flickr = new Flickr("8429718a57e817718d524ea6366b5b42", "3504e68e5812b923", "72157635282605625-a5feb0f5a53c4467");
                            var result = flickr.UploadPicture(fileName);
                            System.IO.File.Delete(file.LocalFileName);


                            // Take the image urls from flickr

                            Auth auth = flickr.AuthCheckToken("72157635282605625-a5feb0f5a53c4467");
                            PhotoSearchOptions options = new PhotoSearchOptions(auth.User.UserId);
                            options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
                            options.PerPage = 1;

                            ICollection<Photo> photos = flickr.PhotosSearch(options);

                            Flickr.FlushCache(flickr.LastRequest);

                            Photo photo = photos.First();
                               user.ProfilePictureUrlMedium = photo.MediumUrl;
                               user.ProfilePictureUrlThumbnail = photo.SquareThumbnailUrl;
                            break;

                        }
                       
                     
                        return Request.CreateResponse(HttpStatusCode.Created);
                    }

                    catch (System.Exception e)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
                    }
                }
            
        }
コード例 #18
0
        // This method takes care of the process heavy stuff. It can report progress and I will use that
        // to load each image.
        private void simmiWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            Console.WriteLine("Async backgroundworker started");

            if ((worker.CancellationPending == true))
            {
                Console.WriteLine("if");
                e.Cancel = true;
                // breaks out of the loop, if there is a loop.
                // break;
            }
            else
            {
                Flickr flickr = new Flickr("59c64644ddddc2a52a089131c8ca0933", "b080535e26aa05df");
                FoundUser user = flickr.PeopleFindByUserName("simmisj");
                //FoundUser user = flickr.PeopleFindByUserName("simmisj");

                //PeoplePhotoCollection people = new PeoplePhotoCollection();

                //people = flickr.PeopleGetPhotosOf(user.UserId);

                PhotoSearchOptions options = new PhotoSearchOptions();
                options.UserId = user.UserId; // Your NSID
                options.PerPage = 4; // 100 is the default anyway
                PhotoCollection photos;

                try
                {
                    photos = flickr.PhotosSearch(options);
                    photos.Page = 1;
                }
                catch (Exception ea)
                {
                    //e.Result = "Exception: " + ea;
                    return;
                }

                for (int i = 0; i < photos.Count; i++)
                {
                    // Report progress and pass the picture to the progresschanged method
                    // for the progresschanged method to update the observablecollection.
                    worker.ReportProgress(100, photos[i].Medium640Url);
                    //pictures.Add(photos[i].Medium640Url);

                    // Add the picture to the ObservableCollection.
                    //pictures.Add(photos[i].Medium640Url);
                    //scatterView1.Items.Add(photos[i].ThumbnailUrl);

                }

            }
        }
コード例 #19
0
ファイル: FormMain.cs プロジェクト: dmcclimans/FlickrDL
        private void BGDownloadAllPhotos(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            PhotoList = new SortableBindingList <Photo>();

            worker.ReportProgress(0, "Searching all photos");

            FlickrNet.Flickr f = FlickrManager.GetFlickrAuthInstance();
            if (f == null)
            {
                BGErrorMessage = "You must authenticate before you can download data from Flickr.";
                return;
            }

            try
            {
                FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions();
                options.Extras    = SearchExtras;
                options.SortOrder = FlickrNet.PhotoSearchSortOrder.DateTakenAscending;
                if (Settings.FilterByDate)
                {
                    options.MinTakenDate = Settings.StartDate.Date;
                    options.MaxTakenDate = Settings.StopDate.Date + new TimeSpan(23, 59, 59);
                }
                options.UserId  = SearchAccountUser.UserId;
                options.Page    = 1;
                options.PerPage = 500;

                FlickrNet.PhotoCollection photoCollection;
                do
                {
                    if (worker.CancellationPending) // See if cancel button was pressed.
                    {
                        return;
                    }

                    photoCollection = f.PhotosSearch(options);
                    if (photoCollection.Total > 3999)
                    {
                        BGErrorMessage = $"Too many photos: {photoCollection.Total}";
                        return;
                    }
                    foreach (FlickrNet.Photo flickrPhoto in photoCollection)
                    {
                        AddPhotoToList(f, flickrPhoto, null);
                    }
                    // Calculate percent complete based on how many pages we have completed.
                    int percent = (options.Page * 100 / photoCollection.Pages);
                    worker.ReportProgress(percent, "Searching all photos");

                    options.Page = photoCollection.Page + 1;
                }while (options.Page <= photoCollection.Pages);
            }
            catch (FlickrNet.FlickrException ex)
            {
                BGErrorMessage = "Download failed. Error: " + ex.Message;
                return;
            }

            DownloadFiles(worker, e);
        }
コード例 #20
0
        // This method takes care of the process heavy stuff. It can report progress and I will use that
        // to load each image.
        private void bwFlickrImageLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            Console.WriteLine("Async backgroundworker started");

            if ((worker.CancellationPending == true))
            {
                Console.WriteLine("if");
                e.Cancel = true;
                // breaks out of the loop, if there is a loop.
                // break;
            }
            else
            {
                PhotoCollection photos;

                Console.WriteLine("else");
                // Perform a time consuming operation and report progress.
                Flickr flickr = new Flickr("59c64644ddddc2a52a089131c8ca0933", "b080535e26aa05df");
                PhotoSearchOptions options = new PhotoSearchOptions();
                //options.Tags = "blue,sky";
                options.Tags = (string)e.Argument;
                options.PerPage = 4; // 100 is the default

                try
                {
                    photos = flickr.PhotosSearch(options);
                    photos.Page = 1;
                }
                catch (Exception ea)
                {
                    e.Result = "Exception: "+ea;
                    return;
                }

                //scatterView1.ItemsSource = photos;
                //scatterView1.DataContext = photos;

                for (int i = 0; i < photos.Count; i++)
                {
                    // Report progress and pass the picture to the progresschanged method
                    // for the progresschanged method to update the observablecollection.
                    worker.ReportProgress(100, photos[i].Medium640Url);

                    // Add the picture to the ObservableCollection.
                    //pictures.Add(photos[i].Medium640Url);
                    //scatterView1.Items.Add(photos[i].ThumbnailUrl);

                }

            }
        }
コード例 #21
0
        public static string GetWallpaper(string theme, int minW, int minH, string dlFolder, out string flickrPage, List<string> bannedWalls, Action<string> banWallpaper)
        {
            flickrPage = "";

            theme = theme.Replace("Twilight", "Sunset"); //because flickr usually returns nothing when the tag combination contains "Twilight"

            try
            {
                Flickr flickr = new Flickr("928a5bfb36cc1ea3160c6d236c2c76d4");

                //search flickr
                PhotoSearchOptions opts = new PhotoSearchOptions();

                opts.Tags = theme.Replace(" - ", ",");
                opts.TagMode = TagMode.AllTags;
                opts.SortOrder = PhotoSearchSortOrder.InterestingnessDescending;
                opts.Licenses.Add(LicenseType.AttributionCC);
                opts.Licenses.Add(LicenseType.AttributionNoDerivativesCC);
                opts.Licenses.Add(LicenseType.AttributionShareAlikeCC);
                opts.Licenses.Add(LicenseType.NoKnownCopyrightRestrictions);
                opts.SafeSearch = SafetyLevel.Safe;
                opts.ContentType = ContentTypeSearch.PhotosOnly;
                opts.MediaType = MediaType.Photos;
                opts.Extras = PhotoSearchExtras.OwnerName;

                PhotoCollection flickrResults = flickr.PhotosSearch(opts);

                if (flickrResults.Count == 0) //no suitable wallpapers found
                    return "";

                //choose random images for one that satisfies min. resolution
                SizeCollection sizes;
                Random rand = new Random((int)DateTime.Now.Ticks);
                string url = "";
                int pick = -1, i;

                while (pick == -1)
                {
                    pick = rand.Next(flickrResults.Count);

                    if (bannedWalls.Contains(flickrResults[pick].WebUrl))
                    {
                        //wallpaper banned, pick another
                        flickrResults.RemoveAt(pick);
                        pick = -1;
                    }
                    else
                    {
                        sizes = flickr.PhotosGetSizes(flickrResults[pick].PhotoId);

                        for (i = sizes.Count - 1; i >= 0; i--)
                            if (sizes[i].Width < minW || sizes[i].Height < minH)
                                break;

                        i++;
                        if (i == sizes.Count) //image not large enough
                        {
                            banWallpaper(flickrResults[pick].WebUrl); //ban it so future searches can ignore it
                            flickrResults.RemoveAt(pick);

                            pick = -1;
                        }
                        else
                            url = sizes[i].Source;
                    }

                    if (flickrResults.Count == 0) //no suitable wallpapers found
                        return "";
                }

                //get valid filename from title
                string filename = flickrResults[pick].Title;
                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                    filename = filename.Replace(c, '_');

                filename += url.Substring(url.LastIndexOf('.')); //append file extension from url

                //dl image
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(url, dlFolder + filename);
                }

                flickrPage = flickrResults[pick].WebUrl;
                return dlFolder + filename;
            }
            catch (Exception e)
            {
                return "";
            }
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: josheschulz/FlickrSlurp
        static void Main(string[] args)
        {
            StringBuilder errorLog = new StringBuilder();
            errorLog.AppendFormat("Starting Run at {0}\n", DateTime.Now.ToString());
            string baseDir = ConfigurationSettings.AppSettings["LocalDir"].ToString();
            Flickr flickr = new Flickr(ConfigurationSettings.AppSettings["APIKey"].ToString(), ConfigurationSettings.AppSettings["APISecret"].ToString());
            flickr.AuthToken = "";

            Auth auth = flickr.AuthCheckToken("");

            PhotoSearchOptions searchOptions = new PhotoSearchOptions();

            searchOptions.PrivacyFilter = PrivacyFilter.None;
            searchOptions.UserId = auth.User.UserId;
            searchOptions.PerPage = 500;

            PhotoCollection pics = new PhotoCollection();

            WebClient wget = new WebClient();
            searchOptions.Extras |= PhotoSearchExtras.DateTaken | PhotoSearchExtras.OriginalFormat | PhotoSearchExtras.OriginalUrl | PhotoSearchExtras.Description | PhotoSearchExtras.Tags;
            PhotoCollection rev = flickr.PhotosSearch(searchOptions);

            while (rev.Pages >= searchOptions.Page)

            {
                foreach(Photo pic in rev){

                        //We have a picture.
                        string year = pic.DateTaken.Year.ToString("0000");
                        string month = pic.DateTaken.Month.ToString("00");
                        string day = pic.DateTaken.Day.ToString("00");
                        //  Does the directory Exist
                        //      No
                        string directory = String.Format("{0}{1}\\{2}\\{3}\\", baseDir, year, month, day);
                        try
                        {
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }

                        string fileName = string.Format("{0}.{1}", pic.PhotoId, pic.OriginalFormat);

                        string finalDestination = String.Format("{0}{1}", directory, fileName);
                        if (!File.Exists(finalDestination))
                        {

                            wget.DownloadFile(pic.OriginalUrl, finalDestination);
                            FileInfo fi = new FileInfo(finalDestination);
                            if (fi.Length < 10000)
                            {
                                //This shoudl catch file unavailable
                                throw new Exception("File size is too small");
                            }

                            StreamWriter dataFile = new StreamWriter(String.Format("{0}{1}.xml", directory, fileName));

                            StringBuilder meta = new StringBuilder();
                            meta.AppendFormat("<xml>\n\t<file>{0}</file>\n\t<title>{1}</title>\n\t<description>{2}</description>\n\t<dateTaken>{3}</dateTaken>\n\t<tags>", fileName, pic.Title, pic.Description, pic.DateTaken.ToString());
                            foreach(String tag in pic.Tags){
                                meta.AppendFormat("\n\t\t<tag>{0}</tag>", tag);
                            }
                            meta.Append("\n\t</tags>\n</xml>");
                            dataFile.Write(meta.ToString());
                            dataFile.Close();
                        }
                    }
                    catch (System.Exception ex)
                    {
                        errorLog.AppendFormat("{0}:{1}:{2}\n", directory, pic.PhotoId, ex.Message);
                    }
                }

                searchOptions.Page = rev.Page + 1;
                rev = flickr.PhotosSearch(searchOptions);
            }
            errorLog.AppendFormat("Finished Run at {0}\n", DateTime.Now.ToString());
            StreamWriter file = new StreamWriter(ConfigurationSettings.AppSettings["LocalDir"].ToString() + "/errors.log");
            file.Write(errorLog.ToString());
            file.Close();
        }
コード例 #23
0
        private void SimpleSearchButton1_Click(object sender, EventArgs e)
        {
            OutputTextbox.Text = "";

            // Example 1
            //string apikey = ApiKey.Text;
            string apikey ="deaba23a63d9b3c34b63f1a04548a3f4";
            Flickr flickr = new Flickr(apikey);

            // Example 2
            PhotoSearchOptions searchOptions = new PhotoSearchOptions();
            searchOptions.UserId = "70831453@N00";
            //searchOptions.Tags = "kanas";
            searchOptions.PerPage = 500;
            PhotoCollection microsoftPhotos = flickr.PhotosSearch(searchOptions);
            PhotosetPhotoCollection myset = flickr.PhotosetsGetPhotos("72157636689533194");
            //PhotoCollection myset = flickr.PhotosSearch(searchOptions);
            //Photoset myset = flickr.PhotosetsGetInfo("72157594398087814");

            // Example 3
            //searchOptions.Page = 2;
            //PhotoCollection microsoftPhotos2 = flickr.PhotosSearch(searchOptions);
            //searchOptions.Page = 3;
            //PhotoCollection microsoftPhotos3 = flickr.PhotosSearch(searchOptions);

            // Eample 4
            List<Photo> allPhotos = new List<Photo>();
            allPhotos.AddRange(myset);
            //allPhotos.AddRange(microsoftPhotos2);
            //allPhotos.AddRange(microsoftPhotos3);

            WebClient webClient = new WebClient();

            String s = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            foreach (Photo photo in allPhotos)
            {

                OutputTextbox.Text += "Photos title is " + photo.Title + " " + photo.ThumbnailUrl+ "\r\n";

                if (photo.DoesLargeExist){
                    webClient.DownloadFile(photo.LargeUrl, s + @"\ssr\" + photo.PhotoId +searchOptions.Tags+ @".jpg");
                }
                else if(photo.DoesMediumExist){
                    webClient.DownloadFile(photo.MediumUrl, s+@"\ssr\"+photo.PhotoId+searchOptions.Tags+@".jpg");

                }
                //else if (photo.OriginalUrl)
                //{
                    //webClient.DownloadFile(photo.MediumUrl, s + @"\temp\" + photo.PhotoId + searchOptions.Tags + @".jpg");

                //}
                else
                {
                    webClient.DownloadFile(photo.Medium640Url , s + @"\ssr\" + photo.PhotoId + searchOptions.Tags+@".jpg");

                }

            }
        }
コード例 #24
0
        public void fetchPhotosFromSpecifcUser(string userName)
        {
            Flickr flickr = new Flickr("59c64644ddddc2a52a089131c8ca0933", "b080535e26aa05df");

            FoundUser user = flickr.PeopleFindByUserName(userName);

            //PeoplePhotoCollection people = new PeoplePhotoCollection();

            //people = flickr.PeopleGetPhotosOf(user.UserId);

            PhotoSearchOptions options = new PhotoSearchOptions();
            options.UserId = user.UserId; // Your NSID
            options.PerPage = 4; // 100 is the default anyway
            PhotoCollection photos = flickr.PhotosSearch(options);

            try
            {
                photos = flickr.PhotosSearch(options);
                photos.Page = 1;
            }
            catch (Exception ea)
            {
                //e.Result = "Exception: " + ea;
                return;
            }

            for (int i = 0; i < photos.Count; i++)
            {
                // Report progress and pass the picture to the progresschanged method
                // for the progresschanged method to update the observablecollection.
                pictures.Add(photos[i].Medium640Url);

                // Add the picture to the ObservableCollection.
                //pictures.Add(photos[i].Medium640Url);
                //scatterView1.Items.Add(photos[i].ThumbnailUrl);

            }
        }