public void SetNewPicture(Picture p) { //make sure that file system redirection is disabled, otherwise the image shows up somewhere else. // thanks to (http://stackoverflow.com/questions/6617530/could-not-find-a-part-of-the-path-c-windows-system32-oobe-info-background) for this IntPtr ptr = new IntPtr(); bool isWow64FsRedirectionDisabled = WinAPI.Wow64DisableWow64FsRedirection(ref ptr); var fiOriginal = new FileInfo(p.LocalPath); if (fiOriginal.Exists && fiOriginal.Length > 0) { var outPutFile = Path.Combine(_oobeBackground, "backgroundDefault.jpg"); //delete any existing files try { File.Delete(outPutFile); } catch(Exception ex) { Log.Logger.Write(string.Format("Error deleting existing Logon Background located at '{0}'. Exception details: {1}",outPutFile, ex.ToString()), Log.LoggerLevels.Errors); } //check if image resolution is a valid aspect ratio, if not try and fix it using (FileStream fs = File.OpenRead(p.LocalPath)) { using (Image img = Image.FromStream(fs)) { var strRatio = Math.Round((double)img.Width / (double)img.Height, 3).ToString(); var aspectRatio = Convert.ToDouble(strRatio.Length <= 4 ? strRatio : strRatio.Substring(0, 4)); //aspect ratio list came from link: http://social.technet.microsoft.com/Forums/en-US/w7itproui/thread/b52689fb-c733-4229-8a10-4aa32d527832/ // this list may not be complete List<double> validRatios = new List<double>(); validRatios.Add(1.25); validRatios.Add(1.33); validRatios.Add(1.60); validRatios.Add(1.67); validRatios.Add(1.77); //if not a valid aspect ratio, adjust image if (!validRatios.Contains(aspectRatio)) { PictureManager.ShrinkImage(p.LocalPath, outPutFile, 0, 0, 90); } else { //save image to output file img.Save(outPutFile); } } } //File.Copy(p.LocalPath, outPutFile, true); var fiNewFile = new FileInfo(outPutFile); //fix picture if it's to big if (fiNewFile.Length / 1024 >= 245) { //reduce quality until we are under 245kb PictureManager.ReduceQuality(outPutFile, outPutFile, 90); } } }
public PictureDownload(Picture p) { if (string.IsNullOrEmpty(p.LocalPath)) throw new ArgumentNullException("The Local Path of the picture must be defined before downloading it"); this.Picture = p; //set default priority this.Priority = 999999999; //set default status of Stopped Status = DownloadStatus.Stopped; //setup webclient events _client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(_client_DownloadFileCompleted); _client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(_client_DownloadProgressChanged); }
public void BanPicture(Picture p) { string banString = (p.Properties.ContainsKey(Picture.StandardProperties.BanImageKey) ? p.Properties[Picture.StandardProperties.BanImageKey] : p.Url); //add the url to the ban list Settings.CurrentSettings.BannedImages.Add(banString); //save the settings file Settings.CurrentSettings.Save(Settings.AppPath + "\\settings.conf"); try { //delete the file from the local disk File.Delete(p.LocalPath); } catch (Exception ex) { Log.Logger.Write(string.Format("Error deleting banned pictures. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } //skip to next photo SkipToNextPicture(); }
public PictureDownload GetPicture(Picture pic, bool queueForDownload) { //check if the requested image exists, if it does then return //if image already has a local path then use it (just what we need for local provider where images are not stored in cache). var picturePath = string.IsNullOrEmpty(pic.LocalPath) ? pic.CalculateLocalPath(SaveFolder) : pic.LocalPath; pic.LocalPath = picturePath; if (pic.IsGood) { //if the wallpaper image already exists, and passes our 0 size check then fire the event return new PictureDownload(pic); } var fi = new FileInfo(picturePath); //for files that do not exist "Delete" does nothing per MSDN docs try { fi.Delete(); } catch (Exception ex) { Log.Logger.Write(string.Format("Error deleting 0 byte file '{0}' while prepareing to redownload it. Exception details: {1}", fi.FullName, ex.ToString()), Log.LoggerLevels.Errors); } PictureDownload pd = new PictureDownload(pic); if (queueForDownload) { //add file to Queue QueuePicture(pd); } return pd; }
/// <summary> /// Retrieves a random picture from the picture list /// </summary> /// <param name="pl">Picture list from which to retrieve pictures</param> /// <param name="saveFolder">Location where to save the picture</param> /// <param name="currentPicture">(optional) the current picture, to avoid repeates. Pass null if not needed or this is the first picture.</param> public PictureDownload GetPicture(PictureList pl, Picture currentPicture, bool queueForDownload) { Picture pic = null; if (pl == null || pl.Pictures.Count == 0) return null; //pick the next picture at random // only "non-random" bit is that we make sure that the next random picture isn't the same as our current one var index = 0; do { index = rnd.Next(pl.Pictures.Count); } while (currentPicture != null && currentPicture.Url == pl.Pictures[index].Url); pic = pl.Pictures[index]; //download current picture first PictureDownload pd = GetPicture(pic, queueForDownload); return pd; }
//find links to pages with wallpaper only with matching resolution private List<Picture> ParsePictures(string content) { var picsRegex = new Regex("<a href=\"(?<link>http://wallbase.cc/wallpaper/.*?)\".*?>.*?<img.*?data-original=\"(?<img>.*?)\".*?</a>", RegexOptions.Singleline); var picsMatches = picsRegex.Matches(content); var result = new List<Picture>(); for (var i = 0; i < picsMatches.Count; i++) { var pic = new Picture(); pic.Url = picsMatches[i].Groups["link"].Value; pic.Properties.Add(Picture.StandardProperties.Thumbnail, picsMatches[i].Groups["img"].Value); result.Add(pic); } resultCount = result.Count; return result; }
public PictureList GetPictures(PictureSearch ps) { var result = new PictureList() { FetchDate = DateTime.Now }; //load provider search settings GoogleImageSearchSettings giss = GoogleImageSearchSettings.LoadFromXML(ps.SearchProvider.ProviderConfig) ?? new GoogleImageSearchSettings(); //if search is empty, return now since we can't search without it if (string.IsNullOrEmpty(giss.Query)) return result; var pageIndex = ps.PageToRetrieve; //set page to retrieve if one specified var imgFoundCount = 0; //if max picture count is 0, then no maximum, else specified max var maxPictureCount = ps.MaxPictureCount > 0?ps.MaxPictureCount : int.MaxValue; //build tbs strring var tbs = "";//isz:ex,iszw:{1},iszh:{2} //handle sizeing if (giss.ImageHeight > 0 && giss.ImageWidth > 0) { tbs += string.Format("isz:ex,iszw:{0},iszh:{1},", giss.ImageWidth, giss.ImageHeight); } //handle colors if (!string.IsNullOrEmpty(giss.Color)) { tbs += GoogleImageSearchSettings.GoogleImageColors.GetColorSearchString((from c in GoogleImageSearchSettings.GoogleImageColors.GetColors() where c.Value == giss.Color select c).Single()) + ","; } //if we have a filter string then add it and trim off trailing commas if (!string.IsNullOrEmpty(tbs)) tbs = ("&tbs=" + tbs).Trim(new char[]{','}); //do safe search setup (off/strict/moderate) this is part of the session and tracked via cookies //SetSafeSearchSetting(giss.GoogleSafeSearchOption); do { //build URL from query, dimensions and page index var url = string.Format(baseURL, giss.Query, tbs, (pageIndex * 20)); var response = string.Empty; using (var client = new HttpUtility.CookieAwareWebClient(_cookies)) { response = client.DownloadString(url); } var images = _imagesRegex2.Matches(response); //track number of images found for paging purposes imgFoundCount = images.Count; //convert images found into picture entries foreach (Match item in images) { var purl = item.Groups["imgurlgrp"].Value; var referrer = item.Groups["imgrefgrp"].Value; var thumbnail = item.Groups["thumbURL"].Value; //get id and trim if necessary (ran into a few cases of rediculously long filenames) var id = System.IO.Path.GetFileNameWithoutExtension(purl); if (id.Length > 50) id = id.Substring(0, 50); //because google images come from so many sites it's not uncommon to have duplicate file names. (we fix this) id = string.Format("{0}_{1}", id, purl.GetHashCode()); var p = new Picture() { Url = purl, Id = id }; p.Properties.Add(Picture.StandardProperties.Thumbnail, thumbnail); p.Properties.Add(Picture.StandardProperties.Referrer, referrer); result.Pictures.Add(p); } //if we have an image ban list check for them // doing this in the provider instead of picture manager // ensures that our count does not go down if we have a max if (ps.BannedURLs != null && ps.BannedURLs.Count > 0) { result.Pictures = (from c in result.Pictures where !(ps.BannedURLs.Contains(c.Url)) select c).ToList(); } //increment page index so we can get the next 20 images if they exist pageIndex++; // Max Picture count is defined in search settings passed in, check for it here too } while (imgFoundCount > 0 && result.Pictures.Count < maxPictureCount && ps.PageToRetrieve == 0); result.Pictures = result.Pictures.Take(maxPictureCount).ToList(); return result; }