public async Task UploadAndProcessImageAsync(string fileName, MemoryStream stream) { string aspNetUserID = await GetUserID(); string uniqueFileName = $"{Guid.NewGuid()}{fileName}"; // calculate the md5 hash and ensure it was already uploaded MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string md5ByteString = System.Text.Encoding.Default.GetString(md5.ComputeHash(stream)); if (this.dbContext.OriginalImages.Any(x => x.MD5Hash == md5ByteString)) { // do something } // if it wasn't, upload the original and delegate the var originalImageRecord = new OriginalImage { DisplayName = fileName, FileName = uniqueFileName, AspNetUserID = aspNetUserID, MD5Hash = md5ByteString, ContainerOrDirectory = "OriginalImages", CreatedAt = DateTime.UtcNow }; this.dbContext.OriginalImages.Add(originalImageRecord); await this.dbContext.SaveChangesAsync(); stream.Position = 0; await this.blobStorage.UploadItemAsync("OriginalImages", uniqueFileName, stream); }
/// <summary> /// Generates the BMP icon image data for this image. /// </summary> /// <returns>The BMP icon image data for this image.</returns> public byte[] GetData() { BitmapSource result = null; if (GenerateTransparencyMap) { // The transparency map has to be above the actual image, so we just copy the original image's data at the bottom // All bytes before that will be set to 0, which is what we want (0 == Visible) byte[] buffer = new byte[OriginalImage.PixelWidth * OriginalImage.PixelHeight * 4 * 2]; OriginalImage.CopyPixels(buffer, OriginalImage.PixelWidth * 4, buffer.Length / 2); result = BitmapSource.Create( OriginalImage.PixelWidth, OriginalImage.PixelHeight * 2, OriginalImage.DpiX, OriginalImage.DpiY, OriginalImage.Format, OriginalImage.Palette, buffer, OriginalImage.PixelWidth * 4); } else { result = OriginalImage; } using (var stream = new MemoryStream()) { var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(result)); encoder.Save(stream); // Remove the BMPFILEHEADER, turning it into a Memory BMP. return(stream.GetBuffer().Skip(BmpFileHeaderSize).ToArray()); } }
private void ApplyEffectsNegative() { System.Drawing.Bitmap bmp; System.Drawing.Imaging.BitmapData bmData; System.IntPtr ptr; int nOffSet, x, y, tamanho; bmp = (System.Drawing.Bitmap)OriginalImage.Clone(); bmData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); ptr = bmData.Scan0; nOffSet = bmData.Stride - bmp.Width * 3; switch (m_enumEffectDirection) { case PictureBox.Directions.Horizontal: break; case PictureBox.Directions.Vertical: tamanho = (int)((bmp.Height * m_nPercentage) / 100); for (y = tamanho; y < bmp.Height - 1; y++) { for (x = 0; x < (bmp.Width * 3) - 1; x++) { System.Runtime.InteropServices.Marshal.WriteByte(ptr, 0, (byte)(255 - System.Runtime.InteropServices.Marshal.ReadByte(ptr, 0))); ptr = new System.IntPtr(ptr.ToInt32() + 1); } } break; } bmp.UnlockBits(bmData); this.Image = bmp; this.Refresh(); }
private void RangeCanvas() { ViewContainer.UpdateLayout(); OriginalImage.UpdateLayout(); EventCanvas.Children.Clear(); EventCanvas.Width = ViewContainer.ActualWidth; EventCanvas.Height = ViewContainer.ActualHeight; ObjectCanvas.Width = ViewContainer.ActualWidth; ObjectCanvas.Height = ViewContainer.ActualHeight; var rect = new Rectangle { Width = ViewContainer.ActualWidth, Height = ViewContainer.ActualHeight, Stroke = new SolidColorBrush(Colors.Transparent), Fill = new SolidColorBrush(Colors.Transparent) }; var objRect = new Rectangle { Width = ViewContainer.ActualWidth, Height = ViewContainer.ActualHeight, Stroke = new SolidColorBrush(Colors.Transparent), Fill = new SolidColorBrush(Colors.Transparent) }; EventCanvas.Children.Add(rect); ObjectCanvas.Children.Add(objRect); f_Ratio = ((EventCanvas.Width / f_OrigWidth) + (EventCanvas.Height / f_OrigHeight)) / 2; }
public string ConvertThumb(string imgbyte) { System.Drawing.Image OriginalImage; OriginalImage = System.Drawing.Image.FromFile(imgbyte); var imThumbnailImage = OriginalImage.GetThumbnailImage(75, 75, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); MemoryStream myMS = new MemoryStream(); imThumbnailImage.Save(myMS, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] test_imge = myMS.ToArray(); string directorypath = Path.Combine(Directory.GetCurrentDirectory(), "Thumbnails"); if (!Directory.Exists(directorypath)) { Directory.CreateDirectory(directorypath); } Guid name = Guid.NewGuid(); string filePath = Path.Combine(directorypath, name.ToString() + ".jpeg"); using (Image image = Image.FromStream(new MemoryStream(test_imge))) { image.Save(filePath, ImageFormat.Jpeg); } imThumbnailImage.Dispose(); OriginalImage.Dispose(); return(filePath); }
internal void GenerateOriginalGene() { workingGene = new Gene(); int initialPolygonsCount = NrOfPolygons / 2 + random.Next(NrOfPolygons / 2); workingGene.InitialFill((Bitmap)OriginalImage.Clone(), NrOfPolygons, initialPolygonsCount); }
/// <summary> /// Scales this image so that it fits a certain width and height. /// </summary> /// <param name="width">the width to fit</param> /// <param name="height">the height to fit</param> /// <returns> /// Returns this instance scaled. /// </returns> public XlsxImage ScaleToFit(float width, float height) { if (this.Equals(XlsxImage.Null)) { return(this); } if (Image == null) { return(this); } _hasScaledPercent = false; _hasScaledFit = true; _scaleX = width; _scaleY = height; var original = (Image)OriginalImage.Clone(); var originalWithEffects = original; if (Configuration.Effects != null) { originalWithEffects = original.ApplyEffects(Configuration.Effects); } ProcessedImage = (Image)originalWithEffects.ScaleToFit(width, height).Clone(); return(this); }
private void Timer_Tick(object sender, EventArgs e) { //check OriginalImage list //1.have original image && not upload //then upload if (this.ftpCtl1 != null && this.ftpCtl1.IsConnected) { this.ConnectedStatus.Text = "Conected"; if (!this.isUpLoading && this.originalImages != null && this.originalImages.Count > 0) { image = originalImages.Pop(); CheckFTPFolder(); Upload(image.FilePath); } } else { this.ConnectedStatus.Text = "Disconnected"; } //2.have original image && uploading //then do nothing //3.have no original image //then do nothing }
/// <summary> /// Apply effects image to this instance. /// </summary> /// <param name="effects">the dimensions to fit</param> /// <returns> /// Returns this instance with effects. /// </returns> public XlsxImage ApplyEffects(EffectType[] effects) { if (this.Equals(XlsxImage.Null)) { return(this); } if (Image == null) { return(this); } Image image = Configuration.Effects == null ? Image.FromStream(OriginalImage.AsStream()) : Image.FromStream(OriginalImage.ApplyEffects(Configuration.Effects).AsStream()); ProcessedImage = (Image)image.ApplyEffects(effects).Clone(); Image = (Image)ProcessedImage.Clone(); if (_hasScaledFit) { ScaleToFit(_scaleX, _scaleY); } if (_hasScaledPercent) { ScalePercent(_scaleX, _scaleY); } return(this); }
private void UpdateGapDistance() { RBSK rbsk = MouseService.GetStandardMouseRules(); rbsk.Settings.GapDistance = GapDistance; rbsk.Settings.BinaryThreshold = ThresholdValue; PointF[] result = RBSKService.RBSK(OriginalImage, rbsk); if (result == null || !result.Any()) { DisplayImage = ImageService.ToBitmapSource(OriginalImage); return; } using (Image <Gray, Byte> displayImage = OriginalImage.Convert <Gray, Byte>()) using (Image <Gray, Byte> binaryimage = displayImage.ThresholdBinary(new Gray(ThresholdValue), new Gray(255))) using (Image <Bgr, byte> drawImage = binaryimage.Convert <Bgr, byte>()) { foreach (PointF point in result) { drawImage.Draw(new CircleF(point, 2), new Bgr(Color.Yellow), 2); } DisplayImage = ImageService.ToBitmapSource(drawImage); } PreviewGenerated = false; Boundries = new ObservableCollection <BoundaryBaseViewModel>(); //Console.WriteLine(GapDistance); }
public static byte[] CreateThumbVideo(byte[] byteArray) { try { System.Drawing.Image imThumbnailImage; System.Drawing.Image OriginalImage; MemoryStream ms = new MemoryStream(); // Stream / Write Image to Memory Stream from the Byte Array. ms.Write(byteArray, 0, byteArray.Length); OriginalImage = System.Drawing.Image.FromStream(ms); // Shrink the Original Image to a thumbnail size. imThumbnailImage = OriginalImage.GetThumbnailImage(75, 75, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallBack), IntPtr.Zero); // Save Thumbnail to Memory Stream for Conversion to Byte Array. MemoryStream myMS = new MemoryStream(); imThumbnailImage.Save(myMS, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] test_imge = myMS.ToArray(); return(test_imge); } catch (System.Exception) { return(byteArray); } }
private async Task LoadImage(string filename, Rect?startRect) { _image = await BetterImage.LoadBitmapSourceAsync(filename); OriginalImage.SetCurrentValue(Image.SourceProperty, _image.ImageSource); CommandManager.InvalidateRequerySuggested(); if (_image.IsBroken) { NonfatalError.Notify(AppStrings.Dialogs_ImageEditor_CantLoadImage); CloseWithResult(MessageBoxResult.Cancel); } else { _model.TotalWidth = MainGrid.Width = _image.Width; _model.TotalHeight = MainGrid.Height = _image.Height; _model.CalculateMinAndMax(); if (startRect.HasValue) { var rect = startRect.Value; _model.OffsetX = rect.X; _model.OffsetY = rect.Y; _model.ImageWidth = rect.Width; _model.ImageHeight = rect.Height; } else { _model.CenterAndFit(); } UpdateView(); } }
public void TestImageProcessor() { var ip = new GalleryImageProcessor(); OriginalImage img = new OriginalImage(); img.Filename = @"C:\Users\Ken\Documents\GitHub\SimplePhotoGallery\SimplePhotoGallery\Galleries\Canon1IMG_0050.JPG"; img.Title = "Renee smiling"; ip.ProcessPostUpload(img); // now we should test that we have four thumbnails: // large, medium, small and tiny GalleryContext db = new GalleryContext(); var originalImage = db.Images.ToList(); // .Where(b => b.Title.Contains("James")).ToList(); /* * .FirstOrDefault(); * .Include("ProcessedImages") * */ foreach (var processedImage in originalImage) { var fn = processedImage.Filename; } }
/// <summary> /// this method rotated the image /// </summary> /// <param name="clockWise">specifies if its clockwise or the other</param> public void RotateImage(bool clockWise) { if (OriginalImage != null) { OriginalImage.RotateFlip(RotateFlipType.Rotate90FlipXY); ZoomImage(ZoomMode.FitPage); } }
protected virtual void Dispose(bool disposing) { if (disposing) { OriginalImage?.Dispose(); Preview?.Dispose(); } }
// Upload entire file private void UploadWholeFile(HttpContext context, List <FilesStatus> statuses) { // hack to see if thumbnails can be added //Thumbnail tn = new Thumbnail(); //tn.Description = "medium"; //tn.MaxWidth = 600; //db.Thumbnails.Add(tn); //db.SaveChanges(); // in a controller we would probably use data binding if (context.Request.Form["uploadDestination"] != "") { // this changes value of StorageRoot GalleryDirectory = "~/" + context.Request.Form["uploadDestination"] + "/"; } else { GalleryDirectory = "~/" + ConfigurationManager.AppSettings["uploadDestination"] + "/"; } for (int i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; // todo, see if this is really the right approach var fullPath = Path.Combine(StorageRoot, Path.GetFileName(file.FileName)); // hack using the file name to access the title field via the file name var fileTitle = context.Request.Form[file.FileName.Replace(" ", "").Replace(".", "")]; // the file title is a description try { GalleryImageProcessor ip = new GalleryImageProcessor(); OriginalImage img = new OriginalImage(); img.Filename = fullPath; img.Title = fileTitle; // todo, see if there are better ways of generating this url img.UrlPath = GalleryDirectory + "/" + Path.GetFileName(file.FileName); // todo, put this saving into the image as I had a bug where no // files were saved because I omitted this step. file.SaveAs(img.Filename); ip.ProcessPostUpload(img); string fullName = Path.GetFileName(file.FileName); statuses.Add(new FilesStatus(fullName, file.ContentLength, fullPath)); } catch (Exception e) { // todo, find out how to report the error to the web page context.Response.Write("<p>Exception " + e.Message + "</p>"); } } }
public override void Dispose() { if (OriginalImage != null) { OriginalImage.Dispose(); OriginalImage = null; } FreeFont(); }
private double computeError(Bitmap sourceImage) { double error = 0; BitmapData bd2 = OriginalImage.LockBits( new Rectangle(0, 0, OriginalImage.Width, OriginalImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Pixel[] sourcePixels = null; BitmapData bd = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); sourcePixels = new Pixel[sourceImage.Width * sourceImage.Height]; unsafe { fixed(Pixel *psourcePixels = sourcePixels) { Pixel *pSrc = (Pixel *)bd.Scan0.ToPointer(); Pixel *pDst = psourcePixels; for (int i = sourcePixels.Length; i > 0; i--) { *(pDst++) = *(pSrc++); } } } sourceImage.UnlockBits(bd); unchecked { unsafe { fixed(Pixel *psourcePixels = sourcePixels) { Pixel *p1 = (Pixel *)bd2.Scan0.ToPointer(); Pixel *p2 = psourcePixels; for (int i = sourcePixels.Length; i > 0; i--, p1++, p2++) { int r = p1->R - p2->R; int g = p1->G - p2->G; int b = p1->B - p2->B; error += r * r + g * g + b * b; } } } } OriginalImage.UnlockBits(bd); return(Math.Sqrt(error)); }
private void UpdateImageCodes() { for (int row = 0; row < 256; row++) { for (int column = 0; column < 256; column++) { ImageCodes[row, column] = OriginalImage.GetPixel(row, column).R; } } }
private void ProcessFrame() { using (Image <Gray, Byte> displayImage = OriginalImage.Convert <Gray, Byte>()) using (Image <Gray, Byte> binaryimage = displayImage.ThresholdBinary(new Gray(ThresholdValue), new Gray(255))) { DisplayImage = ImageService.ToBitmapSource(binaryimage); } PreviewGenerated = false; Boundries = new ObservableCollection <BoundaryBaseViewModel>(); }
public void CreateGrayLevelImage() { for (int i = 0; i < Width; i++) { for (int j = 0; j < Height; j++) { int average = (OriginalImage.GetPixel(i, j).R + OriginalImage.GetPixel(i, j).G + OriginalImage.GetPixel(i, j).B) / 3; GrayLevelImage.SetPixel(i, j, Color.FromArgb(average, average, average)); } } }
private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (Equals(sender, OriginalImage)) { OriginalImage.ReleaseMouseCapture(); } if (Equals(sender, ModifiedImage)) { ModifiedImage.ReleaseMouseCapture(); } }
public override async Task <Bitmap> Process() { if (OriginalImage == null) { return(await DefaultResult()); } var clone = (Bitmap)OriginalImage.Clone(); ProcessedImage = await Task.Run(() => clone.ForEachPixel(pixel => pixel.Grayscale())); return(ProcessedImage); }
public void Dispose() { OriginalImage?.Dispose(); OriginalImage = null; BigImage?.Dispose(); BigImage = null; SmallImage?.Dispose(); SmallImage = null; TinyImage?.Dispose(); TinyImage = null; XtraTinyImage?.Dispose(); XtraTinyImage = null; }
public override async Task <Bitmap> Process() { if (OriginalImage == null) { return(await DefaultResult()); } var bitmap = (Bitmap)OriginalImage.Clone(); return(await Task.Run(() => bitmap.ForEachPixel(p => p.Grayscale())) //.ContinueWith(task => task.Result.MedianFilter((Bitmap)bitmap.Clone(), 3)) .ContinueWith(task => task.Result.ApplyForstnerDetector(2, 4)) .ContinueWith(task => bitmap.MarkAreas(task.Result))); }
public void OnLoadImageFormFilePath(string filePath) { detectImageTaskCancellationToken = new CancellationTokenSource(); detectImageTaskCancellationToken.Token.Register(() => { }); var testingProgressMessage = "Розпізнавання в прогресі. Будь ласка, зачекайте... "; this.DetectionInProgress = true; StatusMessageUpdater(testingProgressMessage); Task task = new Task(() => { Image <Bgr, Byte> image = new Image <Bgr, byte>(filePath); this.OriginalImage = image.Resize(1000, 1000, Inter.Cubic, false); var processedImage = LocalImage.ConvertOriginalImageToGrayScaleAndProcess(this.OriginalImage); this.ProcessedImage = processedImage; (ImageType imageType, List <System.Drawing.Rectangle> rectangles) = Detector.DetectCatInImageFile(NeuralNetwork, this.OriginalImage, this.ProcessedImage, (progress) => { StatusMessageUpdater(testingProgressMessage + " Прогрес - " + progress.ToString("0") + "%"); }); if (imageType == ImageType.CAT) { var rectanglesImage = new Image <Bgr, Byte>(OriginalImage.Width, OriginalImage.Height, new Bgr(0, 0, 0)); foreach (var rectangle in rectangles) { rectanglesImage.Draw(rectangle, new Bgr(150, 0, 0), 2); } OriginalImage = OriginalImage.AddWeighted(rectanglesImage, 1, 1, 0); var mainRectangle = AnchorBox.GetBoundingReactange(rectangles); OriginalImage.Draw(mainRectangle, new Bgr(0, 200, 0), 5); OriginalImage.Draw("Cat", new System.Drawing.Point(30, 120), FontFace.HersheyPlain, 8f, new Bgr(0, 200, 0), 10); } else { OriginalImage.Draw("No cat", new System.Drawing.Point(30, 120), FontFace.HersheyPlain, 8f, new Bgr(0, 0, 255), 10); } var temp = this.OriginalImage; this.OriginalImage = null; this.OriginalImage = temp; this.OriginalImage.ROI = System.Drawing.Rectangle.Empty; }); task.Start(); task.ContinueWith((t) => { this.DetectionInProgress = false; StatusMessageUpdater("Готово"); }); }
internal void ClearImage() { if (OriginalImage != null) { OriginalImage.Dispose(); OriginalImage = null; } if (ThumbImage != null) { ThumbImage.Dispose(); ThumbImage = null; } // this.gridControl1.DataSource = null; }
public void ApplyHaarTransform(bool Forward, bool Safe, int iterations) { decimal[][,] temp = Forward ? OriginalImage.DeepClone() : TransformedImage.DeepClone(); //int Iterations = 0; //int.TryParse(sIterations, out Iterations); decimal[,] Red = temp[0]; decimal[,] Green = temp[1]; decimal[,] Blue = temp[2]; int maxScale = (int)(Math.Log(Red.GetLength(0) < Red.GetLength(1) ? Red.GetLength(0) : Red.GetLength(1)) / Math.Log(2)); if (iterations < 1 || iterations > maxScale) { MessageBox.Show("Iteration must be Integer from 1 to " + maxScale); return; } int time = Environment.TickCount; if (Forward) { DwtF(Red, iterations); DwtF(Green, iterations); DwtF(Blue, iterations); } else { IDwtF(Red, iterations); IDwtF(Green, iterations); IDwtF(Blue, iterations); } if (Forward) { TransformedImage = temp.DeepClone(); } else { OriginalImage = temp.DeepClone(); } string transformationTime = ((int)(Environment.TickCount - time)).ToString() + " milis."; }
/// <summary> /// 监控文件夹中是否穿件新图片 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnChanged(object sender, FileSystemEventArgs e) { if (!bDirty) { stringBuilder.Remove(0, stringBuilder.Length); stringBuilder.Append(e.FullPath); stringBuilder.Append(" "); stringBuilder.Append(e.ChangeType.ToString()); stringBuilder.Append(" "); stringBuilder.Append(DateTime.Now.ToString()); bDirty = true; if (e.ChangeType == WatcherChangeTypes.Created) { OriginalImage originalImage = new OriginalImage(new DateTime(), e.Name, e.FullPath); originalImages.Push(originalImage); } } }
internal void ShowOriginalImage() { this.picEditOriginal.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom; if (OriginalImage != null) { OriginalImage.Dispose(); } if (ThumbImage != null) { ThumbImage.Dispose(); } //OriginalImage = m_Record.OriginalPic == null ? null : m_Record.OriginalPic.Clone() as Image; //ThumbImage = m_Record.ObjectPic == null ? null : m_Record.ObjectPic.Clone() as Image; AutoFit(); }