protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName == nameof(Speed)) { cycleTime /= Speed; } if (propertyName == nameof(AutoStart)) { if (AutoStart) { start(); } } if (propertyName == nameof(Source)) { string resourceID = Source; Assembly assembly = GetType().GetTypeInfo().Assembly; using (Stream stream = assembly.GetManifestResourceStream(resourceID)) { if (stream != null) { resourceBitmap = SKBitmap.Decode(stream); } } resourceBitmap = resourceBitmap?.Resize(new SKImageInfo(90, 90), SKFilterQuality.Medium); } }
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName == nameof(EmbeddedImageName)) { string resourceID = EmbeddedImageName; Assembly assembly = GetType().GetTypeInfo().Assembly; using (Stream stream = assembly.GetManifestResourceStream(resourceID)) { if (stream != null) { _resourceBitmap = SKBitmap.Decode(stream); } } _resourceBitmap = _resourceBitmap?.Resize(new SKImageInfo(90, 90), SKFilterQuality.Medium); } }
private SKImage PrepareBackground(SKBitmap background) { // calculate aspect ratio float bgWidth = background.Width; float bgHeight = background.Height; float ratio = bgWidth / bgHeight; if (ratio > 0) { // image is horizontal // resize to fit background int width = (int)(profileWidth * ratio); int height = profileHeight; background = background.Resize(new SKSizeI(width, height), SKFilterQuality.High); } else { // image is vertical // resize to fit background int width = profileWidth; int height = (int)(profileHeight * ratio); background = background.Resize(new SKSizeI(width, height), SKFilterQuality.High); } // crop image // calculate subset rectangle int subsetX = (background.Width - profileWidth) / 2; int subsetY = (background.Height - profileHeight) / 2; int subsetWidth = subsetX + profileWidth; int subsetHeight = subsetY + profileHeight; // convert bitmap to image SKImage image = SKImage.FromBitmap(background); // subset image from background SKRectI subsetRect = new SKRectI(subsetX, subsetY, subsetWidth, subsetHeight); return(image.Subset(subsetRect)); }
public static void DrawWatermark(SKCanvas c) { if (Properties.Settings.Default.UseIconWatermark && !string.IsNullOrWhiteSpace(Properties.Settings.Default.IconWatermarkPath)) { using SKBitmap watermarkBase = SKBitmap.Decode(new FileInfo(Properties.Settings.Default.IconWatermarkPath).Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); int sizeX = watermarkBase.Width * (int)Properties.Settings.Default.IconWatermarkScale / 512; int sizeY = watermarkBase.Height * (int)Properties.Settings.Default.IconWatermarkScale / 512; SKBitmap watermark = watermarkBase.Resize(sizeX, sizeY); float left = Properties.Settings.Default.IconWatermarkX; float top = Properties.Settings.Default.IconWatermarkY; float right = left + watermark.Width; float bottom = top + watermark.Height; c.DrawBitmap(watermark, new SKRect(left, top, right, bottom), new SKPaint { FilterQuality = SKFilterQuality.High, IsAntialias = true, Color = SKColors.Transparent.WithAlpha((byte)Properties.Settings.Default.IconWatermarkOpacity) }); } }
/// <summary> /// Resize image by targetSize /// </summary> /// <param name="image">Source image</param> /// <param name="format">Destination format</param> /// <param name="targetSize">Target size</param> /// <returns>Image as array of byte[]</returns> protected virtual byte[] ImageResize(SKBitmap image, SKEncodedImageFormat format, int targetSize) { if (image == null) { throw new ArgumentNullException("Image is null"); } float width, height; if (image.Height > image.Width) { // portrait width = image.Width * (targetSize / (float)image.Height); height = targetSize; } else { // landscape or square width = targetSize; height = image.Height * (targetSize / (float)image.Width); } if ((int)width == 0 || (int)height == 0) { width = image.Width; height = image.Height; } try { using var resizedBitmap = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.Medium); using var cropImage = SKImage.FromBitmap(resizedBitmap); return(cropImage.Encode(format, _mediaSettings.DefaultImageQuality).ToArray()); } catch { return(image.Bytes); } }
protected async Task <byte[]> ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize) { if (image == null) { throw new ArgumentNullException("image"); } if (targetSize <= 0) { targetSize = 800; } float width, height; if (image.Height > image.Width) { // portrait width = image.Width * (targetSize / (float)image.Height); height = targetSize; } else { // landscape or square width = targetSize; height = image.Height * (targetSize / (float)image.Width); } if ((int)width == 0 || (int)height == 0) { width = image.Width; height = image.Height; } using (var resized = image.Resize(new SKImageInfo((int)width, (int)height), SKFilterQuality.Low)) { using (var resimage = SKImage.FromBitmap(resized)) { return(await Task.FromResult(resimage.Encode(format, _mediaSettings.DefaultImageQuality).ToArray())); } } }
static bool DecodeImageFrame(SKCodec codec, SKBitmap bitmap, out Frame decoded, int index = -1) { decoded = null; if (( (index < 0) ? codec.GetPixels(codec.Info, bitmap.GetPixels()) : codec.GetPixels(codec.Info, bitmap.GetPixels(), new SKCodecOptions(index, index - 1)) ) == SKCodecResult.Success) { SKBitmap resized = bitmap.Resize(targetInfo, SKFilterQuality.High); decoded = new Frame(new Time( false, free: (index < 0) ? 1000 : codec.FrameInfo[index].Duration )); for (int x = 0; x <= 9; x++) { for (int y = 0; y <= 9; y++) { SKColor color = resized.GetPixel(x, 9 - y); decoded.Screen[y * 10 + x] = new Color( (byte)(color.Red >> 2), (byte)(color.Green >> 2), (byte)(color.Blue >> 2) ); } } return(true); } else { return(false); } }
private async void CreateAndSaveBitmap(string imageUri, string fileName, bool asThumbnail) { SKBitmap bitmap = await CreateBitmapFromStream(imageUri); if (bitmap != null) { if (!asThumbnail) { bitmap = bitmap.Resize(new SKImageInfo(300, 300), SKFilterQuality.Medium); } using (SKImage image = SKImage.FromBitmap(bitmap)) { using (SKData encoded = image.Encode(SKEncodedImageFormat.Jpeg, 100)) { using (System.IO.Stream outFile = System.IO.File.OpenWrite(fileName)) { encoded.SaveTo(outFile); } } _eventAggregator.GetEvent <CacheChangedEvent>().Publish(CacheChangeMode.Added); } } }
private void drawImageBackground(SKCanvas canvas) { SKBitmap bgBitmap = SkiaHelper.createPersistentBitmap(background.imagePath, canvasSize.width, canvasSize.height); if (bgBitmap.Width != canvasSize.width || bgBitmap.Height != canvasSize.height) { var info = new SKImageInfo(canvasSize.width, canvasSize.height); bgBitmap = bgBitmap.Resize(info, SKFilterQuality.High); } if (background.blur.HasValue && background.blur != 0) { var filter = SKImageFilter.CreateBlur((int)background.blur, (int)background.blur); var paint = new SKPaint { ImageFilter = filter }; canvas.DrawBitmap(bgBitmap, new SKPoint(0, 0), paint); } else { canvas.DrawBitmap(bgBitmap, new SKPoint(0, 0)); } }
private static SKBitmap ThumbnailBitmap(SKBitmap bitmap, int?logoSideWidth = null) { SKSizeI size; if (logoSideWidth.HasValue) { if (bitmap.Width != bitmap.Height) { SKRect rect = CalculateCroppingRect(bitmap); SKBitmap croppedBitmap = CropBitmap(bitmap, rect); bitmap = croppedBitmap; } size = new SKSizeI(bitmap.Height * (logoSideWidth.Value / bitmap.Height), logoSideWidth.Value); } else { size = new SKSizeI(bitmap.Width, bitmap.Height); } return(bitmap.Resize(size, SKFilterQuality.Medium)); }
private TagMaskExtraction ProcessMaskedTag(HyperTag tag) { var geometry = tag.GetElement <HyperTagGeometry>(); var geometryMask = tag.GetElement <HyperTagGeometryMask>(); if (geometryMask == null || geometry == null) { return(null); } //var classification = tag.GetElements<HyperTagLabel>().Where(x => x.Type == HyperTagLabel.Types.Classification).Select(x => x.Label).FirstOrDefault(); //if (classification == null) //{ // classification = tag.GetElement<TagonomyExecutionResultHyperTagElement>()?.GetCombinedLabel(); //} var rect = geometry.GeometryItem.BoundingBox; rect = geometry.GeometryItem.ConvertFromAbsoluteXSpaceToRealWorldSpace(rect, _width, _height); var skBitmap = SKBitmap.Decode(geometryMask.RawData); if (skBitmap.Width != geometryMask.Width || skBitmap.Height != geometryMask.Height) { var newSkBitmap = new SKBitmap((int)rect.Width, (int)rect.Height); using (skBitmap) { SKBitmap.Resize(newSkBitmap, skBitmap, SKBitmapResizeMethod.Lanczos3); } skBitmap = newSkBitmap; } return(new TagMaskExtraction { Image = skBitmap, Rect = rect }); }
public async Task <string> Upload(string url) { string guid = Guid.NewGuid().ToString(); using (HttpClient httpClient = new HttpClient()) { using SKBitmap skBitmap = SKBitmap.Decode(await httpClient.GetByteArrayAsync(url)); if (skBitmap == null) { throw new Exception(); } using Stream outputStream = File.OpenWrite(environment.WebRootPath + "/original/" + guid + ".jpg"); using Stream outputResizedStream = File.OpenWrite(environment.WebRootPath + "/preview/" + guid + ".jpg"); using (SKImage skImage = SKImage.FromBitmap(skBitmap)) { skImage.Encode(SKEncodedImageFormat.Jpeg, 70).SaveTo(outputStream); } using (SKBitmap skBitmapResized = skBitmap.Resize(new SKImageInfo(100, 100), SKFilterQuality.High)) { if (skBitmapResized == null) { throw new Exception(); } using (SKImage skImage = SKImage.FromBitmap(skBitmapResized)) { skImage.Encode(SKEncodedImageFormat.Jpeg, 70).SaveTo(outputResizedStream); } } } return(guid); }
/// <summary> /// /// </summary> /// <param name="imagedata"></param> /// <param name="imageCompressionFactor">Percentage the Part wich schould be used.</param> /// <returns></returns> public static byte[] CompressImage(byte[] imagedata, float imageCompressionFactor) { using (SKBitmap bmp = SKBitmap.Decode(imagedata)) { int size = (int)(bmp.Width * imageCompressionFactor); int width, height; if (bmp.Width > bmp.Height) { width = size; height = bmp.Height * size / bmp.Width; } else { width = bmp.Width * size / bmp.Height; height = size; } SKBitmap scaled = bmp.Resize(new SKImageInfo(width, height), SKBitmapResizeMethod.Lanczos3); SKData imageData = SKImage.FromBitmap(scaled).Encode(SKEncodedImageFormat.Jpeg, 100); if (APIStatics.ISDebugging) { Guid imagID = Guid.NewGuid(); Directory.CreateDirectory("/images"); using (var filestream = File.OpenWrite($"/images/image{imagID}.png")) { imageData.SaveTo(filestream); } } using (BinaryReader br = new BinaryReader(imageData.AsStream())) { return(br.ReadBytes((int)imageData.Size)); } } }
/// <summary> /// 重新调整图片的尺寸 /// </summary> /// <param name="imageStream">源图片流</param> /// <param name="maxSize">最大尺寸</param> /// <param name="isSameRate">是否保存相同比率</param> /// <returns></returns> public static byte[] Resize(Stream imageStream, ImageSize maxSize, bool isSameRate = false) { using (SKManagedStream managedStream = new SKManagedStream(imageStream)) //包装流 { using (SKBitmap bitmap = SKBitmap.Decode(managedStream)) // 将流加载到图片中 { if (bitmap == null) { throw new ImageException("传递的参数不是有效图片"); } ImageSize sourceSize = new ImageSize(bitmap.Width, bitmap.Height); ImageSize newSize = maxSize; if (isSameRate) { newSize = ImageSize.GetSameRateSize(sourceSize, maxSize); } using (SKBitmap newBitmap = bitmap.Resize(new SKImageInfo(newSize.Width, newSize.Height), SKFilterQuality.High)) { if (newBitmap == null) { throw new ImageException("调整图片尺寸失败"); } using (SKImage image = SKImage.FromBitmap(newBitmap)) { using (SKData p = image.Encode(SKEncodedImageFormat.Jpeg, 100)) { return(p.ToArray()); } } } } } }
public void Resize(DpiPath dpi, string destination) { int sourceNominalWidth = Info.BaseSize?.Width ?? bmp.Width; int sourceNominalHeight = Info.BaseSize?.Height ?? bmp.Height; var resizeRatio = dpi.Scale; var sourceActualWidth = bmp.Width; var sourceActualHeight = bmp.Height; var nominalRatio = Math.Max((double)sourceNominalWidth / (double)sourceActualWidth, (double)sourceNominalHeight / (double)sourceActualHeight); var adjustRatio = nominalRatio * Convert.ToDouble(resizeRatio); var newWidth = (int)Math.Floor(bmp.Width * adjustRatio); var newHeight = (int)Math.Floor(bmp.Height * adjustRatio); using (var rzBitmap = bmp.Resize(new SKImageInfo(newWidth, newHeight), SKFilterQuality.High)) using (var img = SKImage.FromBitmap(rzBitmap)) using (var data = img.Encode(SKEncodedImageFormat.Png, 100)) using (var fs = File.Open(destination, FileMode.Create)) { data.SaveTo(fs); } }
/// <summary> /// Builds user interface icons /// </summary> /// <returns>The named icon.</returns> /// <param name="resource">Resource.</param> /// <param name="text">Text.</param> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> /// <param name="tagCode">Tag code.</param> /// <param name="alignRight">If set to <c>true</c> align right.</param> /// <param name="alignBottom">If set to <c>true</c> align bottom.</param> /// <param name="opaqueBackground">If set to <c>true</c> opaque background.</param> public IconImage BuildNamedIcon(string resource, string text, float x, float y, int tagCode, bool alignRight = false, bool alignBottom = false, bool opaqueBackground = false) { IconImage image = null; SKSize loadedSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, 1f, 1f); using (System.IO.Stream stream = App.MainAssembly.GetManifestResourceStream(resource)) { SKBitmap tempBitmapPre = SKBitmap.Decode(stream); SKBitmap tempBitmap = tempBitmapPre.Resize(new SKImageInfo((int)loadedSize.Width, (int)loadedSize.Width), SKBitmapResizeMethod.Lanczos3); //SkiaSharp.SKBitmap tempBitmap = SkiaSharp.SKBitmap.Decode(stream); SKBitmap returnBitmap = new SKBitmap((int)System.Math.Round(tempBitmap.Width * 1.5), (int)System.Math.Round(tempBitmap.Height * 1.5), tempBitmap.ColorType, tempBitmap.AlphaType); using (SKCanvas canvas2 = new SKCanvas(returnBitmap)) { if (opaqueBackground) { canvas2.Clear(SKColors.White); } else { canvas2.Clear(SKColors.Transparent); } canvas2.DrawBitmap(tempBitmap, SKRect.Create(System.Convert.ToInt16(tempBitmap.Width * 0.25), System.Convert.ToInt16(tempBitmap.Height * 0.1), tempBitmap.Width, tempBitmap.Height)); using (SKPaint paint = new SKPaint()) { paint.TextSize = Constants.DeviceLayout.TextSizeDefault * App.DisplayScaleFactor; paint.IsAntialias = true; paint.Color = SKColors.Black; paint.TextAlign = SKTextAlign.Center; canvas2.DrawText(text, (System.Convert.ToSingle(tempBitmap.Width) * 1.5f) / 2f, (System.Convert.ToSingle(tempBitmap.Height) * 1.35f), paint); } canvas2.Flush(); SKSize finalSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, Constants.DeviceLayout.InterfaceDimensionDefault, Constants.DeviceLayout.InterfaceDimensionDefault); SKPoint settingsPoint; if ((int)x == -1 || (int)y == -1) { settingsPoint = Constants.DeviceLayout.GetCenterPoint(canvasReference.CanvasSize); } else { settingsPoint = new SKPoint(x, y); } if (alignRight) { settingsPoint.X -= finalSize.Width; } if (alignBottom) { settingsPoint.Y -= finalSize.Height; } image = new IconImage(returnBitmap) { Tag = tagCode, Text = text, BorderColor = SKColors.Black, LocalImage = true, ImageInformation = resource, IsInsertableIntoFolder = false, StoredFolderTag = "", BorderWidth = 2f, Bounds = SKRect.Create(settingsPoint, finalSize) }; return(image); } } }
public void SkiaBitmapResizeBenchmark() { var original = new SKBitmap(Width, Height); var resized = original.Resize(new SKImageInfo(ResizedWidth, ResizedHeight), SKBitmapResizeMethod.Lanczos3); var image = SKImage.FromBitmap(resized); }
public static SKBitmap CenterImage(SKBitmap bitmap) { SKBitmap bmp; SKBitmap Bitmap = bitmap; int xleft = Bitmap.Width; int xright = 0; int ytop = Bitmap.Height; int ybottom = 0; //xleft for (int y = 0; y < Bitmap.Height; y++) { for (int x = 0; x < Bitmap.Width; x++) { SKColor color = Bitmap.GetPixel(x, y); if (color.Red > 0) { if (x < xleft) { xleft = x; } } } } //xright for (int y = 0; y < Bitmap.Height; y++) { for (int x = Bitmap.Width - 1; x >= 0; x--) { SKColor color = Bitmap.GetPixel(x, y); if (color.Red > 0) { if (x > xright) { xright = x; } } } } //ytop for (int x = 0; x < Bitmap.Width; x++) { for (int y = 0; y < Bitmap.Height; y++) { SKColor color = Bitmap.GetPixel(x, y); if (color.Red > 0) { if (y < ytop) { ytop = y; } } } } //yright for (int x = 0; x < Bitmap.Width; x++) { for (int y = Bitmap.Height - 1; y >= 0; y--) { SKColor color = Bitmap.GetPixel(x, y); if (color.Red > 0) { if (y > ybottom) { ybottom = y; } } } } bmp = new SKBitmap(xright - xleft + 1, ybottom - ytop + 1); for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { bmp.SetPixel(x, y, Bitmap.GetPixel(x + xleft, y + ytop)); } } int newHeight = 20; int newWidth = Math.Min(newHeight * bmp.Width / bmp.Height, 20); bmp = bmp.Resize(new SKImageInfo(newWidth, newHeight), SKBitmapResizeMethod.Box); var pixels = new SKColor[28 * 28]; for (int i = 0; i < pixels.Length; i++) { pixels[i] = SKColors.Black; } Bitmap = new SKBitmap(28, 28); Bitmap.Pixels = pixels; //calculate center of mass float meanX = 0; float meanY = 0; float mass = 0; for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { float value = bmp.GetPixel(x, y).Red / 255.0F; meanX += x * value; meanY += y * value; mass += value; } } meanX = meanX / mass; meanY = meanY / mass; //bmp.SetPixel((int)meanX, (int)meanY, SKColors.Green); for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { Bitmap.SetPixel(maxMin(x + Convert.ToInt32(Bitmap.Width / 2 - meanX), Bitmap.Width - 1, 0), maxMin(y + Convert.ToInt32(Bitmap.Height / 2 - meanY), Bitmap.Height - 1, 0), bmp.GetPixel(x, y)); } } return(Bitmap); int maxMin(int val, int max, int min) { return(Math.Max(Math.Min(val, max), min)); } }
public void ResizeImage(int width, int height) { SourceImage = SourceImage.Resize(new SKImageInfo(width, height), SKFilterQuality.Medium); }
public BaseUIData(IUExport[] exports, int baseIndex) : this() { if (exports[baseIndex].GetExport <TextProperty>("DisplayName") is TextProperty displayName) { DisplayName = Text.GetTextPropertyBase(displayName) ?? ""; } if (exports[baseIndex].GetExport <TextProperty>("Description") is TextProperty description) { Description = Text.GetTextPropertyBase(description) ?? ""; if (Description.Equals(DisplayName)) { Description = string.Empty; } if (!string.IsNullOrEmpty(Description)) { Height += (int)descriptionPaint.TextSize * Helper.SplitLines(Description, descriptionPaint, Width - Margin).Count; Height += (int)descriptionPaint.TextSize; } } if (exports[baseIndex].GetExport <ObjectProperty>("StoreFeaturedImage", "FullRender", "VerticalPromoImage", "LargeIcon", "DisplayIcon2", "DisplayIcon") is ObjectProperty icon) { SKBitmap raw = Utils.GetObjectTexture(icon); if (raw != null) { float coef = (float)Width / (float)raw.Width; int sizeX = (int)(raw.Width * coef); int sizeY = (int)(raw.Height * coef); Height += sizeY; IconImage = raw.Resize(sizeX, sizeY); } } if (exports[baseIndex].GetExport <MapProperty>("Abilities") is MapProperty abilities) { AdditionalWidth = 768; foreach (var(_, value) in abilities.Value) { if (value is ObjectProperty o && o.Value.Resource == null && o.Value.Index > 0) { Statistic s = new Statistic(); if (exports[o.Value.Index - 1].GetExport <TextProperty>("DisplayName") is TextProperty aDisplayName) { s.DisplayName = Text.GetTextPropertyBase(aDisplayName) ?? ""; } if (exports[o.Value.Index - 1].GetExport <TextProperty>("Description") is TextProperty aDescription) { s.Description = Text.GetTextPropertyBase(aDescription) ?? ""; if (!string.IsNullOrEmpty(Description)) { s.Height += (int)descriptionPaint.TextSize * Helper.SplitLines(s.Description, descriptionPaint, Width - Margin).Count; s.Height += (int)descriptionPaint.TextSize * 3; } } if (exports[o.Value.Index - 1].GetExport <ObjectProperty>("DisplayIcon") is ObjectProperty displayIcon) { SKBitmap raw = Utils.GetObjectTexture(displayIcon); if (raw != null) { s.Icon = raw.Resize(128, 128); } } Abilities.Add(s); } } } }
/// <summary> /// Builds the communication folder local. /// </summary> /// <returns>The communication folder local.</returns> /// <param name="icon">Icon.</param> public IconImage BuildCommunicationFolderLocal(Storage.CommunicationIcon icon) { IconImage image = null; SKSize loadedSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, icon.Scale, icon.Scale); using (System.IO.Stream stream = App.MainAssembly.GetManifestResourceStream(icon.ResourceLocation)) { SKBitmap tempBitmapPre = SKBitmap.Decode(stream); SKBitmap tempBitmap = tempBitmapPre.Resize(new SKImageInfo((int)loadedSize.Width, (int)loadedSize.Width), SKBitmapResizeMethod.Lanczos3); SKBitmap returnBitmap = new SKBitmap((int)System.Math.Round(tempBitmap.Width * 1.5), (int)System.Math.Round(tempBitmap.Height * 1.5), tempBitmap.ColorType, tempBitmap.AlphaType); using (SKCanvas canvas2 = new SKCanvas(returnBitmap)) { canvas2.Clear(SKColors.Transparent); canvas2.DrawBitmap(tempBitmap, SKRect.Create(System.Convert.ToInt16(tempBitmap.Width * 0.15), System.Convert.ToInt16(tempBitmap.Height * 0.1), tempBitmap.Width * 1.3f, tempBitmap.Height * 1.3f)); using (SKPaint paint = new SKPaint()) { paint.TextSize = Constants.DeviceLayout.TextSizeDefault * App.DisplayScaleFactor * icon.Scale; paint.IsAntialias = true; paint.Color = SKColors.White; paint.TextAlign = SKTextAlign.Center; canvas2.DrawText(icon.Text, (System.Convert.ToSingle(tempBitmap.Width) * 1.5f) / 2f, (System.Convert.ToSingle(tempBitmap.Height) * 1.5f) - (System.Convert.ToSingle(tempBitmap.Height) * 1.5f) / 4f, paint); } canvas2.Flush(); } SKSize finalSize = Constants.DeviceLayout.GetSizeByGrid(canvasReference.CanvasSize, Constants.DeviceLayout.InterfaceDimensionDefault, Constants.DeviceLayout.InterfaceDimensionDefault); SKPoint settingsPoint; if ((int)icon.X == -1 || (int)icon.Y == -1) { settingsPoint = Constants.DeviceLayout.GetCenterPoint(canvasReference.CanvasSize); } else { settingsPoint = new SKPoint(icon.X, icon.Y); } image = new IconImage(returnBitmap) { Tag = icon.Tag, Text = icon.Text, ImageInformation = icon.ResourceLocation, LocalImage = true, IsInsertableIntoFolder = false, IsPinnedToSpot = icon.IsPinned, StoredFolderTag = icon.FolderContainingIcon, IsStoredInAFolder = icon.IsStoredInFolder, CurrentScale = icon.Scale, BorderColor = SKColors.Black, BorderWidth = 2f, Bounds = SKRect.Create(settingsPoint, loadedSize) }; return(image); } }
private void Leaning_Click(object sender, EventArgs e) { if (skimage == null) { return; } SKBitmap bitmap = SKBitmap.FromImage(skimage); var scaledBitmap = bitmap.Resize(new SKImageInfo(400, 400), SKBitmapResizeMethod.Triangle); skimage = SKImage.FromBitmap(scaledBitmap); bitmap = SKBitmap.FromImage(skimage); SKData pngImage = skimage.Encode(); var byteArray = pngImage.ToArray(); Stream stream = new MemoryStream(byteArray); ImageDim.Source = ImageSource.FromStream(() => { return(stream); }); SKColor[] arrColors = bitmap.Pixels; List <bool> boolImage = new List <bool>(); foreach (var item in arrColors) { boolImage.Add(item.ToFormsColor() == Color.Black); } var namePicture = NamePicture.Text; if (string.IsNullOrEmpty(namePicture)) { DisplayAlert("Error", "empty name", "ok"); return; } var answer = new Answer(); string check = ""; do { if (answers.Any(x => x.Name == namePicture)) { answer = answers.FirstOrDefault(x => x.Name == namePicture); for (int i = 0; i < boolImage.Count; i++) { if (boolImage[i]) { answer.Weights[i] += 0.02; } else { answer.Weights[i] -= 0.005; } } } else { answer.Name = namePicture; foreach (var isBlackPic in boolImage) { if (isBlackPic) { answer.Weights.Add(0.02); } else { answer.Weights.Add(0.001); } } answers.Add(answer); } check = ChekeResult(); } while (check != namePicture); NamePicture.Text = string.Empty; Cleane_Click(null, null); DisplayAlert("Status", "Success", "ok"); }
public static SKBitmap ResizeImage(SKBitmap original, int w, int h, string mode) { SKBitmap bitmap = null; if (w == 0 && h != 0) { w = original.Width * h / original.Height; var imageInfo = new SKImageInfo(w, h, SKImageInfo.PlatformColorType, original.AlphaType); bitmap = original.Resize(imageInfo, SKFilterQuality.High); } else if (h == 0 && w != 0) { h = original.Height * w / original.Width; var imageInfo = new SKImageInfo(w, h, SKImageInfo.PlatformColorType, original.AlphaType); bitmap = original.Resize(imageInfo, SKFilterQuality.High); } else if (w != 0 && h != 0) { float originalRatio = ((float)original.Height) / ((float)original.Width); float ratio = ((float)h) / ((float)w); switch (mode) { case "pad": { SKRectI drawRect; if (originalRatio < ratio) { var newW = w; var newH = original.Height * w / original.Width; var pad = (h - newH) / 2; drawRect = new SKRectI { Left = 0, Top = pad, Right = newW, Bottom = newH + pad }; } else { var newW = original.Width * h / original.Height; var newH = h; var pad = (w - newW) / 2; drawRect = new SKRectI { Left = pad, Top = 0, Right = newW + pad, Bottom = newH }; } bitmap = new SKBitmap(w, h, true); var canvas = new SKCanvas(bitmap); canvas.Clear(new SKColor(255, 255, 255)); var imageInfo = new SKImageInfo(drawRect.Width, drawRect.Height, SKImageInfo.PlatformColorType, original.AlphaType); original = original.Resize(imageInfo, SKFilterQuality.High); canvas.DrawBitmap(original, drawRect, new SKPaint()); canvas.Flush(); canvas.Dispose(); break; } case "crop": { SKRectI drawRect; if (originalRatio < ratio) { var newW = original.Width * h / original.Height; var pad = (newW - w) / 2; var imageInfo = new SKImageInfo(newW, h, SKImageInfo.PlatformColorType, original.AlphaType); var resizedBitmap = original.Resize(imageInfo, SKFilterQuality.High); drawRect = new SKRectI { Left = pad, Top = 0, Right = w + pad, Bottom = h }; bitmap = new SKBitmap(drawRect.Width, drawRect.Height, true); resizedBitmap.ExtractSubset(bitmap, drawRect); } else { var newH = original.Height * w / original.Width; var pad = (newH - h) / 2; var imageInfo = new SKImageInfo(w, newH, SKImageInfo.PlatformColorType, original.AlphaType); var resizedBitmap = original.Resize(imageInfo, SKFilterQuality.High); drawRect = new SKRectI { Left = 0, Top = pad, Right = w, Bottom = h + pad }; bitmap = new SKBitmap(drawRect.Width, drawRect.Height); resizedBitmap.ExtractSubset(bitmap, drawRect); } break; } default: break; } } else { bitmap = original.Copy(); } original.Dispose(); return(bitmap); }
private void PaintSurface(object sender, SKPaintSurfaceEventArgs args, computeLensRequestSideDTO computeLensRequestSideDTO, computeLensResponseSideDTO computeLensResponseSideDTO) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); SKPaint blackSKPaint = new SKPaint { Style = SKPaintStyle.Fill, Color = Color.Black.ToSKColor(), }; canvas.DrawRect(new SKRect(0, 0, info.Width, info.Height), blackSKPaint); if (computeLensResponseSideDTO.points != null & computeLensResponseSideDTO.points.Any()) { ICollection <analyzedPointDTO> points = computeLensResponseSideDTO.points.Where(point => point is analyzedPointDTO && Math.Abs(point.x) <= computeLensRequestSideDTO.horizontalDiameter / 2.0 && Math.Abs(point.y) <= computeLensRequestSideDTO.verticalDiameter / 2.0).Select(point => point as analyzedPointDTO).ToList(); double maxCylinder = points.Select(point => point.cylinderMap).Max(); double minCylinder = points.Select(point => point.cylinderMap).Min(); double cylinderRange = (maxCylinder - minCylinder) / 6.0; if (cylinderRange > 0) { double doubleCylinderRange = cylinderRange * 2; double tripleCylinderRange = cylinderRange * 3; double fiveCylinderRange = cylinderRange * 5; double centerX = info.Width / 2.0; double centerY = info.Height / 2.0; int sqrt = Convert.ToInt32(Math.Sqrt(points.Count)); int side = (sqrt - 1) / 2; double bitmapSide = Math.Min(info.Width, info.Height) / 2.0; double sqrtRange = sqrt / 6.0; double doubleSqrtRange = sqrtRange * 2; double tripleSqrtRange = sqrtRange * 3; double fiveSqrtRange = sqrtRange * 5; using (SKBitmap bitmap = new SKBitmap(1, sqrt)) { for (int i = sqrt - 1; i >= 0; i--) { SKColor color = Color.Black.ToSKColor(); switch (Math.Floor(i / sqrtRange)) { case 0: color = Color.FromRgb(Convert.ToInt32(Math.Round(i / sqrtRange * 255)), Convert.ToInt32(Math.Round(i / sqrtRange * 255)), 255).ToSKColor(); break; case 1: color = Color.FromRgb(Convert.ToInt32(Math.Round((doubleSqrtRange - i) / sqrtRange * 255)), 255, 255).ToSKColor(); break; case 2: color = Color.FromRgb(0, 255, Convert.ToInt32(Math.Round((tripleSqrtRange - i) / sqrtRange * 255))).ToSKColor(); break; case 3: color = Color.FromRgb(Convert.ToInt32(Math.Round((i - tripleSqrtRange) / sqrtRange * 255)), 255, 0).ToSKColor(); break; case 4: color = Color.FromRgb(255, Convert.ToInt32(Math.Round((fiveSqrtRange - i) / sqrtRange * 255)), 0).ToSKColor(); break; default: color = Color.FromRgb(255, 0, Convert.ToInt32(Math.Round((i - fiveSqrtRange) / sqrtRange * 255))).ToSKColor(); break; } bitmap.SetPixel(0, i, color); } canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide / 6), Convert.ToInt32(bitmapSide)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(info.Width - bitmapSide / 6), 0, Convert.ToSingle(info.Width), info.Height)); } blackSKPaint.TextSize = info.Height / 32; float textRange = (info.Height - blackSKPaint.TextSize * 3) / 6; canvas.DrawText(string.Format("{0:N2}", minCylinder), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 2), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 2, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 3), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 3, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 4), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 4, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 5), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 5, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", maxCylinder), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 6, blackSKPaint); using (SKBitmap bitmap = new SKBitmap(sqrt, sqrt)) { foreach (analyzedPointDTO point in points) { SKColor color = Color.Black.ToSKColor(); double value = point.cylinderMap - minCylinder; switch (Math.Floor(value / cylinderRange)) { case 0: color = Color.FromRgb(Convert.ToInt32(Math.Round(value / cylinderRange * 255)), Convert.ToInt32(Math.Round(value / cylinderRange * 255)), 255).ToSKColor(); break; case 1: color = Color.FromRgb(Convert.ToInt32(Math.Round((doubleCylinderRange - value) / cylinderRange * 255)), 255, 255).ToSKColor(); break; case 2: color = Color.FromRgb(0, 255, Convert.ToInt32(Math.Round((tripleCylinderRange - value) / cylinderRange * 255))).ToSKColor(); break; case 3: color = Color.FromRgb(Convert.ToInt32(Math.Round((value - tripleCylinderRange) / cylinderRange * 255)), 255, 0).ToSKColor(); break; case 4: color = Color.FromRgb(255, Convert.ToInt32(Math.Round((fiveCylinderRange - value) / cylinderRange * 255)), 0).ToSKColor(); break; default: color = Color.FromRgb(255, 0, Convert.ToInt32(Math.Round((value - fiveCylinderRange) / cylinderRange * 255))).ToSKColor(); break; } bitmap.SetPixel(Convert.ToInt32(side - point.x), Convert.ToInt32(side - point.y), color); } using (SKPath path = new SKPath()) { path.AddCircle(Convert.ToSingle(centerX), Convert.ToSingle(centerY), Convert.ToSingle(bitmapSide * 5 / 6)); canvas.ClipPath(path, SKClipOperation.Intersect); } canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide * 5 / 6), Convert.ToInt32(bitmapSide * 5 / 6)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(centerX - bitmapSide * 5 / 6), Convert.ToSingle(centerY - bitmapSide * 5 / 6), Convert.ToSingle(centerX + bitmapSide * 5 / 6), Convert.ToSingle(centerY + bitmapSide * 5 / 6))); } } } }
static public SKBitmap Encode(ref SKBitmap photo1, ref SKBitmap photo2, float photo1K, float photo2K, byte threshold) { //灰度处理 SKColor[] photo1ColorArray = null; photo1ColorArray = photo1.Pixels; for (int i = 0; i < photo1ColorArray.Length; i++) { int tmpValue = (int)(GetGrayNumColor(photo1ColorArray[i]) * photo1K); if (tmpValue < threshold + 1) { tmpValue = threshold + 1; } if (tmpValue > 254) { tmpValue = 254; } photo1ColorArray[i] = new SKColor((byte)tmpValue, (byte)tmpValue, (byte)tmpValue); } photo1.Pixels = photo1ColorArray; SKColor[] photo2ColorArray = null; photo2ColorArray = photo2.Pixels; for (int i = 0; i < photo2ColorArray.Length; i++) { int tmpValue = (int)(GetGrayNumColor(photo2ColorArray[i]) * photo2K); if (tmpValue > threshold) { tmpValue = threshold; } if (tmpValue < 1) { tmpValue = 1; } photo2ColorArray[i] = new SKColor((byte)tmpValue, (byte)tmpValue, (byte)tmpValue); } photo2.Pixels = photo2ColorArray; //调整图像大小 int height = 0, width = 0; if (photo1.Height != photo2.Height || photo1.Width != photo2.Width) { if (photo1.Height > photo2.Height) { height = photo1.Height; } else { height = photo2.Height; } if (photo1.Width > photo2.Width) { width = photo1.Width; } else { width = photo2.Width; } } else { width = photo1.Width; height = photo1.Height; } float aspectRatio = width / height; //高宽比 if (aspectRatio > photo1.Width / photo1.Height) //根据高宽比拉伸图像 { photo1 = photo1.Resize(new SKSizeI(photo1.Width * height / photo1.Height, height), SKFilterQuality.High); } else { photo1 = photo1.Resize(new SKSizeI(width, photo1.Height * width / photo1.Width), SKFilterQuality.High); } if (aspectRatio > photo2.Width / photo2.Height) //根据高宽比拉伸图像 { photo2 = photo2.Resize(new SKSizeI(photo2.Width * height / photo2.Height, height), SKFilterQuality.High); } else { photo2 = photo2.Resize(new SKSizeI(width, photo2.Height * width / photo2.Width), SKFilterQuality.High); } SKBitmap photo1Temp = new SKBitmap(width, height); SKBitmap photo2Temp = new SKBitmap(width, height); SKCanvas photo1Canvas = new SKCanvas(photo1Temp); SKCanvas photo2Canvas = new SKCanvas(photo2Temp); photo1Canvas.DrawColor(SKColors.LightGray); photo2Canvas.DrawColor(SKColors.DimGray); photo1Canvas.DrawBitmap(photo1, width / 2 - photo1.Width / 2, height / 2 - photo1.Height / 2); photo2Canvas.DrawBitmap(photo2, width / 2 - photo2.Width / 2, height / 2 - photo2.Height / 2); photo1ColorArray = photo1Temp.Pixels; photo2ColorArray = photo2Temp.Pixels; /* /!/装配坦克/!/ */ SKBitmap photoTank = new SKBitmap(width, height); SKColor[] photoTankColorArray = new SKColor[width * height]; for (int i = 0; i < width * height; i++) { int pixel1 = photo1ColorArray[i].Red; int pixel2 = photo2ColorArray[i].Red; int alpha = 255 - (pixel1 - pixel2); int gray = (int)(255 * pixel2 / alpha); if (gray > 255) { gray = 255; } photoTankColorArray[i] = new SKColor((byte)gray, (byte)gray, (byte)gray, (byte)alpha); } photoTank.Pixels = photoTankColorArray; return(photoTank); }
private void bwResizeWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; decimal i = 0; var result = Parallel.ForEach(lbBatchFiles.Items.Cast <ImageReference>(), ir => { worker.ReportProgress(Convert.ToInt16((++i / lbBatchFiles.Items.Count) * 100)); if (worker.CancellationPending == true) { e.Cancel = true; return; } else { try { foreach (ResizeParameter resize in lbDimensions.Items) { //Determine name for target file var rootName = Path.GetFileNameWithoutExtension(ir.Name); var targetWidth = resize.TargetWidth; var targetHeight = resize.TargetHeight; string resizeName; if (baseResize != null && baseResize == resize) { resizeName = $"{rootName}.jpg"; } else { resizeName = $"{rootName}_{targetWidth}x{targetHeight}.jpg"; } var sourcePath = Path.Combine(ir.DirectoryPath, ir.Name); //Determine full path for the target file string targetPath = chkMaintainRelativePath.Checked switch { true => Path.Combine(destPath, ir.DirectoryPath.Replace(ir.RootPath + "\\", ""), resizeName), false => Path.Combine(destPath, resizeName) }; //Check for the existence of a file already in that path and apply the chosen action if (File.Exists(targetPath)) { switch (collisionAction) { case Common.Enums.CollisionAction.Skip: return; case Common.Enums.CollisionAction.Overwrite: File.Delete(targetPath); break; case Common.Enums.CollisionAction.RenameResize: resizeName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + ir.Name; targetPath = Path.Combine(destPath, resizeName); break; case Common.Enums.CollisionAction.RenameExisting: var rename = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + ir.Name; var copyPath = Path.Combine(destPath, rename); File.Move(targetPath, copyPath); break; } } //If the target directory doesn't exist, create it var targetDir = new FileInfo(targetPath).Directory; if (!targetDir.Exists) { System.IO.Directory.CreateDirectory(targetDir.FullName); } //If the source is an heic, convert it to jpg please. Thank you Apple. if (sourcePath.EndsWith(".heic")) { if (System.IO.File.Exists(sourcePath)) { using MagickImage original = new(sourcePath) { Format = MagickFormat.Jpg, }; original.Write(sourcePath.Replace(".heic", ".jpg")); System.IO.File.Delete(sourcePath); //Yeah, its fine, they're my pictures } sourcePath = sourcePath.Replace(".heic", ".jpg"); } //Open the the source file for processing using var fileStream = System.IO.File.Open(sourcePath, FileMode.Open); using SKBitmap bitmap = LoadBitmap(fileStream, out SKEncodedOrigin origin); //Determine how the image will best fit within the target dimensions var bitmapRatio = (float)bitmap.Width / bitmap.Height; var resizeRatio = (float)targetWidth / targetHeight; if (bitmapRatio > resizeRatio) { // original is more "landscape" targetHeight = (int)Math.Round(bitmap.Height * ((float)targetWidth / bitmap.Width)); } else { targetWidth = (int)Math.Round(bitmap.Width * ((float)targetHeight / bitmap.Height)); } //Finally, let's do the resize var resizedImageInfo = new SKImageInfo(targetWidth, targetHeight, SKImageInfo.PlatformColorType, bitmap.AlphaType); using SKBitmap resizedBitmap = bitmap.Resize(resizedImageInfo, SKFilterQuality.High); using var resizedImage = SKImage.FromBitmap(resizedBitmap); var encodeFormat = SKEncodedImageFormat.Jpeg; var data = resizedImage.Encode(encodeFormat, 90); using var resizedFile = System.IO.File.Create(targetPath); data.SaveTo(resizedFile); }
private void PaintLens(object sender, SKPaintSurfaceEventArgs args) { analyzeLensResponseDTO analyzeLensResponseDTO = RightLens.Equals(sender) ? model.RightAnalyzeLensResponse : model.LeftAnalyzeLensResponse; SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); SKPaint blackSKPaint = new SKPaint { Style = SKPaintStyle.Fill, Color = SKColors.Black }; canvas.DrawRect(new SKRect(0, 0, info.Width, info.Height), blackSKPaint); if (analyzeLensResponseDTO != null && analyzeLensResponseDTO.points != null & analyzeLensResponseDTO.points.Any()) { int sqrt = Convert.ToInt32(Math.Sqrt(analyzeLensResponseDTO.points.Count())); int side = (sqrt - 1) / 2; ICollection <analyzedPointDTO> points = analyzeLensResponseDTO.points.Where(p => IsInside(p, side + 1)).ToList(); double max = compare && model.RightAnalyzeLensResponse != null && model.LeftAnalyzeLensResponse != null?Math.Max(model.RightAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Max(), model.LeftAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Max()) : points.Where(p => IsInside(p, side + 1)).Select(mapping).Max(); double min = compare && model.RightAnalyzeLensResponse != null && model.LeftAnalyzeLensResponse != null?Math.Min(model.RightAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Min(), model.LeftAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Min()) : points.Where(p => IsInside(p, side + 1)).Select(mapping).Min(); double range = (max - min) / 6.0; if (range > 0) { double centerX = info.Width / 2.0; double centerY = info.Height / 2.0; double bitmapSide = Math.Min(centerX, centerY); double radius = bitmapSide * 5 / 6; double doubleRange = range * 2; double tripleRange = range * 3; double fiveRange = range * 5; double sqrtRange = sqrt / 6.0; double doubleSqrtRange = sqrtRange * 2; double tripleSqrtRange = sqrtRange * 3; double fiveSqrtRange = sqrtRange * 5; using (SKBitmap bitmap = new SKBitmap(1, sqrt)) { for (int i = sqrt - 1; i >= 0; i--) { SKColor color = SKColors.Black; switch (Math.Floor(i / sqrtRange)) { case 0: color = new SKColor(Convert.ToByte(Math.Round(i / sqrtRange * 255)), Convert.ToByte(Math.Round(i / sqrtRange * 255)), 255); break; case 1: color = new SKColor(Convert.ToByte(Math.Round((doubleSqrtRange - i) / sqrtRange * 255)), 255, 255); break; case 2: color = new SKColor(0, 255, Convert.ToByte(Math.Round((tripleSqrtRange - i) / sqrtRange * 255))); break; case 3: color = new SKColor(Convert.ToByte(Math.Round((i - tripleSqrtRange) / sqrtRange * 255)), 255, 0); break; case 4: color = new SKColor(255, Convert.ToByte(Math.Round((fiveSqrtRange - i) / sqrtRange * 255)), 0); break; default: color = new SKColor(255, 0, Convert.ToByte(Math.Round((i - fiveSqrtRange) / sqrtRange * 255))); break; } bitmap.SetPixel(0, i, color); } canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide / 6.0), Convert.ToInt32(bitmapSide)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(info.Width - bitmapSide / 6.0), 0, Convert.ToSingle(info.Width), info.Height)); } blackSKPaint.TextSize = info.Height / 32f; float textRange = (info.Height - blackSKPaint.TextSize * 3) / 6f; canvas.DrawText(string.Format("{0:N2}", min), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", min + range), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", min + range * 2), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 2, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", min + range * 3), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 3, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", min + range * 4), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 4, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", min + range * 5), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 5, blackSKPaint); canvas.DrawText(string.Format("{0:N2}", max), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 6, blackSKPaint); using (SKBitmap bitmap = new SKBitmap(sqrt, sqrt)) { foreach (analyzedPointDTO point in points) { SKColor color = SKColors.Black; double value = mapping.Invoke(point) - min; switch (Math.Floor(value / range)) { case 0: color = new SKColor(Convert.ToByte(Math.Round(value / range * 255)), Convert.ToByte(Math.Round(value / range * 255)), 255); break; case 1: color = new SKColor(Convert.ToByte(Math.Round((doubleRange - value) / range * 255)), 255, 255); break; case 2: color = new SKColor(0, 255, Convert.ToByte(Math.Round((tripleRange - value) / range * 255))); break; case 3: color = new SKColor(Convert.ToByte(Math.Round((value - tripleRange) / range * 255)), 255, 0); break; case 4: color = new SKColor(255, Convert.ToByte(Math.Round((fiveRange - value) / range * 255)), 0); break; default: color = new SKColor(255, 0, Convert.ToByte(Math.Round((value - fiveRange) / range * 255))); break; } bitmap.SetPixel(Convert.ToInt32(side - point.x), Convert.ToInt32(side - point.y), color); } if (mask) { using (SKPath path = new SKPath()) { path.AddCircle(Convert.ToSingle(centerX), Convert.ToSingle(centerY), Convert.ToSingle(radius)); canvas.ClipPath(path, SKClipOperation.Intersect); } } canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(radius), Convert.ToInt32(radius)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(centerX - radius), Convert.ToSingle(centerY - radius), Convert.ToSingle(centerX + radius), Convert.ToSingle(centerY + radius))); } } } }
//----------------------------------------------------------------------------- private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e) { if (bmpSrc == null || Label == null) { return; } var canvas = e.Surface.Canvas; // Resize bitmap to match height of "this" Log.L("SI: canvas wh " + canvas.DeviceClipBounds.Width + ", " + canvas.DeviceClipBounds.Height); if (bmpSrc.Height != canvas.DeviceClipBounds.Height) // resize { float hDest = canvas.DeviceClipBounds.Height; // actual pixels float scale = hDest / (float)bmpSrc.Height; float wDest = bmpSrc.Width * scale; bmpSrc = bmpSrc.Resize(new SKSizeI((int)wDest, (int)hDest), SKFilterQuality.High); } // identify left, right halves and a 10px wide swath of the middle of the source bitmap SKRect rectSrcLeft = new SKRect(0, 0, bmpSrc.Width / 2, bmpSrc.Height); SKRect rectSrcRight = new SKRect(bmpSrc.Width / 2, 0, bmpSrc.Width, bmpSrc.Height); SKRect rectSrcMid = new SKRect(bmpSrc.Width / 2 - 5, 0, bmpSrc.Width / 2 + 5, bmpSrc.Height); // create a new bitmap containing a 10 pixel wide swatch from middle of bmpSrc SKBitmap bmpSrcMid = new SKBitmap(10, bmpSrc.Height); using (SKCanvas tempCanvas = new SKCanvas(bmpSrcMid)) { SKRect rectDest = new SKRect(0, 0, rectSrcMid.Width, rectSrcRight.Height); tempCanvas.DrawBitmap(bmpSrc, rectSrcMid, rectDest); } using (SKPaint paint = new SKPaint()) { // paint.Color = new SKColor (0, 255, 255); // canvas.DrawRect (0, 0, canvas.DeviceClipBounds.Width, canvas.DeviceClipBounds.Height, paint); paint.IsAntialias = false; // determine dest rect for middle section float rightDest = canvas.DeviceClipBounds.Width; SKRect rectDestMid = new SKRect(rectSrcLeft.Width, 0, rightDest - rectSrcRight.Width, rectSrcRight.Height); // left part of tab canvas.DrawBitmap(bmpSrc, rectSrcLeft, rectSrcLeft, paint); Log.L("SI: hSrc " + bmpSrc.Height); // right part of tab { SKRect rectDest = new SKRect(rectDestMid.Right, 0, rightDest, rectSrcRight.Height); canvas.DrawBitmap(bmpSrc, rectSrcRight, rectDest, paint); } // mid part of tab paint.Shader = SKShader.CreateBitmap(bmpSrcMid, SKShaderTileMode.Repeat, SKShaderTileMode.Repeat); canvas.DrawRect(rectDestMid, paint); } using (SKPaint paint = new SKPaint { Color = SKColors.Black }) { paint.TextSize = (paint.TextSize + textSizeAdjustment) * getScreenScaleFactor(); float leftText = padding * getScreenScaleFactor(); float bottomText = canvas.DeviceClipBounds.Height / 2 + textCoreHeight / 2; canvas.DrawText(Label, new SKPoint(leftText, bottomText), paint); } }
private SKData GetImageData(string imagePath, ResizeParams resizeParams, DateTime lastWriteTimeUtc) { // check cache and return if cached string cacheKey; unchecked { cacheKey = "imgasc_" + imagePath.GetHashCode() + lastWriteTimeUtc.ToBinary() + resizeParams.ToString().GetHashCode(); } SKData imageData; byte[] cacheData = _asyncCacheService.GetByKeyAsync <byte[]>(cacheKey).Result; if (cacheData != null) { return(SKData.CreateCopy(cacheData)); } // this represents the EXIF orientation SKBitmap bitmap = LoadBitmap(File.OpenRead(imagePath), out SKEncodedOrigin origin); // always load as 32bit (to overcome issues with indexed color) // if autorotate = true, and origin isn't correct for the rotation, rotate it if (resizeParams.autorotate && origin != SKEncodedOrigin.TopLeft) { bitmap = RotateAndFlip(bitmap, origin); } // if either w or h is 0, set it based on ratio of original image if (resizeParams.h == 0) { resizeParams.h = (int)Math.Round(bitmap.Height * (float)resizeParams.w / bitmap.Width); } else if (resizeParams.w == 0) { resizeParams.w = (int)Math.Round(bitmap.Width * (float)resizeParams.h / bitmap.Height); } // if we need to crop, crop the original before resizing if (resizeParams.mode == "crop") { bitmap = Crop(bitmap, resizeParams); } // store padded height and width int paddedHeight = resizeParams.h; int paddedWidth = resizeParams.w; // if we need to pad, or max, set the height or width according to ratio if (resizeParams.mode == "pad" || resizeParams.mode == "max") { float bitmapRatio = (float)bitmap.Width / bitmap.Height; float resizeRatio = (float)resizeParams.w / resizeParams.h; if (bitmapRatio > resizeRatio) // original is more "landscape" { resizeParams.h = (int)Math.Round(bitmap.Height * ((float)resizeParams.w / bitmap.Width)); } else { resizeParams.w = (int)Math.Round(bitmap.Width * ((float)resizeParams.h / bitmap.Height)); } } // resize SKImageInfo resizedImageInfo = new SKImageInfo(resizeParams.w, resizeParams.h, SKImageInfo.PlatformColorType, bitmap.AlphaType); SKBitmap resizedBitmap = bitmap.Resize(resizedImageInfo, SKFilterQuality.None); // optionally pad if (resizeParams.mode == "pad") { resizedBitmap = Pad(resizedBitmap, paddedWidth, paddedHeight, resizeParams.format != "png"); } // encode SKImage resizedImage = SKImage.FromBitmap(resizedBitmap); SKEncodedImageFormat encodeFormat = resizeParams.format == "png" ? SKEncodedImageFormat.Png : SKEncodedImageFormat.Jpeg; imageData = resizedImage.Encode(encodeFormat, resizeParams.quality); // cache the result _asyncCacheService.SetValueAsync(cacheKey, imageData.ToArray()); // cleanup resizedImage.Dispose(); bitmap.Dispose(); resizedBitmap.Dispose(); return(imageData); }
public SearchFaces(byte[] photoArray, int[] additionalRotateAngles = null, int photoJpegQuality = 95, double faceClippingRatio = 1.2) { if (photoArray != null) { try { using (Stream input = new MemoryStream(photoArray)) { photoArray = null; using (var inputStream = new SKManagedStream(input)) using (var codec = SKCodec.Create(inputStream)) using (var original = SKBitmap.Decode(codec)) { // ЧИТАЕМ EXIF-ИНФОРМАЦИЮ input.Position = 0; try { using (ExifReader reader = new ExifReader(input)) { reader.GetTagValue(ExifTags.DateTime, out photoDateTime); reader.GetTagValue(ExifTags.BodySerialNumber, out cameraSerialNumber); } } catch (Exception exc) { } // НОРМАЛИЗУЕМ ИЗОБРАЖЕНИE ПО ВРАЩЕНИЮ SKBitmap normalized = AdjustOrientation(original, codec.EncodedOrigin); double scaleFactor = 2; // ПОЛУЧАЕМ ДЕТЕКТИРУЕМОЕ НА ЛИЦА ИЗОБРАЖЕНИЕ using (var scanned = normalized.Resize(new SKImageInfo((int)Math.Round((double)normalized.Width / scaleFactor), (int)Math.Round((double)normalized.Height / scaleFactor)), SKFilterQuality.High)) { if (scanned == null) { return; } int additionalFacesCounter = 0; List <FaceLocation> faceLocationList = new List <FaceLocation>(); using (var fd = Dlib.GetFrontalFaceDetector()) { DlibDotNet.Rectangle[] faces = null; using (var array2D = Dlib.LoadImageData <RgbPixel>(ImagePixelFormat.Rgba, scanned.Bytes, (uint)scanned.Height, (uint)scanned.Width, (uint)(scanned.Bytes.Length / scanned.Height))) faces = fd.Operator(array2D); if (faces != null && faces.Length > 0) { for (int f = 0; f < faces.Length; f++) { #region обрезаем лицо до квадрата Point center = faces[f].Center; int radius = 0; if (faces[f].Width < faces[f].Height) { radius = (int)faces[f].Width / 2; } else { radius = (int)faces[f].Height / 2; } faces[f].Left = center.X - radius; faces[f].Right = center.X + radius; faces[f].Top = center.Y - radius; faces[f].Bottom = center.Y + radius; #endregion обрезаем лицо до квадрата FaceLocation faceLocation = CalculateNormalFaceLocation(faces[f], normalized.Width, normalized.Height, scaleFactor, faceClippingRatio); faceLocationList.Add(faceLocation); } } if (additionalRotateAngles != null && additionalRotateAngles.Length > 0) { for (int r = 0; r < additionalRotateAngles.Length; r++) { if (additionalRotateAngles[r] != 0) { DlibDotNet.Rectangle[] addFaces = null; SKBitmap rotatedScanned = Rotate(scanned, additionalRotateAngles[r]); using (var array2D = Dlib.LoadImageData <RgbPixel>(ImagePixelFormat.Rgba, rotatedScanned.Bytes, (uint)rotatedScanned.Height, (uint)rotatedScanned.Width, (uint)(rotatedScanned.Bytes.Length / rotatedScanned.Height))) addFaces = fd.Operator(array2D); if (addFaces != null && addFaces.Length > 0) { for (int i = 0; i < addFaces.Length; i++) { #region обрезаем лицо до квадрата Point center = addFaces[i].Center; int radius = 0; if (addFaces[i].Width < addFaces[i].Height) { radius = (int)addFaces[i].Width / 2; } else { radius = (int)addFaces[i].Height / 2; } addFaces[i].Left = center.X - radius; addFaces[i].Right = center.X + radius; addFaces[i].Top = center.Y - radius; addFaces[i].Bottom = center.Y + radius; #endregion обрезаем лицо до квадрата FaceLocation faceLocation = CalculateRotatedFaceLocation((double)rotatedScanned.Width / 2, (double)rotatedScanned.Height / 2, addFaces[i], -additionalRotateAngles[r], normalized.Width, normalized.Height, scaleFactor, faceClippingRatio); additionalFacesCounter++; faceLocationList.Add(faceLocation); } } } } } } if (faceLocationList.Count > 0) { List <FaceLocation> correlatedFaceList = GetCorrelatedFaceList(faceLocationList, additionalFacesCounter); // пропускаем через коррелятор лиц для избавления от дублей и уменьшения бокового наклона if (correlatedFaceList != null && correlatedFaceList.Count > 0) { for (int i = 0; i < correlatedFaceList.Count; i++) { //var cropRect = new SKRectI { Left = correlatedFaceList[i].Left, Top = correlatedFaceList[i].Top, Right = correlatedFaceList[i].Right, Bottom = correlatedFaceList[i].Bottom }; var cropRect = new SKRectI(); int w = correlatedFaceList[i].Right - correlatedFaceList[i].Left; int h = correlatedFaceList[i].Bottom - correlatedFaceList[i].Top; int centerX = correlatedFaceList[i].Left + w / 2; int centerY = correlatedFaceList[i].Top + h / 2; if (w > h) { cropRect.Left = centerX - h / 2; cropRect.Right = centerX + h / 2; cropRect.Top = centerY - h / 2; cropRect.Bottom = centerY + h / 2; } else if (w < h) { cropRect.Left = centerX - w / 2; cropRect.Right = centerX + w / 2; cropRect.Top = centerY - w / 2; cropRect.Bottom = centerY + w / 2; } else { cropRect.Left = correlatedFaceList[i].Left; cropRect.Top = correlatedFaceList[i].Top; cropRect.Right = correlatedFaceList[i].Right; cropRect.Bottom = correlatedFaceList[i].Bottom; } var faceBitmap = new SKBitmap(cropRect.Width, cropRect.Height); normalized.ExtractSubset(faceBitmap, cropRect); //// ТЕПЕРЬ БУДЕМ ПОВОРАЧИВАТЬ SKBitmap rotated = Rotate(faceBitmap, -correlatedFaceList[i].Angle); // ТЕПЕРЬ НАКЛАДЫВАЕМ МАСКУ НА ЛИЦО В ВИДЕ КРУГА double radius = 0; if (cropRect.Width < cropRect.Height) { radius = (double)cropRect.Width / 2 * (1 + 0.5 / 2); } else { radius = (double)cropRect.Height / 2 * (1 + 0.5 / 2); } using (SKCanvas canvas = new SKCanvas(rotated)) { canvas.DrawBitmap(rotated, 0, 0); SKPaint paint = new SKPaint(); paint.Color = maskColor; paint.Style = SKPaintStyle.Stroke; paint.StrokeWidth = (float)(radius * 0.4); canvas.DrawCircle((float)rotated.Width / 2, (float)rotated.Height / 2, (float)radius, paint); canvas.Flush(); } // ВЫРЕЗАЕМ ИТОГ double x = (double)rotated.Width / 2; double y = (double)rotated.Height / 2; var finalCropRect = new SKRectI { Left = (int)(x - (double)faceBitmap.Width / 2), Top = (int)(y - (double)faceBitmap.Height / 2), Right = (int)(x + (double)faceBitmap.Width / 2), Bottom = (int)(y + (double)faceBitmap.Height / 2) }; faceBitmap.Dispose(); using (SKBitmap face = new SKBitmap(finalCropRect.Width, finalCropRect.Height)) { rotated.ExtractSubset(face, finalCropRect); try { if (face.Width > 600 * scaleFactor) { using (var scaled = face.Resize(new SKImageInfo((int)Math.Round(400 * scaleFactor), (int)Math.Round(400 * scaleFactor)), SKFilterQuality.High)) { if (scaled != null) { using (var image = SKImage.FromBitmap(scaled)) using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 90)) { if (facesByteArrays == null) { facesByteArrays = new List <byte[]>(); } facesByteArrays.Add(data.ToArray()); } } } } else { using (var image = SKImage.FromBitmap(face)) using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 90)) { if (facesByteArrays == null) { facesByteArrays = new List <byte[]>(); } facesByteArrays.Add(data.ToArray()); } } } catch (Exception exc) { }; } } normalized.Dispose(); correlatedFaceList = null; } faceLocationList = null; } } } isSuccess = true; } } catch (Exception exc) { try { isSuccess = false; if (exc.StackTrace != null && exc.StackTrace != "") { log.Debug(String.Format("SearchFaces. Exception: {0}", exc.StackTrace)); } else if (exc.Message != null && exc.Message != "") { log.Debug(String.Format("SearchFaces. Exception: {0}", exc.Message)); } } catch (Exception ex) { } } } else { log.Debug("SearchFaces. Null request."); } }