/// <summary> /// Starts the download /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void FrmDownload_Shown(object sender, EventArgs e) { pbStatus.Maximum = Images.Count; Thread T = new Thread(delegate() { while (Images.Count > 0 && !Exit) { ImgurImage I = Images[0]; Images.RemoveAt(0); //Just cache if path is not defined if (string.IsNullOrEmpty(Path)) { Cache.GetImage(I); } else { string FileName = System.IO.Path.Combine(Path, I.GetImageUrl().Segments.Last()); if (FileName.StartsWith(Path)) { System.IO.File.WriteAllBytes(FileName, Cache.GetImage(I)); } } #if DEBUG System.Diagnostics.Debug.WriteLine($"URL ({I.GetImageUrl()}) tried to get out of {Path}"); #endif Invoke((MethodInvoker) delegate { ++pbStatus.Value; }); } Invoke((MethodInvoker)Done); }) { IsBackground = true }; T.Start(); }
/// <summary> /// Gets the thumbnail associated with the given metadata /// </summary> /// <param name="I">Image metadata</param> /// <returns>Image file, null if not found</returns> /// <remarks>Downloads the image to cache if necessary</remarks> public static byte[] GetThumbnail(ImgurImage I) { string ThumbFile = Path.Combine(_thumbDir, GetThumbnailName(I)); if (!File.Exists(ThumbFile)) { File.WriteAllBytes(ThumbFile, Imgur.GetImage(I, ImgurImageSize.BigSquare, false)); } return(File.ReadAllBytes(ThumbFile)); }
/// <summary> /// Gets the thumbnail associated with the given image id /// </summary> /// <param name="ImageId">Image id</param> /// <returns>Image file, null if not found</returns> /// <remarks>Downloads the image to cache if necessary</remarks> public static byte[] GetThumbnail(string ImageId) { ImgurImage Img = Images.FirstOrDefault(m => m.id == ImageId); if (Img != null) { return(GetThumbnail(Img)); } return(null); }
/// <summary> /// Downloads an image from Imgur /// </summary> /// <param name="I">Imgur image</param> /// <param name="Size">Image size</param> /// <param name="AllowVideo">Allow video files</param> /// <returns>Image data</returns> /// <remarks>If <paramref name="AllowVideo"/> is <see cref="false"/>, it will use <see cref="ImgurImageSize.HugeThumbnail"/> for video files</remarks> public static byte[] GetImage(ImgurImage I, ImgurImageSize Size, bool AllowVideo) { using (WebClient WC = new WebClient()) { if (AllowVideo || !I.type.ToLower().StartsWith("video/")) { return(WC.DownloadData(I.GetImageUrl(Size))); } return(WC.DownloadData(I.GetImageUrl(Size == ImgurImageSize.Original ? ImgurImageSize.HugeThumbnail : Size))); } }
/// <summary> /// Opens the properties of the selected image /// </summary> private void EditSelectedImageTitle() { if (lvImages.SelectedItems.Count > 0) { ImgurImage I = (ImgurImage)lvImages.SelectedItems[0].Tag; using (frmProperties prop = new frmProperties(S, I)) { prop.ShowDialog(); } } }
/// <summary> /// Opens next image /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private void BtnNext_Click(object sender, EventArgs e) { if (Save()) { LastAction = ActionType.Older; ImgurImage img = Application.OpenForms.OfType <FrmMain>().First().NextImage(); if (img != null) { SetImage(img); } } }
/// <summary> /// Deletes an image /// </summary> /// <param name="I">Imgur image</param> /// <returns><see cref="true"/> on success</returns> public async Task <bool> DeleteImage(ImgurImage I) { HttpWebRequest R = Req(new Uri($"https://api.imgur.com/3/image/{I.deletehash}")); R.Method = "DELETE"; using (HttpWebResponse Res = await GetResponse(R)) { string data = await ReadAll(Res.GetResponseStream()); return(!ProcessErrorResponse(data) && !IsErrorCode(Res.StatusCode)); } }
/// <summary> /// Gets the image file associated with the given metadata /// </summary> /// <param name="I">Image metadata</param> /// <returns>Image file, null if not found</returns> /// <remarks>Downloads the image to cache if necessary</remarks> public static byte[] GetImage(ImgurImage I) { string ImageFile = Path.Combine(_imageDir, GetImageName(I)); if (!File.Exists(ImageFile)) { //Add image to cache if not found File.WriteAllBytes(ImageFile, Imgur.GetImage(I, ImgurImageSize.Original, false)); //New images are at the start Images = (new ImgurImage[] { I }).Concat(Images).ToArray(); } return(File.ReadAllBytes(ImageFile)); }
/// <summary> /// Uploads the selected image /// </summary> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments</param> private async void BtnUpload_Click(object sender, EventArgs e) { byte[] Data = null; try { if (UseClipboard) { using (MemoryStream MS = new MemoryStream()) { pbPreview.Image.Save(MS, ImageFormat.Png); Data = MS.ToArray(); } } else { Data = File.ReadAllBytes(tbImage.Text); } } catch (Exception ex) { MessageBox.Show($"Unable to read file. Reason: {ex.Message}", "File read Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (Data != null) { Imgur I = new Imgur(S); try { ImgurImage img = await I.UploadImage(Data, Path.GetFileName(tbImage.Text), tbTitle.Text, tbDescription.Text); if (img != null) { //Add new image Cache.Images = (new ImgurImage[] { img }).Concat(Cache.Images).ToArray(); DialogResult = DialogResult.OK; Close(); } else { throw new Exception("Imgur API did not accept the image"); } } catch (Exception ex) { MessageBox.Show($"Unable to upload your image. Reason: {ex.Message}", "File read Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/// <summary> /// Sets the title and description of an image /// </summary> /// <param name="I">Imgur image</param> /// <param name="Title">New title</param> /// <param name="Description">New description</param> /// <returns><see cref="true"/> on success</returns> public async Task <bool> SetImageDescription(ImgurImage I, string Title, string Description) { string fd = BuildFormData(new Dictionary <string, string>() { { "title", string.IsNullOrEmpty(Title) ? string.Empty : Title }, { "description", string.IsNullOrEmpty(Description) ? string.Empty : Description } }); HttpWebRequest R = Req(new Uri($"https://api.imgur.com/3/image/{I.id}"), fd); using (HttpWebResponse Res = await GetResponse(R)) { string data = await ReadAll(Res.GetResponseStream()); if (!ProcessErrorResponse(data) && !IsErrorCode(Res.StatusCode)) { return(data.FromJson <ImgurResponse <bool> >().data); } } return(false); }
/// <summary> /// Initializes the property form /// </summary> /// <param name="S">Current settings</param> /// <param name="I">Current image</param> public frmProperties(Settings S, ImgurImage I) { LastAction = ActionType.None; this.S = S; InitializeComponent(); if (S.UI.PropertyWindowMaximized) { WindowState = FormWindowState.Maximized; } else { Size ConfigSize = S.UI.PropertyWindowSize; if (ConfigSize.Height >= MinimumSize.Height && ConfigSize.Width >= MinimumSize.Width) { Size = ConfigSize; } } SetImage(I); }
/// <summary> /// Checks if the given search matches the given image /// </summary> /// <param name="I">Image</param> /// <param name="Search">Search string</param> /// <returns>"True", if match</returns> /// <remarks>Case insensitive, will always match if search is null or empty</remarks> private static bool IsMatch(ImgurImage I, string Search) { if (string.IsNullOrEmpty(Search)) { return(true); } IEnumerable <string> Strings = new string[] { I.title, I.description, I.name }.Where(m => !string.IsNullOrEmpty(m)); foreach (string s in Strings) { if (s.ToLower().Contains(Search.ToLower())) { return(true); } } return(false); }
/// <summary> /// Sets the currently shown image /// </summary> /// <param name="I">Current image</param> private void SetImage(ImgurImage I) { this.I = I; Text = $"Image Properties [{I.name}] ({I.views} views)"; tbTitle.Text = I.title; //Imgur uses \n only if (string.IsNullOrEmpty(I.description)) { tbDesc.Text = string.Empty; } else { tbDesc.Lines = I.description.Split('\n'); } if (!I.animated) { using (MemoryStream MS = new MemoryStream(Cache.GetImage(I))) { using (Image img = Image.FromStream(MS)) { pbImage.Image = (Image)img.Clone(); } } } else { //var Imgur = new Imgur(S); //This is a temporary solution until I can figure out how to play GIF animations again using (MemoryStream MS = new MemoryStream(Imgur.GetImage(I, ImgurImageSize.HugeThumbnail, false))) { using (Image img = Image.FromStream(MS)) { pbImage.Image = (Image)img.Clone(); } } } ScaleImage(); tbTitle.Focus(); tbTitle.SelectAll(); }
/// <summary> /// Removes an image (meta+thumb+image) from cache /// </summary> /// <param name="I">Image to remove</param> /// <returns>True, if thumbnail and image could be removed too. False on error</returns> public static bool RemoveImage(ImgurImage I) { string ImageFile = Path.Combine(_imageDir, GetImageName(I)); string ThumbFile = Path.Combine(_thumbDir, GetThumbnailName(I)); try { File.Delete(ImageFile); } catch { return(false); } try { File.Delete(ThumbFile); } catch { return(false); } Images = Images.Where(m => m.id != I.id).ToArray(); return(true); }
/// <summary> /// Gets the file name of a thumbnail from the cache /// </summary> /// <param name="I">Image metadata</param> /// <returns>File name</returns> public static string GetThumbnailName(ImgurImage I) { return(I.GetImageUrl(ImgurImageSize.Original).Segments.Last()); }
private async void BtnStartUpload_Click(object sender, EventArgs e) { SetControlState(false); Stack <FileNameItem> ItemList = new Stack <FileNameItem>(lbFileList.Items.OfType <FileNameItem>().Reverse()); Imgur I = new Imgur(S); if (ItemList.Count > 0) { string AlbumId = cbAlbum.SelectedIndex > 0 ? ((AlbumEntry)cbAlbum.SelectedItem).Id : null; List <string> Images = AlbumId == null ? null : (await I.GetAlbumImages(AlbumId)).Select(m => m.id).ToList(); lbFileList.SelectedIndex = 0; while (ItemList.Count > 0) { FileNameItem Current = ItemList.Pop(); ImgurImage Img = await I.UploadImage( File.ReadAllBytes(Current.LongName), Path.GetFileName(Current.LongName), FormatFileString(tbTitle.Text, Current.LongName), cbDescDate.Checked?DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss \U\T\C") : ""); if (Img != null) { if (Images != null) { Images.Add(Img.id); } Cache.GetImage(Img); lbFileList.Items.RemoveAt(0); } else { //Add failed image back to the queue ItemList.Push(Current); //Ask user to retry or cancel if (MessageBox.Show("Failed to upload an image. Response: " + I.LastError, "Upload failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel) { break; } } } if (Images != null) { while ( !await I.SetAlbumImages(AlbumId, Images) && MessageBox.Show("Failed to add uploaded images to the album. Response: " + I.LastError, "Album change failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry) { ; } } if (lbFileList.Items.Count == 0) { DialogResult = DialogResult.OK; } else { SetControlState(true); } } else { MessageBox.Show("Please select at least one file to upload.", "No files", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// Downloads the selected image(s) /// </summary> /// <param name="CacheOnly">Don't prompt, download to cache only</param> /// <remarks>Will show folder browse dialog if multiple images are selected and file save dialog if only one</remarks> private void SaveSelectedImages(bool CacheOnly) { switch (lvImages.SelectedItems.Count) { case 0: break; case 1: if (CacheOnly) { Cache.GetImage((ImgurImage)lvImages.SelectedItems[0].Tag); } else { using (SaveFileDialog SFD = new SaveFileDialog()) { ImgurImage Img = (ImgurImage)lvImages.SelectedItems[0].Tag; SFD.DefaultExt = Img.link.Split('.').Last(); if (Img.name != null) { SFD.FileName = $"{Img.name}.{SFD.DefaultExt}"; } else { SFD.FileName = Img.link.Split('/').Last(); } SFD.Filter = $"{Img.type}|*.{SFD.DefaultExt}"; SFD.Title = $"Downloading {Img.link}"; if (SFD.ShowDialog(this) == DialogResult.OK) { File.WriteAllBytes(SFD.FileName, Cache.GetImage(Img)); } } } break; default: if (CacheOnly) { IEnumerable <ImgurImage> Images = lvImages.SelectedItems .OfType <ListViewItem>() .Select(m => (ImgurImage)m.Tag); using (FrmDownload fDownload = new FrmDownload(Images, null)) { fDownload.ShowDialog(); } } else { using (FolderBrowserDialog FBD = new FolderBrowserDialog()) { FBD.Description = $"Saving {lvImages.SelectedItems.Count} Images"; FBD.ShowNewFolderButton = true; if (FBD.ShowDialog(this) == DialogResult.OK) { IEnumerable <ImgurImage> Images = lvImages.SelectedItems .OfType <ListViewItem>() .Select(m => (ImgurImage)m.Tag); using (FrmDownload fDownload = new FrmDownload(Images, FBD.SelectedPath)) { fDownload.ShowDialog(); } } } } break; } }