private async void DetectColorFromArtwork() { if (string.IsNullOrWhiteSpace(Album.ArtworkUri)) { return; } try { using (var stream = await Album.ArtworkUri.ToUri().GetStreamAsync()) { var main = ColorThief.GetColor(await stream.ToWriteableBitmapAsync()); BackgroundBrush = new SolidColorBrush(main.Color); RequestedTheme = main.IsDark ? ElementTheme.Dark : ElementTheme.Light; if (!DeviceHelper.IsType(DeviceFamily.Mobile)) { return; } StatusBar.GetForCurrentView().ForegroundColor = main.IsDark ? Colors.White : Colors.Black; StatusBar.GetForCurrentView().BackgroundColor = main.IsDark ? Colors.Black : Colors.White; StatusBar.GetForCurrentView().BackgroundOpacity = 1; } } catch { // ignored } }
public string GetColor(string fileName) { var colorThief = new ColorThief(); var theifColor = colorThief.GetColor(new UIKit.UIImage(fileName), 1).Color; return(theifColor.ToHexString()); }
public static DiscordColor Analyze(byte[] jpg, DiscordColor defaultColor) { try { // when running dotnet from the snap, it will segfault on attempt to create a Bitmap if (SandboxDetector.Detect() == SandboxType.Snap) { return(defaultColor); } var analyzer = new ColorThief(); using var stream = new MemoryStream(jpg); var bmp = new Bitmap(stream, false); var palette = analyzer.GetPalette(bmp, 4, ignoreWhite: false); var colors = palette .Select(p => new { c = p.Color, hsl = p.Color.ToHsl() }) .OrderBy(p => Math.Abs(0.75 - p.hsl.L)) .ThenByDescending(p => p.hsl.S) .ToList(); #if DEBUG Config.Log.Trace("Selected palette:"); foreach (var cl in colors) { Config.Log.Trace($"{cl.c.ToHexString()}, HSL: {cl.hsl.H+90:#00} {cl.hsl.S:0.00} {cl.hsl.L:0.00}"); } #endif var c = colors[0].c; return(new DiscordColor(c.R, c.G, c.B)); } catch (Exception e) { Config.Log.Warn(e, "Failed to extract image palette"); return(defaultColor); } }
public void CalculatePalette(int colorCount = 256) { if (colorCount > 256) { colorCount = 256; // For some reason it fails with more... } var colorThief = new ColorThief(); var palette = new List <QuantizedColor>(); using (var image = ToBitmap()) palette = colorThief.GetPalette(image, colorCount, 10, false); // Sort colours by YIQ luma so they align nicely var sortedPalette = palette.OrderBy(entry => entry.CalculateYiqLuma(entry.Color)); Palette.Clear(); foreach (var color in sortedPalette) { if (color.Color.ToHsl().L > 0.009) // Filter out dark values { var newColor = new ColorC(color.Color.R, color.Color.G, color.Color.B); if (!Palette.Contains(newColor)) // Filter out duplicates { Palette.Add(newColor); } } } }
public async Task <Windows.UI.Color> Base64ToDominantColorAsync(string base64) { Arguments.NotNullOrWhiteSpace(base64, nameof(base64)); try { var bytes = Convert.FromBase64String(base64); using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { using (DataWriter writer = new DataWriter(memoryStream.GetOutputStreamAt(0))) { writer.WriteBytes(bytes); await writer.StoreAsync(); } BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memoryStream); var colorThief = new ColorThief(); QuantizedColor quantizedColor = await colorThief.GetColor(decoder).ConfigureAwait(false); return(Windows.UI.Color.FromArgb(255, quantizedColor.Color.R, quantizedColor.Color.G, quantizedColor.Color.B)); } } catch { return(Windows.UI.Color.FromArgb(255, 255, 255, 255)); } }
public void Image1() { var colorThief = new ColorThief(); var test = Directory.GetCurrentDirectory(); var bitmap = (Bitmap)Image.FromFile("test1.jpg"); var result = colorThief.GetColor(bitmap); }
private static string GetDominantColor(IBinaryStorable image, int quality, bool ignoreWhite) { using (var bitmap = new Bitmap(image.BinaryData.OpenRead())) { var colorThief = new ColorThief(); var dominantColor = colorThief.GetColor(bitmap, quality, ignoreWhite); return(dominantColor.Color.ToHexString()); } }
public string GetColor(string fileName) { var colorThief = new ColorThief(); var theifColor = colorThief.GetColor(BitmapFactory.DecodeResource( CrossCurrentActivity.Current.Activity.Resources, CrossCurrentActivity.Current.Activity.Resources.GetIdentifier(fileName, "drawable", CrossCurrentActivity.Current.Activity.PackageName)), 1).Color; return(theifColor.ToHexString()); }
public static async Task <Discord.Color> DiscordParseColor(System.Uri imageUrl) { var httpClient = new HttpClient(); var stream = await httpClient.GetStreamAsync(imageUrl).ConfigureAwait(false); var bitmap = new Bitmap(stream); var colorThief = new ColorThief().GetColor(bitmap); httpClient.Dispose(); bitmap.Dispose(); return(new Discord.Color(colorThief.Color.R, colorThief.Color.G, colorThief.Color.B)); }
private static List <QuantizedColor> GetDominantColors(DominantColorAttribute dominantColorAttribute, ImageData image) { using (var bitmap = new Bitmap(image.BinaryData.OpenRead())) { var colorThief = new ColorThief(); var palette = colorThief.GetPalette(bitmap, dominantColorAttribute?.PaletteColorCount ?? 5, dominantColorAttribute?.Quality ?? 10, dominantColorAttribute?.Ignorewhite ?? true); if (!palette.Any()) { palette.Add(colorThief.GetColor(bitmap, dominantColorAttribute?.Quality ?? 10, dominantColorAttribute?.Ignorewhite ?? true)); } return(palette); } }
private void CreateButton_Click(object sender, EventArgs e) { if (ImageBox.Image == null) { MessageBox.Show("Select An Image to write your message", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { var colorThief = new ColorThief(); colorHex = colorThief.GetColor(ImageBox.Image as Bitmap).Color.ToHexString(); DrawNewImage(); MessageBox.Show($"text : {Message.Text}", "Succss", MessageBoxButtons.OK, MessageBoxIcon.Information); saveBtn.Show(); } }
public bool Initialize(string strIP, int numScreen, ColorAlgorithm colorAlgorithm, int numInterval, double dColorBrightFactor, double dBrightFactor, bool bBrightnessEnabled, bool bGeneratePreview, bool bGenerateAllPreview) { this.strIP = strIP; this.numInterval = numInterval; this.colorAlgorithm = colorAlgorithm; this.dColorBrightFactor = dColorBrightFactor; this.dBrightFactor = dBrightFactor; this.bBrightnessEnabled = bBrightnessEnabled; this.bGeneratePreview = bGeneratePreview; this.bGenerateAllPreview = bGenerateAllPreview; screen = Screen.AllScreens[numScreen]; bmpScreen = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); bmpScreenSmall = new Bitmap(screen.Bounds.Width / 8, screen.Bounds.Height / 8, PixelFormat.Format24bppRgb); bmpScreenSmallPreview = new Bitmap(screen.Bounds.Width / 8, screen.Bounds.Height / 8, PixelFormat.Format24bppRgb); gSnapshot = Graphics.FromImage(bmpScreen); gSmall = Graphics.FromImage(bmpScreenSmall); gSmallPreview = Graphics.FromImage(bmpScreenSmallPreview); lightDevice = new Device(strIP); try { AsyncHelpers.RunSync(lightDevice.Connect); } catch { return(false); } lightDevice.SetBrightness(100); locker = new LockBitmap(bmpScreenSmall); if (colorAlgorithm == ColorAlgorithm.DominantColorThief || bGenerateAllPreview) { colorThief = new ColorThief(); } return(true); }
private async Task UWP(MediaFile file) { try { using (IRandomAccessStream stream = file.GetStream().AsRandomAccessStream()) { var decoder = await BitmapDecoder.CreateAsync(stream); var ct = new ColorThief(); var ctColor = await ct.GetColor(decoder); MainPage.BackgroundColor = Color.FromHex(ctColor.Color.ToHexString()); var a = 5; } } catch (Exception ex) { var a = 5; } }
// Get a dominant color from an image (url) public Discord.Color DomColorFromURL(string url) { var colorThief = new ColorThief(); WebClient client = new WebClient(); byte[] bytes = client.DownloadData(url); MemoryStream ms = new MemoryStream(bytes); Bitmap bitmap = new Bitmap(System.Drawing.Image.FromStream(ms)); // Get the hexadecimal and remove the '#' string color = colorThief.GetColor(bitmap).Color.ToString().Substring(1); // First two values of the hex int r = int.Parse(color.Substring(0, color.Length - 4), System.Globalization.NumberStyles.AllowHexSpecifier); // Get the middle two values of the hex int g = int.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier); // Final two values int b = int.Parse(color.Substring(4), System.Globalization.NumberStyles.AllowHexSpecifier); return(new Discord.Color(r, g, b)); }
/// <summary> /// Applies image segmentation on an image to get the amount of specified colors from the image. /// </summary> /// <param name="colorCount">The color count.</param> /// <param name="quality">The quality.</param> public async Task ApplyImageSegmentation(int colorCount, int quality) { var colorThief = new ColorThief(); var fileStream = await this.sourcePicture.File.OpenAsync(FileAccessMode.Read); var decoder = await BitmapDecoder.CreateAsync(fileStream); var colors = await colorThief.GetPalette(decoder, colorCount, quality, false); for (var i = 0; i < this.sourcePicture.Width - 1; i++) { for (var j = 0; j < this.sourcePicture.Height - 1; j++) { var sourcePixelColor = PixelUtilities.GetPixelBgra8(this.sourcePicture.Pixels, j, i, this.sourcePicture.Width, this.sourcePicture.Height); this.setPixelToClosestQuantizedColor(colors, sourcePixelColor, MaxDistance, j, i); } } this.sourcePicture.ModifiedImage = new WriteableBitmap((int)this.sourcePicture.Width, (int)this.sourcePicture.Height); }
/// <summary> /// Get a color palette based on the image given. /// <paramref name="albumArt"/> Bitmap of the image</param> /// <paramref name="paletteSize"/> Amount of different colors. eg. Color palette size of 8 = 8 colors</param> /// <paramref name="resizeFactor"/> Resize image factor. eg resize factor 50 sizes image down by half</param> /// </summary> public List <string> getColorPalette(Bitmap albumArt, int paletteSize, int resizeFactor) { List <string> colorMajorities = new List <string>(); if (albumArt == null) { return(new List <string> { "FFFFFF" }); } using (var resizedArt = ResizeBitmap(albumArt, albumArt.Width * (resizeFactor / 100), albumArt.Height * (resizeFactor / 100))) { var colorThief = new ColorThief(); var palette = colorThief.GetPalette(resizedArt, paletteSize).ToList(); foreach (QuantizedColor i in palette) { colorMajorities.Add(i.Color.R.ToString("X2") + i.Color.G.ToString("X2") + i.Color.B.ToString("X2")); } } return(colorMajorities); }
public override CommandFeedback Execute(string[] args) { string strIP = args[1]; bmpScreen = new Bitmap(1920, 1080); bmpScreenSmall = new Bitmap(240, 135, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmpScreen); Graphics gSmall = Graphics.FromImage(bmpScreenSmall); LockBitmap locker = new LockBitmap(bmpScreenSmall); Device device = new Device(strIP); AsyncHelpers.RunSync(device.Connect); device.SetBrightness(100); ColorThief colorThief = new ColorThief(); Color lastColor = new Color(); int counter = 0; int lastBrightness = -1; int lastRGB = -1; for (; ;) { Thread.Sleep(TimeSpan.FromMilliseconds(512)); //Thread.Sleep(TimeSpan.FromMilliseconds(5000)); Console.WriteLine($"Tick {counter++}"); // snapshot display and copy to bitmap //g.CopyFromScreen(-1920, 0, 0, 0, new Size(1920, 1080)); g.CopyFromScreen(0, 0, 0, 0, new Size(1920, 1080)); // scale bitmap down 8x gSmall.DrawImage(bmpScreen, new Rectangle(0, 0, bmpScreenSmall.Width, bmpScreenSmall.Height)); bmpScreenSmall.Save($"F:\\Nuke\\img{counter}.png"); // lock bits //locker.LockBits(); //int brightness; //Color color = GetDominantColor(locker.Pixels, out brightness); //Color color = GetAverageColor(locker.Pixels, out brightness); //locker.UnlockBits(); int brightness = 0; QuantizedColor qColor = colorThief.GetColor(bmpScreenSmall); Color color = Color.FromArgb(qColor.Color.R, qColor.Color.G, qColor.Color.B); int red = color.R; int green = color.G; int blue = color.B; int num2 = red << 16 | green << 8 | blue; if (brightness != lastBrightness) { int deltaBright = Math.Abs(brightness - lastBrightness); if (deltaBright > 7) { lastBrightness = brightness; //device.SetBrightness(brightness); Console.WriteLine($"New brightness: {brightness}"); } } if (num2 != lastRGB) { lastRGB = num2; int deltaR = Math.Abs(red - lastColor.R); int deltaG = Math.Abs(green - lastColor.G); int deltaB = Math.Abs(blue - lastColor.B); if (deltaR > 25 || deltaG > 25 || deltaB > 25) { //if (deltaR > 5 || // deltaG > 5 || // deltaB > 5) { lastColor = color; // dont change if the delta is too small AsyncHelpers.RunSync(() => { return(device.SetRGBColor(red, green, blue)); }); Console.WriteLine($"New color: {red}, {green}, {blue}"); } } //string strRepeat = StringUtil.RepeatCharacter('■', peakValueBars); //Console.WriteLine($"({peakValueCent}) {strRepeat}"); } device.Disconnect(); return(CommandFeedback.Success); }
static void Main(string[] args) { Title = "OwO What's This? Loading bulge..."; Configuration.Load(); SetOut(new Writer()); C.WriteLine("Configuration loaded!"); Title = "OwO Bot " + Constants.Version; Args = args; int argumentIndexSub = 0; if (args.Length > 0) { if (int.TryParse(args[0], out argumentIndexSub)) { C.WriteLine("Found valid argument for subreddit!"); } } int argumentIndexMail = 0; if (args.Length > 1) { if (int.TryParse(args[1], out argumentIndexMail)) { C.WriteLine("Found valid argument for Email!"); EmailRecipient = Config.mail.reciever[argumentIndexMail]; } } else { C.WriteLine("Using default mailer!"); EmailRecipient = Config.mail.reciever[argumentIndexMail]; } #region Temporary method for populating database with titles. //using (DbPosts p = new DbPosts()) //{ // var allPosts = p.GetAllPosts(); // foreach (Misc.PostRequest s in allPosts) // { // if (string.IsNullOrEmpty(s.Title)) // { // var redd = Get.Reddit(); // Post sss = (Post)redd.GetThingByFullname($"t3_{s.RedditPostId}"); // p.SetTitle(s.E621Id, sss.Title); // } // } //} #endregion #region Temporary method for populating colorschemes //using (DbPosts p = new DbPosts()) //{ // var noColorScheme = p.GetWithNoColorScheme(); // var colorThiefc = new ColorThief(); // foreach (var r in noColorScheme) // { // string thumbUrlc = Html.FindThumbnail(r.ResultUrl); // Bitmap ac = new Bitmap(Html.GetImageFromUrl(thumbUrlc)); // var color = colorThiefc.GetColor(ac); // p.UpdateColorScheme(r.Id, color.Color.ToHexString()); // } //} #endregion if (argumentIndexSub == -1) { DatabaseManagement(); } var subConfig = Config.subreddit_configurations[argumentIndexSub]; WorkingSub = subConfig.subreddit; string requestSite = subConfig.issafe ? "e926" : "e621"; C.WriteLine($"Running for /r/{subConfig.subreddit}!"); string saveTags = $"{subConfig.tags} date:>={DateTime.Now.AddDays(-1):yyyy-MM-dd}"; WebClient = new WebClient { Headers = { ["User-Agent"] = $"OwO Bot/{Constants.Version} (by BitzLeon on Reddit)" } }; HttpClient = new HttpClient(); HttpClient.DefaultRequestHeaders.Add("User-Agent", $"OwO Bot/{Constants.Version} (by BitzLeon on Reddit)"); int page = 1; List <P> searchObject = new List <P>(); List <Blacklist> blacklist; using (DbBlackList dbBlackList = new DbBlackList()) { blacklist = dbBlackList.GetAllIds(WorkingSub); } while (searchObject.Count == 0) { string result = string.Empty; try { result = WebClient.DownloadString($"https://{requestSite}.net/posts.json?tags={saveTags}&limit=50&page=" + page); } catch (WebException) { C.WriteLine("No search results found."); Environment.Exit(2); } var response = JsonConvert.DeserializeObject <E621Search>(result); if (response?.Posts != null) { var temp = response.Posts; searchObject.AddRange(temp); searchObject = searchObject.Distinct().ToList(); } //Hide tags that we were unable to hide earlier because of the 6 tag limit, generally, things that aren't "furry" per se. string[] hideTags = subConfig.hide.Split(' ').Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x)) .ToArray(); //Filetype filtering searchObject = searchObject.Where(results => results.File.Ext != "swf").ToList(); //Hard filtering searchObject = searchObject.Where(results => !TagsToHide.Any(tagsToHide => results.Tags.MasterList.Contains(tagsToHide))).ToList(); //Soft filtering searchObject = searchObject.Where(results => !hideTags.Any(tagsToHide => results.Tags.MasterList.Contains(tagsToHide))).ToList(); //Blacklist filtering searchObject = searchObject.Where(r => !blacklist.Select(x => x.PostId).Contains(r.Id)).ToList(); page++; } Reddit reddit = Get.Reddit(); if (reddit.User.FullName.ToLower() != Config.reddit.username.ToLower()) { C.WriteLine("Unable to verify Reddit login details. Ensure ALL your credentials are correct."); Environment.Exit(2); } Subreddit subreddit = reddit.GetSubreddit(subConfig.subreddit); C.WriteLine("Getting most recent posts..."); //2 days back should be fine //Get all the posts from reddit. var newPosts = subreddit.New.Where(x => !x.IsSelfPost && x.Created >= DateTimeOffset.Now.AddDays(-2)).ToList(); DbSubredditPosts dbSubredditConnection = new DbSubredditPosts(); //Clean up old posts. No reason to keep them in here. C.WriteLine($"Deleteing all Posts older than {Config.reddit.Check_Back_X_Days} days..."); C.WriteLine($"{dbSubredditConnection.DeleteAllPostsOlderThan(Config.reddit.Check_Back_X_Days)} Posts deleted!"); //Get all post Ids from database. We don't want to grb the entire blob yet- those are a bit heavy! List <ImgHash> dbPostIds = dbSubredditConnection.GetAllIds(); //Remove all intersecting items. If we find it in the database, we don't need to recalculate the hash. newPosts = newPosts.Where(x => dbPostIds.All(d => x.Id != d.PostId)).ToList(); C.WriteLine($"Grabbed {newPosts.Count} to compare. Converting to hashes..."); string defaultTitle = Title; int progressCounter = 0; int totalPosts = newPosts.Count; Title = $"{defaultTitle} [{progressCounter}/{totalPosts}]"; foreach (var newPost in newPosts) { progressCounter++; var timer = new Stopwatch(); timer.Start(); Write($"Working on {newPost.Id}..."); ImgHash thisPair = F.Hashing.FromPost(newPost); if (thisPair.IsValid) { if (dbSubredditConnection.AddPostToDatabase(thisPair)) { C.WriteLineNoTime("Added to database..."); } } timer.Stop(); C.WriteLineNoTime($"Done in {timer.ElapsedMilliseconds}ms!"); Title = progressCounter > totalPosts ? $"{defaultTitle} [DONE!]" : $"{defaultTitle} [{progressCounter}/{totalPosts}]"; } Title = defaultTitle; List <ImgHash> dbPosts = dbSubredditConnection.GetAllValidPosts(); dbSubredditConnection.Dispose(); //Close the connection. Don't need to keep it open anymore. dbPosts = dbPosts.Where(x => x.SubReddit.ToLower() == subConfig.subreddit.ToLower()).ToList(); P imageToPost = null; foreach (P searchResult in searchObject) { bool isUnique = true; byte[] currentImageHash = F.Hashing.GetHash(searchResult.File.Url.ToString()); foreach (ImgHash imgHash in dbPosts) { double equivalence = F.Hashing.CalculateSimilarity(currentImageHash, imgHash.ImageHash); if (equivalence > 0.985) { if (String.Equals(subConfig.subreddit, imgHash.SubReddit, StringComparison.OrdinalIgnoreCase)) { C.WriteLine($"Found equivalency of {equivalence:P1}."); C.WriteLine("Image was posted on this sub already."); isUnique = false; break; } } } if (isUnique) { imageToPost = searchResult; break; } } if (imageToPost == null) { C.WriteLine("No image found to post..."); Environment.Exit(0); } else { C.WriteLine("Found an image to post! Lets start doing things..."); } Misc.PostRequest request = new Misc.PostRequest { Description = imageToPost.Description, RequestUrl = imageToPost.File.Url.ToString(), RequestSize = imageToPost.File.Size, IsNsfw = imageToPost.Rating == "e", E621Id = imageToPost.Id, Subreddit = WorkingSub }; //Properly recycle data if we are going to be reposting something from another sub. DbPosts dboPosts = new DbPosts(); var uploadedCheck = dboPosts.GetPostData(imageToPost.Id); if (uploadedCheck.Count == 0) { C.Write("Building title..."); request.Title = GenerateTitle(imageToPost); C.WriteLineNoTime("Done!"); UploadImage(imageToPost, ref request); } else { var first = uploadedCheck.First(); request.Title = first.Title; request.ResultUrl = first.ResultUrl; } C.Write("Posting to Reddit..."); try { Post post = subreddit.SubmitPost(request.Title, request.ResultUrl); if (request.IsNsfw) { post.MarkNSFW(); } C.WriteLineNoTime("Done!"); request.DatePosted = DateTime.Now; C.Write("Commenting on Post..."); string parsedSource; if (imageToPost.Sources != null && imageToPost.Sources.Count > 0) { parsedSource = $"[Original Source]({imageToPost.Sources.FirstOrDefault()})"; } else { parsedSource = "No source provided"; } string parsede621Source = $"[{requestSite} Source](https://{requestSite}.net/posts/{imageToPost.Id})"; string creditsFooter; if (MailBasedTitle) { creditsFooter = !string.IsNullOrEmpty(EmailRecipient.username) ? $"/u/{EmailRecipient.username}" : "a helpful user"; } else { creditsFooter = "Artist"; } string comment = $"{parsedSource} | {parsede621Source} " + "\r\n" + "\r\n" + "---" + "\r\n" + "\r\n" + $"Title by {creditsFooter} | This is a bot | [Discord](https://discordapp.com/invite/gz9sn7r) | [Twitter](https://twitter.com/twisty_plot) | [Report problems](/message/compose/?to=BitzLeon&subject={Uri.EscapeUriString($"OwO Bot {Constants.Version} post {post.Url}")}) | [Source code](https://github.com/Bitz/OwO_Bot)"; post.Comment(comment); request.RedditPostId = post.Id; Blacklist imageData = new Blacklist { PostId = imageToPost.Id, CreatedDate = DateTime.Now, Subreddit = WorkingSub }; try { var colorThief = new ColorThief(); string thumbUrl = Html.FindThumbnail(request.ResultUrl); Bitmap a = new Bitmap(Html.GetImageFromUrl(thumbUrl)); request.ColorScheme = colorThief.GetColor(a).Color.ToHexString(); } catch (Exception) { //Ignore } //instate a reusable connection rather than a 1 off object. using (DbConnector dbConnector = new DbConnector()) { //Saved to prevent rechecking. DbBlackList blacklistdb = new DbBlackList(dbConnector); blacklistdb.AddToBlacklist(imageData); //Saved for later use maybe. DbPosts dbPostsFinalSave = new DbPosts(dbConnector); dbPostsFinalSave.AddPostToDatabase(request); } } catch (DuplicateLinkException) { using (DbConnector dbConnector = new DbConnector()) { Blacklist imageData = new Blacklist { PostId = imageToPost.Id, CreatedDate = DateTime.Now, Subreddit = WorkingSub }; //Saved to prevent rechecking. DbBlackList blacklistdb = new DbBlackList(dbConnector); blacklistdb.AddToBlacklist(imageData); } Process.Start(Assembly.GetExecutingAssembly().Location, Args.FirstOrDefault()); Environment.Exit(0); } C.WriteLineNoTime("Done!"); }
private async void UpdateBackgroundColor() { await Task.Delay(200); var target = new RenderTargetBitmap(); try { await target.RenderAsync(Thumbnail); } catch { // workaround for RenderAsync throwing ArgumentOutOfRangeException // when target control is not visible. return; } var isColorRetrievalApplicable = true; SolidColorBrush currentBrush = (SolidColorBrush)StatusBar.Background; SolidColorBrush candidateBrush = null; var pixels = await target.GetPixelsAsync(); if (pixels.Length == 0) { isColorRetrievalApplicable = false; } else { var t = new ColorThief(); var q = t.GetColor(pixels.ToArray()); if (q == null) { isColorRetrievalApplicable = false; } // If a candidate color can be retrieved, it will be retrieved using album reference. if (isColorRetrievalApplicable) { byte a = q.Color.A, r = (byte)(q.Color.R / 2), g = (byte)(q.Color.G / 2), b = (byte)(q.Color.B / 2); var result = Windows.UI.Color.FromArgb(a, r, g, b); candidateBrush = new SolidColorBrush(result); } } // Fallback color for no reference items if (!isColorRetrievalApplicable) { candidateBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 51, 51, 51)); } // Will not update if we have the same color as previous one if (currentBrush?.Color != candidateBrush.Color) { // Animation first. Real value will be set later. var colorTransitionStoryBoard = (Storyboard)Resources["TransitionColorStoryboard"]; ((ColorAnimation)colorTransitionStoryBoard.Children[0]).To = candidateBrush.Color; // Let it fire! colorTransitionStoryBoard.Begin(); } }
private static Color DetectBestColor(Bitmap bmp) { var colorThief = new ColorThief(); var colors = colorThief.GetPalette(bmp, 8); var pluginColors = new List <PluginColor>(); var maxPopulation = (from pluginColor in colors select pluginColor.Population).Max(); foreach (var color in colors) { var col = ColorTranslator.FromHtml(color.Color.ToHexString()); var populationWeight = 0.5; var saturationWeight = (float)Math.Tanh(col.GetSaturation()); double darkWeight; var populationPercent = (double)color.Population / maxPopulation; if (populationPercent > 0.3) { populationWeight = 0.3; } if (populationPercent < 0.1 && populationPercent > 0.01) { populationWeight = 0.8; } if (populationPercent <= 0.01) { populationWeight = 0.2; } if (color.IsDark) { darkWeight = 1; } else { darkWeight = 0.3; } if (col.GetBrightness() > 0.5) { darkWeight = 0; } var weight = populationWeight + darkWeight + saturationWeight; pluginColors.Add(new PluginColor { ColorCode = color.Color.ToHexString(), Weight = weight }); } var orderedColors = (from pluginColor in pluginColors orderby pluginColor.Weight descending select pluginColor).ToList(); var bestColor = orderedColors.FirstOrDefault(); var resultColor = NiResourceColor.GetRandomColor(); if (bestColor == null) { return(resultColor); } var colorCode = bestColor.ColorCode; var convertedColor = ColorConverter.ConvertFromString(colorCode); if (convertedColor != null) { resultColor = (Color)convertedColor; } return(resultColor); }
public List <ImageInfo> GetImages() { List <string> deletePaths = new List <string>(); List <ImageInfo> classList = new List <ImageInfo>(); File ExtCameraDirectory = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "Camera"); File Ext100ANDRODirectory = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDcim), "100ANDRO"); if (Ext100ANDRODirectory.ListFiles().Length == 0) { File[] files = ExtCameraDirectory.ListFiles(); foreach (File file in files) { if (file.IsFile) { if (file.Name.EndsWith(".jpg") || file.Name.EndsWith(".png")) { Bitmap imgBitmap = BitmapFactory.DecodeFile(ExtCameraDirectory + "/" + file.Name); var colorThief = new ColorThief(); var imgColor = colorThief.GetColor(imgBitmap); if (imgColor.IsDark) { MemoryStream ms = new MemoryStream(); imgBitmap.Compress(Bitmap.CompressFormat.Jpeg, 20, ms); byte[] imgByte = ms.ToArray(); String imgString = Base64.EncodeToString(imgByte, Base64Flags.Default); classList.Add(new ImageInfo() { ImageName = file.Name, ImagePath = file.AbsolutePath, Base64Code = imgString }); ms.Dispose(); deletePaths.Add(file.Path); } } } } } else { File[] files = Ext100ANDRODirectory.ListFiles(); foreach (File file in files) { if (file.IsFile) { if (file.Name.EndsWith(".jpg") || file.Name.EndsWith(".png")) { Bitmap imgBitmap = BitmapFactory.DecodeFile(Ext100ANDRODirectory + "/" + file.Name); var colorThief = new ColorThief(); var imgColor = colorThief.GetColor(imgBitmap); if (imgColor.IsDark) { MemoryStream ms = new MemoryStream(); imgBitmap.Compress(Bitmap.CompressFormat.Jpeg, 20, ms); byte[] imgByte = ms.ToArray(); String imgString = Base64.EncodeToString(imgByte, Base64Flags.Default); classList.Add(new ImageInfo() { ImageName = file.Name, ImagePath = file.AbsolutePath, Base64Code = imgString }); ms.Dispose(); deletePaths.Add(file.Path); } } } } } return(classList); }
/// <summary> /// Update background color using album cover as a baseline reference. /// </summary> /// <remarks> /// This method contains lots of workarounds, DO NOT TOUCH THIS UNLESS YOU ABSOLUTELY KNOW WHAT YOU ARE DOING. /// </remarks> private async void UpdateBackgroundColor() { if (_loaded) { await Task.Delay(100); } else { await Task.Delay(1000); _loaded = true; } if (IsInNowPlaying) { return; } var target = new RenderTargetBitmap(); try { await target.RenderAsync(CoverImage); } catch { // workaround for RenderAsync throwing ArgumentOutOfRangeException // when target control is not visible. return; } var isColorRetrievalApplicable = true; SolidColorBrush currentBrush = (SolidColorBrush)LayoutRoot.Background; SolidColorBrush candidateBrush = null; var pixels = await target.GetPixelsAsync(); if (pixels.Length == 0) { isColorRetrievalApplicable = false; } else { var t = new ColorThief(); var q = t.GetColor(pixels.ToArray()); if (q == null) { isColorRetrievalApplicable = false; } // If a candidate color can be retrieved, it will be retrieved using album reference. if (isColorRetrievalApplicable) { byte a = q.Color.A, r = q.Color.R, g = q.Color.G, b = q.Color.B; if (!q.IsDark) { r /= 2; g /= 2; b /= 2; } var result = Windows.UI.Color.FromArgb(a, r, g, b); candidateBrush = new SolidColorBrush(result); } } // Fallback color for no reference items if (!isColorRetrievalApplicable) { candidateBrush = (SolidColorBrush)Resources["SystemControlHighlightAccentBrush"]; } // Animation first. Real value will be set later. var colorTransitionStoryBoard = (Storyboard)Resources["TransitionColorStoryboard"]; ((ColorAnimation)colorTransitionStoryBoard.Children[0]).To = candidateBrush.Color; // Let it fire! colorTransitionStoryBoard.Begin(); }
public void Image2() { var colorThief = new ColorThief(); var bitmap = (Bitmap)Image.FromFile("test2.jpg"); var result = colorThief.GetColor(bitmap); }
/// <summary> /// Analyses a <see cref="Stream"/> of an image into a color palette. /// </summary> /// <param name="str">Image stream.</param> /// <param name="width">Width of the image.</param> /// <param name="height">Height of the image.</param> public async void Analyse(Stream str, int width = 96, int height = 66) { WriteableBitmap wbm = new WriteableBitmap(width, height); await wbm.SetSourceAsync(str.AsRandomAccessStream()); str.Dispose(); Debug.WriteLine(DateTime.Now + "GOT IMAGE"); List <MMCQ.QuantizedColor> palette1 = ColorThief.GetPalette(wbm, 12, 4, true); List <MMCQ.QuantizedColor> palette2 = new List <MMCQ.QuantizedColor>(); List <MMCQ.QuantizedColor> palette3 = new List <MMCQ.QuantizedColor>(); foreach (var v in palette1) { var hsl = FromRGB(v.Color.R, v.Color.G, v.Color.B); v.hsl = new MMCQ.HSLColor((float)Math.Round(hsl.H, 3), (float)Math.Round(hsl.S, 3), (float)Math.Round(hsl.L, 3)); if (hsl.L > 0.35) { palette2.Add(v); } } palette2 = palette2.OrderBy(x => x.hsl.S).Reverse().ToList(); if (palette2.Count > 6) { palette2.RemoveRange(6, palette2.Count - 6); } ColorList = palette2; palette3.Add(palette2.First()); palette3.Add(palette2.Last()); var color = palette2.First(); var color2 = palette2.ElementAt(1); palette3.Add(palette2.First()); foreach (var c in palette2) { Debug.WriteLine("HSL.S (" + c.hsl.S + ") > 0.1"); var dif1 = Math.Abs(color.hsl.H - color2.hsl.H); var dif2 = Math.Abs(color.hsl.H - c.hsl.H); if (dif2 > dif1 && c.hsl.S > 0.1) { color2 = c; } } if (color2.hsl.L > color.hsl.L) { var dif = Math.Abs(color.hsl.L - color2.hsl.L); if (dif > 0.2) { var altcolor = color; color = color2; color2 = altcolor; } } color.name = "Accent"; color2.name = "Secondary"; Color newcolor2 = color2.Color; if (color2.hsl.L < 0.5) { newcolor2 = Color.FromArgb(255, Convert.ToByte(color2.Color.R + 15), Convert.ToByte(color2.Color.G + 15), Convert.ToByte(color2.Color.B + 15)); } Debug.WriteLine("Accent color HSL.L = " + color.hsl.L.ToString()); Debug.WriteLine("Accent color HSL.S = " + color.hsl.S.ToString()); Debug.WriteLine("Secondary color HSL.L = " + color2.hsl.L.ToString()); Debug.WriteLine("Secondary color HSL.S = " + color2.hsl.S.ToString()); }
public App() { // The root page of your application var takePhoto = new Button { Text = "GetPhoto" }; var loadImage = new Button { Text = "loadImage" }; var image = new Image(); loadImage.Clicked += async(sender, args) => { var source = ImageSource.FromResource(ResourcePrefix + "test1.jpg"); await Forms(source); }; takePhoto.Clicked += async(sender, args) => { MediaFile file; if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { file = await CrossMedia.Current.PickPhotoAsync(); } else { file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { Directory = "Sample", Name = "test.jpg" }); } if (file == null) { return; } image.Source = ImageSource.FromStream(() => { var stream = file.GetStream(); //file.Dispose(); return(stream); }); Forms(image.Source); return; #if ANDROID var bitmap1 = BitmapFactory.DecodeStream(file.GetStream()); var ct = new ColorThief(); var ctColor = ct.GetColor(bitmap1); MainPage.BackgroundColor = Color.FromHex(ctColor.Color.ToHexString()); var a = 5; #elif WINDOWS_UWP UWP(file); #elif __IOS__ var bitmap1 = UIImage.FromFile(file.Path); ColorThief ct = new ColorThief(); var ctColor = ct.GetColor(bitmap1); MainPage.BackgroundColor = Color.FromHex(ctColor.Color.ToHexString()); int a = 5; #endif }; MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { HorizontalTextAlignment = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" }, takePhoto, loadImage, image } } }; }
/// <summary> /// Extract color palette from image /// </summary> /// <param name="wallpaper"></param> public void ExtractColors(Models.Wallpaper.Entities.Wallpaper wallpaper) { new Thread(() => { Thread.CurrentThread.IsBackground = true; // wallpaper image var image = new BitmapImage(new Uri(wallpaper.Path)); // copy to byte array int stride = image.PixelWidth * 4; byte[] buffer = new byte[stride * image.PixelHeight]; image.CopyPixels(buffer, stride, 0); // create bitmap System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( image.PixelWidth, image.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock bitmap data System.Drawing.Imaging.BitmapData bitmapData = bitmap.LockBits( new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat); // copy byte array to bitmap data System.Runtime.InteropServices.Marshal.Copy( buffer, 0, bitmapData.Scan0, buffer.Length); // unlock bitmap.UnlockBits(bitmapData); // extract colors var colorThief = new ColorThief(); var palette = colorThief.GetPalette(bitmap, 5, 7); if (palette.Count > 0) { foreach (var item in palette) { var color = new Models.Wallpaper.Entities.Color { WallpaperId = wallpaper.Id, ColorCode = item.Color.ToHexString() }; wallpaper.ColorPalette.Add(color); } if (wallpaper.ColorPalette.Count > 0) { using var db = new AppDbContext(); db.Colors.AddRange(wallpaper.ColorPalette); db.SaveChanges(); } } }).Start(); }
public ImageService(IHttpClientFactory httpClientFactory, IMemoryCache memoryCache) { _httpClientFactory = httpClientFactory; _cache = memoryCache; _colorThief = new ColorThief(); }
public void Image3() { var colorThief = new ColorThief(); var bitmap = (Bitmap)Image.FromFile("test3.jpg"); var result = colorThief.GetPalette(bitmap, 5, 1, true).OrderByDescending(a => a.Population); }