/// <summary> /// 下载图片资源 /// </summary> public void DownLoadImage(ImageTable imgObj, string referer) { string imageFullPath = string.Empty, imageNewUrl = string.Empty; try { imageFullPath = downLoadPath + @"\" + imgObj.Guid + ".jpg"; imageNewUrl = remotePath + imgObj.Guid + ".jpg"; byte[] imgByteArr = hh.DowloadCheckImg(imgObj.OriginalUrl, cookie, Host, referer); Image image = myUtils.GetImageByBytes(imgByteArr); image.Save(imageFullPath, ImageFormat.Jpeg); var imageObj = ise.ImageTables.Where(w => w.Id == imgObj.Id).FirstOrDefault(); if (imageObj != null) { imageObj.IsDownLoad = true; imageObj.Width = image.Width; imageObj.Height = image.Height; imageObj.NewUrl = imageNewUrl; imageObj.DownLoadTime = DateTime.Now; ise.SaveChanges(); currentCount++; label4.Invoke(new Action(() => { label4.Text = currentCount + "/" + ImagesTotalCount; })); } } catch (Exception ex) { myUtils.WriteLog($"图片【{imgObj.OriginalUrl}】 下载失败!"); } Thread.Sleep(1000 * 3); }
public HttpResponseMessage UploadImage() { string imageName = null; var httpRequest = HttpContext.Current.Request; //Upload Image var postedFile = httpRequest.Files["Image"]; //Create custom filename imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-"); imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName); var filePath = HttpContext.Current.Server.MapPath("~/Image/" + imageName); postedFile.SaveAs(filePath); //Save to DB using (ApplicationDbContext db = new ApplicationDbContext()) { ImageTable image = new ImageTable() { ImageCaption = httpRequest["ImageCaption"], ImageName = imageName }; db.ImageTable.Add(image); db.SaveChanges(); } return(Request.CreateResponse(HttpStatusCode.Created)); }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- public async Task <ImageTable> getImageAsync(ChatMessageTable msg) { await GET_IMAGE_SEMA.WaitAsync(); // Is already downloading: ImageTable img = (ImageTable)await ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.FindAsync((x) => { return(x is ImageTable imageTable && string.Equals(imageTable.messageId, msg.id)); }); if (img is null) { // Is in the DB: List <ImageTable> list = dB.Query <ImageTable>(true, "SELECT * FROM " + DBTableConsts.IMAGE_TABLE + " WHERE " + nameof(ImageTable.messageId) + " = ?;", msg.id); if (list.Count > 0) { img = list[0]; } else { // Create a new image entry: StorageFolder folder = await ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.GetCacheFolderAsync(); img = new ImageTable() { messageId = msg.id, SourceUrl = msg.message, TargetFileName = ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.CreateUniqueFileName(msg.message), TargetFolderPath = folder.Path, State = DownloadState.NOT_QUEUED, Progress = 0, }; setImage(img); } } GET_IMAGE_SEMA.Release(); return(img); }
public async Task deleteImageAsync(ChatMessageTable msg) { ImageTable image = await getImageAsync(msg); if (!(image is null)) { // Cancel download: ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.CancelDownload(image); // Try to delete local file: try { if (!string.IsNullOrEmpty(image.TargetFolderPath) && !string.IsNullOrEmpty(image.TargetFileName)) { string path = image.GetFullPath(); StorageFile file = await StorageFile.GetFileFromPathAsync(path); if (!(file is null)) { await file.DeleteAsync(); } } Logger.Info("Deleted: " + image.TargetFileName); } catch (Exception e) { Logger.Error("Failed to delete image: " + image.TargetFileName, e); } // Delete DB entry: dB.Delete(image); } }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- /// <summary> /// Retries to download the image from the given ChatMessageTable. /// </summary> /// <param name="msg">The ChatMessageTable containing the image url.</param> /// <returns>The image container.</returns> public ImageTable retryImageDownload(ChatMessageTable msg) { if (msg.isImage) { ImageTable img = getImageForMessage(msg); if (img == null) { img = new ImageTable() { messageId = msg.id, path = null, state = DownloadState.WAITING, progress = 0 }; } else { img.state = DownloadState.WAITING; img.progress = 0; img.path = null; } Task.Run(async() => { update(img); await downloadImageAsync(img, msg.message); }); return(img); } return(null); }
public ActionResult Upload(ImageTable IT) { if (IT.File.ContentLength > (4 * 1024 * 1024)) { ModelState.AddModelError("CustomError", "File size must be less than 4MB"); return View(IT); } if (!(IT.File.ContentType == "image/jpeg" || IT.File.ContentType == "image/gif")) { ModelState.AddModelError("CustomError", "File type allowed: jpeg and gif"); } IT.FileName = IT.File.FileName; IT.ImageSize = IT.File.ContentLength; byte[] data = new byte[IT.File.ContentLength]; IT.File.InputStream.Read(data, 0, IT.File.ContentLength); IT.ImageData = data; using (PostsDataBaseEntities dc = new PostsDataBaseEntities()) { dc.ImageTables.Add(IT); dc.SaveChanges(); } return RedirectToAction("ImageFetching"); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public async Task DownloadImageAsync(ImageTable image) { if (image.State != DownloadState.DOWNLOADING && image.State != DownloadState.QUEUED) { await DOWNLOAD_HANDLER.EnqueueDownloadAsync(image); } }
private void SelectNextGlyph() { var index = _rng.Next(0, _glyphs.Count - 1); _current = _glyphs[index]; ImageTable.ColumnStyles.Clear(); ImageTable.ColumnCount = 0; foreach (var pictureBox in _toDispose) { pictureBox.Dispose(); } _toDispose.Clear(); for (int i = 0; i < _current.Graphics.Count; i++) { ImageTable.ColumnCount = i + 1; var display = new PictureBox(); display.AutoSize = true; display.Image = _current.Graphics[i]; display.Parent = ImageTable; display.Margin = new Padding(0); _toDispose.Add(display); ImageTable.SetCellPosition(display, new TableLayoutPanelCellPosition(i, 0)); ImageTable.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 0)); } }
private async Task showImageAsync(ImageTable img) { message_tbx.Visibility = Visibility.Collapsed; imageError_grid.Visibility = Visibility.Collapsed; imageLoading_grid.Visibility = Visibility.Visible; openImage_mfo.IsEnabled = false; redownloadImage_mfo.IsEnabled = false; imgPath = img.path; if (img.state == DownloadState.DONE) { image_img.Source = await img.getBitmapImageAsync(); if (image_img.Source == null) { img.DownloadStateChanged -= Img_DownloadStateChanged; img.DownloadProgressChanged -= Img_DownloadProgressChanged; imageLoading_grid.Visibility = Visibility.Collapsed; imageError_grid.Visibility = Visibility.Visible; Message = "Image not found!"; message_tbx.Visibility = Visibility.Visible; redownloadImage_mfo.IsEnabled = true; return; } } switch (img.state) { case DownloadState.DOWNLOADING: loading_prgrb.IsIndeterminate = false; break; case DownloadState.WAITING: loading_prgrb.IsIndeterminate = true; break; case DownloadState.DONE: img.DownloadStateChanged -= Img_DownloadStateChanged; img.DownloadProgressChanged -= Img_DownloadProgressChanged; image_img.Visibility = Visibility.Visible; imageLoading_grid.Visibility = Visibility.Collapsed; openImage_mfo.IsEnabled = true; redownloadImage_mfo.IsEnabled = true; break; case DownloadState.ERROR: img.DownloadStateChanged -= Img_DownloadStateChanged; img.DownloadProgressChanged -= Img_DownloadProgressChanged; imageLoading_grid.Visibility = Visibility.Collapsed; imageError_grid.Visibility = Visibility.Visible; image_img.Source = null; Message = string.IsNullOrWhiteSpace(img.errorMessage) ? "No error message given!" : img.errorMessage; message_tbx.Visibility = Visibility.Visible; redownloadImage_mfo.IsEnabled = true; break; } }
private async Task cacheImageAsync(ChatMessageTable msg) { if (!Settings.getSettingBoolean(SettingsConsts.DISABLE_IMAGE_AUTO_DOWNLOAD)) { ImageTable img = await ImageDBManager.INSTANCE.getImageAsync(msg); await ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.StartDownloadAsync(img); } }
private async Task LoadImageAsync() { if (SpeechBubbleViewModel is null || SpeechBubbleViewModel.ChatMessageModel.Message is null) { return; } ImageTable image = await ImageDBManager.INSTANCE.getImageAsync(SpeechBubbleViewModel.ChatMessageModel.Message); MODEL.UpdateView(image); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public async Task StartDownloadAsync(ImageTable image) { await DOWNLOAD_SEMA.WaitAsync(); if (image.State != DownloadState.DOWNLOADING && image.State != DownloadState.QUEUED) { await DOWNLOAD_HANDLER.EnqueueDownloadAsync(image); } DOWNLOAD_SEMA.Release(); }
private async Task retryImageDownloadAsync() { ImageTable img = ImageDBManager.INSTANCE.retryImageDownload(ChatMessage); if (img != null) { waitForImageDownloadToFinish(img); await showImageAsync(img); } }
private void waitForImageDownloadToFinish(ImageTable img) { img.DownloadStateChanged -= Img_DownloadStateChanged; img.DownloadStateChanged += Img_DownloadStateChanged; img.DownloadProgressChanged -= Img_DownloadProgressChanged; img.DownloadProgressChanged += Img_DownloadProgressChanged; imageLoading_grid.Visibility = Visibility.Visible; loading_prgrb.IsIndeterminate = img.state == DownloadState.WAITING; }
/// <summary> /// Updates the progress of the given ImageTable and triggers if necessary the onDownloadProgressChanged event. /// </summary> /// <param name="img">The image container.</param> /// <param name="totalLengt">The total length of the download in bytes.</param> /// <param name="bytesReadTotal">How many bytes got read already?</param> /// <param name="lastProgressUpdatePercent">When was the last onDownloadProgressChanged event triggered?</param> /// <returns>Returns the last progress update percentage.</returns> private double updateProgress(ImageTable img, long totalLengt, long bytesReadTotal, double lastProgressUpdatePercent) { img.progress = ((double)bytesReadTotal) / ((double)totalLengt); if ((img.progress - lastProgressUpdatePercent) >= DOWNLOAD_PROGRESS_REPORT_INTERVAL) { img.onDownloadProgressChanged(); return(img.progress); } return(lastProgressUpdatePercent); }
/// <summary> /// Returns the image container from a given ChatMessageTable. /// </summary> /// <param name="msg">The ChatMessageTable.</param> /// <returns>The corresponding image container.</returns> public ImageTable getImageForMessage(ChatMessageTable msg) { ImageTable img = downloading.Find(x => string.Equals(x.messageId, msg.id)); if (img == null) { List <ImageTable> list = dB.Query <ImageTable>(true, "SELECT * FROM " + DBTableConsts.IMAGE_TABLE + " WHERE messageId = ?;", msg.id); if (list.Count > 0) { img = list[0]; } } return(img); }
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- private void OnImagePathChanged(string newValue) { if (!(loadImageCancellationSource is null)) { loadImageCancellationSource.Cancel(); } loadImageCancellationSource = new CancellationTokenSource(); Task.Run(async() => { if (Image is null || Image.State != DownloadState.DONE) { Image = null; }
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- /// <summary> /// /// </summary> /// <param name="msg"></param> /// <returns></returns> public async Task <ImageTable> getImageAsync(ChatMessageTable msg) { ImageTable img = (ImageTable)await ConnectionHandler.INSTANCE.IMAGE_DOWNLOAD_HANDLER.FindAsync((x) => { return(x is ImageTable imageTable && string.Equals(imageTable.messageId, msg.id)); }); if (img is null) { List <ImageTable> list = dB.Query <ImageTable>(true, "SELECT * FROM " + DBTableConsts.IMAGE_TABLE + " WHERE " + nameof(ImageTable.messageId) + " = ?;", msg.id); if (list.Count > 0) { img = list[0]; } } return(img); }
async void SwipedRight(int index) { try { string result = ""; if (InformationClass.Dict.Count == 1) { var _result = InformationClass.Dict.First(); result = _result.Value; } else { InformationClass.Dict.TryGetValue(index - 2, out result); InformationClass.Dict.Remove(index - 2); } var item = await MobileService.GetTable <Project>().LookupAsync(result); if (item == null) { Application.Current.MainPage = new NavigationPage(new FinishPage()); } else { item.UpVote = item.UpVote + 1; await MobileService.GetTable <Project>().UpdateAsync(item); ImageTable image = new ImageTable { UserName = AzureResult.UserName, UpVote = true, ImageUrl = item.Url }; await MobileService.GetTable <ImageTable>().InsertAsync(image); countCheck++; if (countCheck == AzureResult.Count || InformationClass.Dict.Count < 1) { Application.Current.MainPage = new NavigationPage(new FinishPage()); } } } catch (Exception ex) { await DisplayAlert("Alert", "Unable to cast vote. Kindly restart the application and try again", "OK"); } }
/// <summary> /// Updates the DownloadState of the given ImageTable and triggers the onStateChanged() event. /// </summary> /// <param name="img">The ImageTable, that should get updated.</param> /// <param name="state">The new DownloadState.</param> private void updateImageState(ImageTable img, DownloadState state) { img.state = state; img.onStateChanged(); update(img); switch (state) { case DownloadState.DONE: case DownloadState.ERROR: downloading.Remove(img); break; default: break; } }
/// <summary> /// Tries to download the image from the given url. /// </summary> /// <param name="url">The image url.</param> /// <param name="name"><The image name for storing the image./param> /// <returns>Returns null if it fails, else the local path.</returns> private async Task <string> downloadImageAsync(ImageTable img, string url, string name) { Logger.Info("Started downloading image <" + name + "> from: " + url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); long bytesReadTotal = 0; double lastProgressUpdatePercent = 0; // Check that the remote file was found. The ContentType // check is performed since a request for a non-existent // image file might be redirected to a 404-page, which would // yield the StatusCode "OK", even though the image was not // found. if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect) { // if the remote file was found, download it StorageFile f = await createImageStorageFileAsync(name); using (Stream inputStream = response.GetResponseStream()) using (Stream outputStream = await f.OpenStreamForWriteAsync()) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length); await outputStream.WriteAsync(buffer, 0, bytesRead); // Update progress: lastProgressUpdatePercent = updateProgress(img, response.ContentLength, (bytesReadTotal += bytesRead), lastProgressUpdatePercent); } while (bytesRead != 0); } Logger.Info("Finished downloading image <" + name + "> from: " + url); return(f.Path); } else { img.errorMessage = "Status code check failed: " + response.StatusCode + " (" + response.StatusDescription + ')'; update(img); } Logger.Error("Unable to download image <" + name + "> from: " + url + " Status code: " + response.StatusCode); return(null); }
/// <summary> /// Downloads the image from the given message and stores it locally. /// </summary> /// <param name="img">The image container.</param> /// <param name="msg">The image url.</param> /// <returns></returns> private async Task downloadImageAsync(ImageTable img, string msg) { downloading.Add(img); updateImageState(img, DownloadState.DOWNLOADING); string path = await getImagePathAsync(img, msg); img.path = path; if (path == null) { updateImageState(img, DownloadState.ERROR); } else { updateImageState(img, DownloadState.DONE); } }
public async Task SaveTaskAsync(ImageTable image) { try { if (image.Id == null) { await imageTable.InsertAsync(image); } else { await imageTable.UpdateAsync(image); } } catch (Exception e) { Debug.WriteLine(@"Sync error: {0}", e.Message); } }
/// <summary> /// Creates a new task, downloads the image from the given message and stores it locally. /// </summary> /// <param name="msg">The ChatMessageTable containing the image url.</param> public void downloadImage(ChatMessageTable msg) { if (msg.isImage) { Task.Run(async() => { ImageTable img = new ImageTable() { messageId = msg.id, path = null, state = DownloadState.WAITING, progress = 0 }; update(img); await downloadImageAsync(img, msg.message); }); } }
private void SetImage(ImageTable value) { ImageTable oldImage = Image; if (SetProperty(ref _Image, value, nameof(Image))) { if (!(oldImage is null)) { oldImage.PropertyChanged -= Image_PropertyChanged; } if (!(Image is null)) { Image.PropertyChanged += Image_PropertyChanged; State = Image.State; ErrorText = Image.Error.ToString(); ImagePath = Path.Combine(Image.TargetFolderPath, Image.TargetFileName); } } }
private void RevealGlyph() { if (_revealed) { return; } for (int i = 0; i < _current.Graphics.Count; i++) { ImageTable.ColumnCount = i + 1; var display = new PictureBox(); display.AutoSize = true; display.Image = _current.Graphics[i]; display.Parent = ImageTable; display.Margin = new Padding(0); _toDispose.Add(display); ImageTable.SetCellPosition(display, new TableLayoutPanelCellPosition(i, 0)); ImageTable.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 0)); } _revealed = true; }
/// <summary> /// Checks if the image is already available locally, if yes returns the path to it. /// Else tries to download the image and stores it. Also returns the path of the downloaded image. /// </summary> /// <param name="img">The image container.</param> /// <param name="url">The image url.</param> /// <returns>Returns the local path to the downloaded image.</returns> public async Task <string> getImagePathAsync(ImageTable img, string url) { try { string fileName = createUniqueFileName(url); string path = await getLocalImageAsync(fileName); if (path == null) { path = await downloadImageAsync(img, url, fileName); } return(path); } catch (Exception e) { Logger.Error("Error during downloading image: " + e.Message); img.errorMessage = e.Message; update(img); return(null); } }
public void ImageTest() { var filename = ""; var accessor = CreateAccessor(out filename); var gnu = new ImageTable() { Test = GetBytes("This is a test") }; accessor.WriteEntity(gnu); var existing = accessor.ReadEntities <ImageTable>("SELECT * FROM [ImageTable]"); Assert.Equal(1, existing.Count()); var first = existing.First(); var value = GetString(first.Test); Assert.Equal("This is a test", value); DestroyAccessor(filename); }
public async Task <ImageTable> DownloadImageAsync(ChatMessageTable msg) { ImageTable image = await ImageDBManager.INSTANCE.getImageAsync(msg); if (image is null) { StorageFolder folder = await GetImageCacheFolderAsync(); image = new ImageTable() { messageId = msg.id, SourceUrl = msg.message, TargetFileName = CreateUniqueFileName(msg.message), TargetFolderPath = folder.Path, State = DownloadState.NOT_QUEUED, Progress = 0, }; ImageDBManager.INSTANCE.setImage(image); } await DownloadImageAsync(image); return(image); }
public void CancelDownload(ImageTable image) { DOWNLOAD_HANDLER.CancelDownload(image); }
public async Task RedownloadAsync(ImageTable image) { await DOWNLOAD_HANDLER.EnqueueDownloadAsync(image); }