public ExportItem(string caption, SKImage thumbnail, ExportType type) { Caption = caption; using (var data = thumbnail.Encode()) using (var stream = data.AsStream()) { Thumbnail = Helpers.GetImageSource(stream); } Type = type; }
public static ImageSource GenerateBitmapPopulateImageSource(SKImage skImage) { ImageSource ImgSrc = ImageSource.FromStream(() => { SKData skData = skImage.Encode(SKEncodedImageFormat.Png, 100); Stream stream = skData.AsStream(true); return(stream); }); return(ImgSrc); }
private void ReturnMomentaryAsJpg(HttpRequest Request, HttpResponse Response) { SKImage Gauge = this.GenerateGauge(Request.Header); SKData Data = Gauge.Encode(SKEncodedImageFormat.Jpeg, 90); byte[] Binary = Data.ToArray(); Response.ContentType = "image/jpeg"; Response.Write(Binary); }
public IActionResult ValidateCode() { #region 反射SK支持的全部颜色 //List<SKColor> colors = new List<SKColor>(); //var skcolors = new SKColors(); //var type = skcolors.GetType(); //foreach (FieldInfo field in type.GetFields()) //{ // colors.Add( (SKColor)field.GetValue(skcolors)); //} #endregion //int maxcolorindex = colors.Count-1; string text = "1A3V"; var zu = text.ToList(); SKBitmap bmp = new SKBitmap(80, 30); using (SKCanvas canvas = new SKCanvas(bmp)) { //背景色 canvas.DrawColor(SKColors.White); using (SKPaint sKPaint = new SKPaint()) { sKPaint.TextSize = 16; //字体大小 sKPaint.IsAntialias = true; //开启抗锯齿 sKPaint.Typeface = SKTypeface.FromFamilyName("微软雅黑", SKTypefaceStyle.Bold); //字体 SKRect size = new SKRect(); sKPaint.MeasureText(zu[0].ToString(), ref size); //计算文字宽度以及高度 float temp = (bmp.Width / 4 - size.Size.Width) / 2; float temp1 = bmp.Height - (bmp.Height - size.Size.Height) / 2; Random random = new Random(); for (int i = 0; i < 4; i++) { sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255)); canvas.DrawText(zu[i].ToString(), temp + 20 * i, temp1, sKPaint);//画文字 } //干扰线 for (int i = 0; i < 5; i++) { sKPaint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255)); canvas.DrawLine(random.Next(0, 40), random.Next(1, 29), random.Next(41, 80), random.Next(1, 29), sKPaint); } } //页面展示图片 using (SKImage img = SKImage.FromBitmap(bmp)) { using (SKData p = img.Encode()) { return(File(p.ToArray(), "image/Png")); } } } }
private static async Task <bool> SaveSKBitmapAsync(SKBitmap sKBitmap, string fullPath) { //Save using SKImage image = SKImage.FromBitmap(sKBitmap); using SKData data = image.Encode(SKEncodedImageFormat.Png, 100); fullPath = Path.ChangeExtension(fullPath, ".png"); return(await FileUtil.TrySaveFileAsync(data.ToArray(), fullPath).ConfigureAwait(false)); }
internal ImageSource GetImageResource() { SKImage image = SKImage.FromBitmap(bitmap); // encode the image (defaults to PNG) SKData encoded = image.Encode(); System.IO.Stream stream = encoded.AsStream(); var source = Xamarin.Forms.ImageSource.FromStream(() => stream); return(source); }
/// <summary> /// Saves the specified stream. /// </summary> /// <param name="image">The image.</param> /// <param name="stream">The stream.</param> /// <param name="format">The format.</param> /// <param name="quality">The quality.</param> /// <exception cref="ArgumentOutOfRangeException">quality</exception> public static void Save(this SKImage image, Stream stream, SKEncodedImageFormat format = SKEncodedImageFormat.Png, int quality = 100) { if (quality < 1 || quality > 100) { throw new ArgumentOutOfRangeException(nameof(quality)); } using (var data = image.Encode(format, quality)) { data.SaveTo(stream); } }
/// <summary> /// Event thrown when touching the "Valider" button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <returns></returns> async Task OnValidateButtonClickedAsync(object sender, EventArgs e) { if (entryName.Text == null || entryName.Text.Equals("")) { await DisplayAlert("Erreur", "Le nom du signataire ne doit pas être vide", "OK"); return; } SKImageInfo info = new SKImageInfo(widthExport, heightExport); var surface = SKSurface.Create(info); var canvas = surface.Canvas; foreach (SKPath path in completedPathsResize) { canvas.DrawPath(path, paint); } foreach (SKPath path in inProgressPathsResize.Values) { canvas.DrawPath(path, paint); } SKImage snap = surface.Snapshot(); data = snap.Encode(); Eval.IsSigned = true; CurrentCandidate.IsSigned = true; Eval.Signatures.Add(new Signature(entryName.Text, data.ToArray())); bool answer = await DisplayAlert("Signature", "Voulez-vous effectuer une autre signature ?", "Oui", "Non"); if (!answer) { await Navigation.PopAsync(); } else { data = null; if (canvasSaved != null) { canvasSaved = null; } canvasView.InvalidateSurface(); completedPaths.Clear(); inProgressPaths.Clear(); completedPathsResize.Clear(); inProgressPathsResize.Clear(); entryName.Text = ""; } }
/// <summary> /// Converts a UIImage to a Base64 string, using minimal suppression via JPEG conversion /// <param name="image">The image being converted.</param> /// </summary> public static string SKImageToBase64(SKImage image) { if (image == null) { throw new ArgumentNullException(); } var data = image.Encode(SharedConstants.EncodingFormat, SharedConstants.EncodingQuality).ToArray(); return(Convert.ToBase64String(data)); }
public void SaveImage() { SKImage bitmapImage = SKImage.FromBitmap(myApp.myPage.secondPage.drawing.bitmap); var jpgImage = bitmapImage.Encode(SKEncodedImageFormat.Jpeg, 90); var bytes = jpgImage.ToArray(); var thisthing = Foundation.NSData.FromArray(bytes); var imageToSave = UIImage.LoadFromData(thisthing); imageToSave.SaveToPhotosAlbum((image, error) => { Console.WriteLine("Error"); }); }
public IImage ImageData() { var image = new BackgroundImage(); if (_snapShot != null) { image.Data = _snapShot.Encode(SKImageEncodeFormat.Jpeg, 100).ToArray(); image.Width = _snapShot.Width; image.Height = _snapShot.Height; } return(image); }
public ProcessImage PngToJpeg(ProcessImage source) { if (source.Type != ProcessImageType.PNG) { throw new FormatException("Process image should be Png"); } SKImage tmp = SKImage.FromBitmap(SKBitmap.Decode(source.Load)); return(new ProcessImage { Load = tmp.Encode(SKEncodedImageFormat.Jpeg, 95).ToArray(), Type = ProcessImageType.JPEG, Width = tmp.Width, Height = tmp.Height }); }
public static Image GetImageFromBitmap(SKBitmap bitmap) { Image img = new Image(); SKImage image = SKImage.FromPixels(bitmap.PeekPixels()); SKData encoded = image.Encode(); Stream stream = encoded.AsStream(); img.Source = ImageSource.FromStream(() => stream); return(img); }
private void Save(SKImage Image, string FileName) { if (!Directory.Exists("Graphs")) { Directory.CreateDirectory("Graphs"); } using (SKData Data = Image.Encode(SKEncodedImageFormat.Png, 100)) { File.WriteAllBytes(Path.Combine("Graphs", FileName), Data.ToArray()); } }
public static void SaveBitmap(SKBitmap bitmap, string filename) { // Make sure the directories exist Directory.CreateDirectory(Path.GetDirectoryName(filename)); using (SKImage image = SKImage.FromBitmap(bitmap)) using (SKData data = image.Encode(SKImageEncodeFormat.Png, 100)) using (Stream stream = File.OpenWrite(filename)) { data.SaveTo(stream); } }
public void Missisippi_Skia(int offset) { string jsonContent = File.ReadAllText(TestFile.GetInputFileFullPath(TestImages.GeoJson.States)); FeatureCollection features = JsonConvert.DeserializeObject <FeatureCollection>(jsonContent); Feature missisipiGeom = features.Features.Single(f => (string)f.Properties["NAME"] == "Mississippi"); Matrix3x2 transform = Matrix3x2.CreateTranslation(-87, -54) * Matrix3x2.CreateScale(60, 60) * Matrix3x2.CreateTranslation(offset, offset); IReadOnlyList <PointF[]> points = PolygonFactory.GetGeoJsonPoints(missisipiGeom, transform); var path = new SKPath(); foreach (PointF[] pts in points.Where(p => p.Length > 2)) { path.MoveTo(pts[0].X, pts[0].Y); for (int i = 0; i < pts.Length; i++) { path.LineTo(pts[i].X, pts[i].Y); } path.LineTo(pts[0].X, pts[0].Y); } var imageInfo = new SKImageInfo(10000, 10000); using var paint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.White, StrokeWidth = 1f, IsAntialias = true, }; using var surface = SKSurface.Create(imageInfo); SKCanvas canvas = surface.Canvas; canvas.Clear(new SKColor(0, 0, 0)); canvas.DrawPath(path, paint); string outDir = TestEnvironment.CreateOutputDirectory("Skia"); string fn = System.IO.Path.Combine(outDir, $"Missisippi_Skia_{offset}.png"); using SKImage image = surface.Snapshot(); using SKData data = image.Encode(SKEncodedImageFormat.Png, 100); using FileStream fs = File.Create(fn); data.SaveTo(fs); }
/// <summary> /// Save an image to a file /// </summary> /// <param name="image">The image to save</param> /// <param name="fileName">The path to the output file</param> /// <param name="format">The image format for encoding (default: Png)</param> /// <param name="quality">Quality level for the image; between 0 and 100 (default: 100)</param> public static void SaveToFile(this SKImage image, string fileName, SKEncodedImageFormat format = SKEncodedImageFormat.Png, int quality = 100) { // Ensure the output path exists string fullPath = Path.GetFullPath(fileName); Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); // Actually save to the file using (var stream = File.Create(fullPath)) using (var data = image.Encode(format, quality)) data.SaveTo(stream); }
public byte[] Resize( MemoryStream fileContents, int maxWidth, int maxHeight) { using SKBitmap sourceBitmap = SKBitmap.Decode(fileContents); using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(maxWidth, maxHeight), SKFilterQuality.Medium); using SKImage scaledImage = SKImage.FromBitmap(scaledBitmap); using SKData data = scaledImage.Encode(); return(data.ToArray()); }
public ImageSource GetImageSource() { if (snapshot == null) { return(null); } //var image = SkiaSharp.SKImage.FromBitmap(bitmap); var encoded = snapshot.Encode(); var stream = encoded.AsStream(); var source = ImageSource.FromStream(() => stream); return(source); }
/// <inheritdocs /> public Task RenderAsync(ITextData textData, Stream outputStream) { Debug.Assert(textData != null); Debug.Assert(outputStream != null); using (SKBitmap bitmap = GenerateBitmap(textData)) using (SKImage image = SKImage.FromBitmap(bitmap)) { image.Encode().SaveTo(outputStream); } return(Task.CompletedTask); }
public static BitmapImage bitmapImageFromSKImage(SKImage image) { using var encoded = image.Encode(); using var stream = encoded.AsStream(); BitmapImage photo = new BitmapImage(); photo.BeginInit(); photo.CacheOption = BitmapCacheOption.OnLoad; photo.StreamSource = stream; photo.EndInit(); photo.Freeze(); return(photo); }
public byte[] GetImageBytes() { if (_image != null) { var encodedData = _image.Encode(SKEncodedImageFormat.Jpeg, Quality); return(encodedData.ToArray()); } var data = SKImage.FromBitmap(_bitmap).Encode(SKEncodedImageFormat.Jpeg, Quality); return(data.ToArray()); }
public void initialize(string argument) { this.Size = new Size(500, 500); this.StartPosition = FormStartPosition.CenterScreen; this.MaximumSize = new Size(500, 500); this.MinimumSize = new Size(500, 500); try { image_info = new SKImageInfo(width, height); surface = SKSurface.Create(image_info); canvas = surface.Canvas; canvas.Clear(SKColors.White); coordinates_lines_paint = new SKPaint(); coordinates_lines_paint.Color = SKColor.Parse("#d55e00"); coordinates_lines_paint.IsAntialias = true; coordinates_lines_paint.StrokeWidth = 1; coordinates_lines_paint.Style = SKPaintStyle.Stroke; graph_paint = new SKPaint(); graph_paint.Color = SKColors.Black; graph_paint.IsAntialias = true; graph_paint.StrokeWidth = 1; graph_paint.Style = SKPaintStyle.Stroke; //points = get_points(-198, height); coordinates_lines = new SKPath(); graph = new SKPath(); points = coordinates(); graph_coordinates_lines(); graph_lines(points); canvas.DrawPath(coordinates_lines, coordinates_lines_paint); canvas.DrawPath(graph, graph_paint); image = surface.Snapshot(); data = image.Encode(SKEncodedImageFormat.Png, 500); memory_stream = new MemoryStream(data.ToArray()); bitmap = new Bitmap(memory_stream, false); this.BackgroundImage = bitmap; this.BackgroundImageLayout = ImageLayout.None; delete_data(); } catch (System.Exception error) { Console.WriteLine("" + error); } }
private async Task <byte[]> CreateMapImageAsync( int width, int height, Models.Bounds boundingBox, string mediaType, bool isTransparent, uint backgroundColor, IList <string> layerNames) { var imageInfo = new SKImageInfo( width: width, height: height, colorType: SKColorType.Rgba8888, alphaType: SKAlphaType.Premul); using var surface = SKSurface.Create(imageInfo); using var canvas = surface.Canvas; canvas.Clear(new SKColor(backgroundColor)); foreach (var layerName in layerNames) { if (this.tileSourceFabric.Contains(layerName)) { await WmsHelper.DrawLayerAsync( // TODO: ? pass required format to avoid conversions this.tileSourceFabric.Get(layerName), width, height, boundingBox, canvas, isTransparent, backgroundColor); } } using SKImage image = surface.Snapshot(); if (String.Compare(mediaType, MediaTypeNames.Image.Tiff, StringComparison.OrdinalIgnoreCase) == 0) { using var bitmap = SKBitmap.FromImage(image); // TODO: improve performance of pixels processing, maybe using unsafe/pointers var pixels = bitmap.Pixels.SelectMany(p => new byte[] { p.Red, p.Green, p.Blue, p.Alpha }).ToArray(); var tiff = ImageHelper.CreateTiffImage(pixels, image.Width, image.Height); return(tiff); } else { var imageFormat = U.ImageHelper.SKEncodedImageFormatFromMediaType(mediaType); using SKData data = image.Encode(imageFormat, 90); // TODO: ? quality parameter return(data.ToArray()); } }
// // // BEGIN IMAGE PROCESSING HELPERS // BEGIN IMAGE PROCESSING HELPERS // BEGIN IMAGE PROCESSING HELPERS // // /// <summary> /// Convenience method for converting a given SKImage to a Xamarin Image UI Component. /// </summary> /// <param name="inImg">A valid SKImage</param> /// <returns>A Xamarin.Forms.Image object based on the passed in SKImage</returns> public static Image SKImageToXamarinImage(SKImage inImg) { // yes, there should be a way to do this without the multiple back and forth to bytes. // no, it's not worth my time to try and figure it out. var data = inImg.Encode(SKEncodedImageFormat.Jpeg, 100); MemoryStream ms = new MemoryStream(); data.SaveTo(ms); var bytes = ms.ToArray(); Image outImage = new Image(); outImage.Source = ImageSource.FromStream(() => new MemoryStream(bytes)); return(outImage); }
public static byte[] CambiarTamanio(string fileContents, int maxWidth, int maxHeight) { using FileStream ms = new FileStream(fileContents, FileMode.Open); using SKBitmap sourceBitmap = SKBitmap.Decode(ms); int height = Math.Min(maxHeight, sourceBitmap.Height); int width = Math.Min(maxWidth, sourceBitmap.Width); using SKBitmap scaledBitmap = sourceBitmap.Resize(new SKImageInfo(width, height), SKFilterQuality.High); using SKImage scaledImage = SKImage.FromBitmap(scaledBitmap); using SKData data = scaledImage.Encode(); return(data.ToArray()); }
public MemoryStream SourceStream() { SKImage image = SKImage.FromBitmap(SourceImage); SKData encoded = image.Encode(); var memoryStream = new MemoryStream(); encoded.AsStream().CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); #if LOG_DEBUG SDV_Logger.LogInfo("SourceStream", $"Stream length: {memoryStream.Length}"); #endif return(memoryStream); }
public static void SaveImage(Image img, string path) { if (img == null || path == null) { return; } SKImage image = SKImage.FromBitmap(img); SKData png = image.Encode(SKEncodedImageFormat.Png, 100); using (var filestream = File.OpenWrite(path)) { png.SaveTo(filestream); } }
public static byte[] SquareImage(byte[] imgBytes) { // my passed in imgBytes are a jpg, not a bmp. //SKBitmap bmp = GlobalSingletonHelpers.SKBitmapFromBytes(imgBytes); SKBitmap bmp = buildFixedRotationSKBitmapFromBytes(imgBytes); SKImage res = SKImage.FromBitmap(CropImage(bmp)); return(res.Encode(SKEncodedImageFormat.Jpeg, 100).ToArray()); // testing //byte[] test = res.Encode(SKEncodedImageFormat.Jpeg, 100).ToArray(); //SKBitmap res3 = SKBitmapFromBytes(test2); //return test; }
public static byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height) { byte[] bytes; var text = verifyCode.ToUpper().ToList(); SKBitmap bmp = new SKBitmap(width, height); using (SKCanvas canvas = new SKCanvas(bmp)) { // 背景色 canvas.DrawColor(SKColors.White); using (SKPaint sKPaint = new SKPaint()) { sKPaint.TextSize = 18; // 字体大小 sKPaint.FakeBoldText = true; sKPaint.IsAntialias = true; // 开启抗锯齿 sKPaint.Typeface = SKTypeface.FromFamilyName("WenQuanYi Micro Hei", SKTypefaceStyle.Normal); //字体 SKRect size = new SKRect(); sKPaint.MeasureText(text[0].ToString(), ref size); // 计算文字宽度以及高度 float _x = (width - size.Width * text.Count) / 2 - size.Width; float _y = size.Height; int num = Next(0, 9); sKPaint.Color = colors[num]; // 干扰线 for (int i = 0; i < 3; i++) { canvas.DrawLine(Next(0, 40), Next(1, 29), Next(41, 80), Next(1, 29), sKPaint); } // 文字 for (int i = 0; i < text.Count; i++) { _x += size.Width + Next(0, 3); _y = size.Height + Next(5, 15); canvas.DrawText(text[i].ToString(), _x, _y, sKPaint); // 画文字 } } // 页面展示图片 using (SKImage img = SKImage.FromBitmap(bmp)) { using (SKData p = img.Encode()) { bytes = p.ToArray(); } } } return(bytes); }