private void DumpVPK(Package package, string type, string newType) { if (ExtFilterList != null && !ExtFilterList.Contains(type)) { return; } if (!package.Entries.ContainsKey(type)) { Console.WriteLine("There are no files of type \"{0}\".", type); return; } var entries = package.Entries[type]; foreach (var file in entries) { var filePath = string.Format("{0}.{1}", file.FileName, file.TypeName); if (!string.IsNullOrWhiteSpace(file.DirectoryName)) { filePath = Path.Combine(file.DirectoryName, filePath); } filePath = FixPathSlashes(filePath); if (FileFilter != null && !filePath.StartsWith(FileFilter, StringComparison.Ordinal)) { continue; } if (OutputFile != null) { if (CachedManifest && OldPakManifest.TryGetValue(filePath, out var oldCrc32) && oldCrc32 == file.CRC32) { continue; } OldPakManifest[filePath] = file.CRC32; } Console.WriteLine("\t[archive index: {0:D3}] {1}", file.ArchiveIndex, filePath); package.ReadEntry(file, out var output); if (type.EndsWith("_c", StringComparison.Ordinal) && Decompile) { using (var resource = new Resource()) { using (var memory = new MemoryStream(output)) { try { resource.Read(memory); } catch (Exception e) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("\t" + e.Message + " on resource type " + type + ", extracting as-is"); Console.ResetColor(); } DumpFile(filePath, output); break; } if (type == newType) { newType = type.Substring(0, type.Length - 2); } switch (type) { case "vxml_c": case "vcss_c": case "vjs_c": output = ((Panorama)resource.Blocks[BlockType.DATA]).Data; if (newType.StartsWith("v", StringComparison.Ordinal)) { newType = newType.Substring(1); } break; case "vpcf_c": //Wrap it around a KV3File object to get the header. output = Encoding.UTF8.GetBytes(new ValveResourceFormat.KeyValues.KV3File(((BinaryKV3)resource.Blocks[BlockType.DATA]).Data).ToString()); break; case "vsnd_c": var sound = ((Sound)resource.Blocks[BlockType.DATA]); if (sound.Type == Sound.AudioFileType.MP3) { newType = "mp3"; } else { newType = "wav"; } output = sound.GetSound(); break; case "vtex_c": newType = "png"; var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); var image = SKImage.FromBitmap(bitmap); using (var ms = new MemoryStream()) { using (var data = image.Encode(SKEncodedImageFormat.Png, 100)) { data.SaveTo(ms); } output = ms.ToArray(); } break; default: try { output = Encoding.UTF8.GetBytes(resource.Blocks[BlockType.DATA].ToString()); } catch (Exception) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.WriteLine("\tDecompiler for resource type " + type + " not implemented, extracting as-is"); Console.ResetColor(); } output = memory.ToArray(); newType = type; } break; } } } } if (OutputFile != null) { if (type != newType) { filePath = Path.ChangeExtension(filePath, newType); } DumpFile(filePath, output); } } }
public void Update() { if (!Inputs.Any()) { return; } if ((bool)Inputs.Last().Value) { var httpRequest = (HttpWebRequest)WebRequest.CreateHttp(description.QueryUrl); httpRequest.Method = "POST"; httpRequest.Accept = "application/json"; httpRequest.ContentType = "application/json"; if (!string.IsNullOrWhiteSpace(description.FToken)) { httpRequest.Headers.Add("Authorization", "Bearer " + description.FToken); } var inputs = "{"; foreach (var input in Inputs.Cast <MyPin>().SkipLast(1)) { if (input.Type == typeof(IImage)) { inputs += "\"" + input.OriginalName + "\": \"data:image/jpeg;base64,"; var skImage = Imaging.FromImage((IImage)input.Value, false); var jpg = skImage.Encode(SKEncodedImageFormat.Jpeg, 100).ToArray(); var base64 = Convert.ToBase64String(jpg); inputs += base64 + "\", "; } else if (input.Type == typeof(Spread <float>)) //vector { var v = (Spread <float>)input.Value; inputs += "\"" + input.OriginalName + "\": [" + string.Join(", ", v) + "], "; } else { inputs += "\"" + input.OriginalName + "\": " + GetValue(input.Value.ToString()) + ", "; } } inputs = inputs.TrimEnd(new char[2] { ',', ' ' }) + "}"; var data = Encoding.UTF8.GetBytes(inputs); httpRequest.GetRequestStream().Write(data, 0, data.Length); var rstream = httpRequest.GetResponse().GetResponseStream(); string modelInfo = ""; using (var reader = new StreamReader(rstream, Encoding.UTF8, true, 0x1000, leaveOpen: true)) { modelInfo = reader.ReadToEnd(); } dynamic model = JsonConvert.DeserializeObject(modelInfo); foreach (var output in Outputs.Cast <MyPin>()) { if (output.Type == typeof(string)) { output.Value = model[output.OriginalName].ToString(); } else if (output.Type == typeof(int)) { output.Value = (int)model[output.OriginalName]; } else if (output.Type == typeof(float)) { output.Value = (float)model[output.OriginalName]; } else if (output.Type == typeof(IEnumerable <RectangleF>)) //array { var rects = new List <RectangleF>(); foreach (var rect in model[output.OriginalName]) { var x = (float)rect[0]; var y = (float)rect[1]; var width = (float)rect[2] - x; var height = (float)rect[3] - y; rects.Add(new RectangleF(x, y, width, height)); } output.Value = (IEnumerable <RectangleF>)rects; } else if (output.Type == typeof(IEnumerable <float>)) { var floats = new List <float>(); foreach (var f in model[output.OriginalName]) { floats.Add((float)f); } output.Value = (IEnumerable <float>)floats; } else if (output.Type == typeof(IEnumerable <string>)) { var texts = new List <string>(); foreach (var t in model[output.OriginalName]) { texts.Add((string)t); } output.Value = (IEnumerable <string>)texts; } else if (output.Type == typeof(IImage)) { string result = model[output.OriginalName].ToString(); var base64 = result.Split(',').LastOrDefault(); var jpg = Convert.FromBase64String(base64); var skImage = SKImage.FromEncodedData(jpg); output.Value = Imaging.ToImage(skImage); } else if (output.Type == typeof(IEnumerable <IEnumerable <Vector2> >)) { var landmarks = new List <List <Vector2> >(); foreach (var lm in model[output.OriginalName]) { var points = new List <Vector2>(); foreach (var p in lm) { points.Add(new Vector2((float)p[0], (float)p[1])); } landmarks.Add(points); } output.Value = landmarks; } } } }
private async Task DrawPreview() { AddBtn.IsEnabled = false; UpBtn.IsEnabled = false; DownBtn.IsEnabled = false; DeleteBtn.IsEnabled = false; ClearBtn.IsEnabled = false; ImTheSlider.IsEnabled = false; OpenImageBtn.IsEnabled = false; SaveImageBtn.IsEnabled = false; int num = 1; int curW = 0; int curH = 0; int maxWidth = 0; int maxHeight = 0; int lineMaxHeight = 0; int imagesPerRow = Convert.ToInt32(ImTheSlider.Value); Dictionary <int, SKPoint> positions = new Dictionary <int, SKPoint>(); SKBitmap[] images = new SKBitmap[Images_LstBx.Items.Count]; for (int i = 0; i < images.Length; i++) { SKBitmap img = SKBitmap.Decode(new FileInfo((Images_LstBx.Items[i] as ListBoxItem).ContentStringFormat).Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); positions[i] = new SKPoint(curW, curH); images[i] = img; if (img.Height > lineMaxHeight) { lineMaxHeight = img.Height; } if (num % imagesPerRow == 0) { maxWidth = curW + img.Width + _MARGIN; curH += lineMaxHeight + _MARGIN; curW = 0; lineMaxHeight = 0; } else { maxHeight = curH + lineMaxHeight + _MARGIN; curW += img.Width + _MARGIN; if (curW > maxWidth) { maxWidth = curW; } } num++; } await Task.Run(() => { using var ret = new SKBitmap(maxWidth - _MARGIN, maxHeight - _MARGIN, SKColorType.Rgba8888, SKAlphaType.Unpremul); using var c = new SKCanvas(ret); for (int i = 0; i < images.Length; i++) { using (images[i]) { c.DrawBitmap(images[i], positions[i], new SKPaint { FilterQuality = SKFilterQuality.High, IsAntialias = true }); } } SKImage image = SKImage.FromBitmap(ret); 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(); Application.Current.Dispatcher.Invoke(delegate { Preview_Img.Source = photo; }); }).ContinueWith(t => { AddBtn.IsEnabled = true; UpBtn.IsEnabled = true; DownBtn.IsEnabled = true; DeleteBtn.IsEnabled = true; ClearBtn.IsEnabled = true; ImTheSlider.IsEnabled = true; OpenImageBtn.IsEnabled = true; SaveImageBtn.IsEnabled = true; }, TaskScheduler.FromCurrentSynchronizationContext()); }
private void ProcessFile(string path, Stream stream) { var resource = new Resource(); try { var sw = Stopwatch.StartNew(); resource.Read(stream); sw.Stop(); Console.WriteLine("Parsed in {0}ms", sw.ElapsedMilliseconds); string extension = Path.GetExtension(path); if (extension.EndsWith("_c", StringComparison.Ordinal)) { extension = extension.Substring(0, extension.Length - 2); } // Verify that extension matches resource type if (resource.ResourceType != ResourceType.Unknown) { var type = typeof(ResourceType).GetMember(resource.ResourceType.ToString()).First(); var attribute = "." + ((ExtensionAttribute)type.GetCustomAttributes(typeof(ExtensionAttribute), false).First()).Extension; if (attribute != extension) { throw new Exception(string.Format("Mismatched resource type and file extension. ({0} != expected {1})", attribute, extension)); } } if (CollectStats) { string id = string.Format("{0}_{1}", resource.ResourceType, resource.Version); string info = string.Empty; switch (resource.ResourceType) { case ResourceType.Texture: info = ((Texture)resource.Blocks[BlockType.DATA]).Format.ToString(); break; case ResourceType.Sound: info = ((Sound)resource.Blocks[BlockType.DATA]).Type.ToString(); break; } if (info != string.Empty) { id = string.Concat(id, "_", info); } lock (stats) { if (stats.ContainsKey(id)) { if (stats[id].Count++ < 10) { stats[id].FilePaths.Add(path); } } else { stats.Add(id, new ResourceStat(resource, info, path)); } } if (resource.EditInfo != null && resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { lock (uniqueSpecialDependancies) { foreach (var dep in ((ValveResourceFormat.Blocks.ResourceEditInfoStructs.SpecialDependencies)resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]).List) { uniqueSpecialDependancies[string.Format("{0} \"{1}\"", dep.CompilerIdentifier, dep.String)] = path; } } } } if (OutputFile != null) { byte[] data; switch (resource.ResourceType) { case ResourceType.Panorama: data = ((Panorama)resource.Blocks[BlockType.DATA]).Data; break; case ResourceType.Sound: var sound = ((Sound)resource.Blocks[BlockType.DATA]); switch (sound.Type) { case Sound.AudioFileType.MP3: extension = "mp3"; break; case Sound.AudioFileType.WAV: extension = "wav"; break; } data = sound.GetSound(); break; case ResourceType.Texture: extension = "png"; var bitmap = ((Texture)resource.Blocks[BlockType.DATA]).GenerateBitmap(); var image = SKImage.FromBitmap(bitmap); using (var ms = new MemoryStream()) { using (var imageData = image.Encode(SKEncodedImageFormat.Png, 100)) { imageData.SaveTo(ms); } data = ms.ToArray(); } break; case ResourceType.Particle: case ResourceType.Mesh: //Wrap it around a KV3File object to get the header. data = Encoding.UTF8.GetBytes(new ValveResourceFormat.KeyValues.KV3File(((BinaryKV3)resource.Blocks[BlockType.DATA]).Data).ToString()); break; //These all just use ToString() and WriteText() to do the job case ResourceType.SoundEventScript: data = Encoding.UTF8.GetBytes(resource.Blocks[BlockType.DATA].ToString()); break; default: Console.WriteLine("-- (I don't know how to dump this resource type)"); return; } var filePath = Path.ChangeExtension(path, extension); if (RecursiveSearch) { // I bet this is prone to breaking, is there a better way? filePath = filePath.Remove(0, InputFile.TrimEnd(Path.DirectorySeparatorChar).Length + 1); } else { filePath = Path.GetFileName(filePath); } DumpFile(filePath, data); } } catch (Exception e) { File.AppendAllText("exceptions.txt", string.Format("---------------\nFile: {0}\nException: {1}\n\n", path, e)); lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(e); Console.ResetColor(); } } if (CollectStats) { return; } //Console.WriteLine("\tInput Path: \"{0}\"", args[fi]); //Console.WriteLine("\tResource Name: \"{0}\"", "???"); //Console.WriteLine("\tID: {0:x16}", 0); lock (ConsoleWriterLock) { // Highlight resource type line if undetermined if (resource.ResourceType == ResourceType.Unknown) { Console.ForegroundColor = ConsoleColor.Cyan; } Console.WriteLine("\tResource Type: {0} [Version {1}] [Header Version: {2}]", resource.ResourceType, resource.Version, resource.HeaderVersion); Console.ResetColor(); } Console.WriteLine("\tFile Size: {0} bytes", resource.FileSize); Console.WriteLine(Environment.NewLine); if (resource.Blocks.ContainsKey(BlockType.RERL)) { Console.WriteLine("--- Resource External Refs: ---"); Console.WriteLine("\t{0,-16} {1,-48}", "Id:", "Resource Name:"); foreach (var res in resource.ExternalReferences.ResourceRefInfoList) { Console.WriteLine("\t{0:X16} {1,-48}", res.Id, res.Name); } } else { Console.WriteLine("--- (No External Resource References Found)"); } Console.WriteLine(Environment.NewLine); if (false) { // TODO: Resource Deferred Refs: } else { Console.WriteLine("--- (No Deferred Resource References Found)"); } Console.WriteLine(Environment.NewLine); Console.WriteLine("--- Resource Blocks: Count {0} ---", resource.Blocks.Count); foreach (var block in resource.Blocks) { Console.WriteLine("\t-- Block: {0,-4} Size: {1,-6} bytes [Offset: {2,6}]", block.Key, block.Value.Size, block.Value.Offset); } if (PrintAllBlocks || !string.IsNullOrEmpty(BlockToPrint)) { Console.WriteLine(Environment.NewLine); foreach (var block in resource.Blocks) { if (!PrintAllBlocks && BlockToPrint != block.Key.ToString()) { continue; } Console.WriteLine("--- Data for block \"{0}\" ---", block.Key); Console.WriteLine(block.Value); } } }
private static Stream ToStream(SKImage skiaImage) { return(skiaImage.Encode().AsStream()); }
public static string GetAssetJsonData(PakReader.PakReader reader, IEnumerable <FPakEntry> entriesList, bool loadImageInBox = false) { var currentFileName = Path.GetFileName(entriesList.ElementAt(0).Name.Replace(".uasset", "").Replace(".uexp", "").Replace(".ubulk", "")); DebugHelper.WriteLine("Assets: Gathering info about {0}", entriesList.ElementAt(0).Name); Stream[] AssetStreamArray = new Stream[3]; foreach (FPakEntry entry in entriesList) { switch (Path.GetExtension(entry.Name.ToLowerInvariant())) { case ".ini": /* FWindow.FMain.Dispatcher.InvokeAsync(() => * { * FWindow.FMain.AssetPropertiesBox_Main.SyntaxHighlighting = ResourceLoader.LoadHighlightingDefinition("Ini.xshd"); * });*/ using (var s = reader.GetPackageStream(entry)) using (var r = new StreamReader(s)) return(r.ReadToEnd()); case ".uproject": case ".uplugin": case ".upluginmanifest": using (var s = reader.GetPackageStream(entry)) using (var r = new StreamReader(s)) return(r.ReadToEnd()); case ".locmeta": using (var s = reader.GetPackageStream(entry)) return(JsonConvert.SerializeObject(new LocMetaFile(s), Formatting.Indented)); case ".locres": using (var s = reader.GetPackageStream(entry)) return(JsonConvert.SerializeObject(new LocResFile(s).Entries, Formatting.Indented)); case ".udic": using (var s = reader.GetPackageStream(entry)) using (var r = new BinaryReader(s)) return(JsonConvert.SerializeObject(new UDicFile(r).Header, Formatting.Indented)); case ".bin": if (string.Equals(entry.Name, "/FortniteGame/AssetRegistry.bin") || !entry.Name.Contains("AssetRegistry")) //MEMORY ISSUE { break; } using (var s = reader.GetPackageStream(entry)) return(JsonConvert.SerializeObject(new AssetRegistryFile(s), Formatting.Indented)); default: if (entry.Name.EndsWith(".uasset")) { AssetStreamArray[0] = reader.GetPackageStream(entry); } if (entry.Name.EndsWith(".uexp")) { AssetStreamArray[1] = reader.GetPackageStream(entry); } if (entry.Name.EndsWith(".ubulk")) { AssetStreamArray[2] = reader.GetPackageStream(entry); } break; } } AssetReader ar = GetAssetReader(AssetStreamArray); if (ar != null) { if (loadImageInBox) { foreach (ExportObject eo in ar.Exports) { switch (eo) { case Texture2D texture: SKImage image = texture.GetImage(); if (image != null) { using (var data = image.Encode()) using (var stream = data.AsStream()) { /* * using (Image img = ImagesUtility.GetImageSource(stream)) * { * img.Save(FProp.FOutput_Path + "\\Icons\\"+ currentFileName+".png"); * * }*/ /* FWindow.FMain.Dispatcher.InvokeAsync(() => * { * FWindow.FMain.ImageBox_Main.Source = BitmapFrame.Create((BitmapSource)img); //thread safe and fast af * * if (FWindow.FMain.MI_Auto_Save_Images.IsChecked) //auto save images * { * ImagesUtility.SaveImage(FProp.Default.FOutput_Path + "\\Icons\\" + FWindow.FCurrentAsset + ".png"); * } * });*/ } } return(JsonConvert.SerializeObject(texture.textures, Formatting.Indented)); case USoundWave sound: using (sound) { byte[] s = readSound(sound); if (s != null) { // string path = FProp.FOutput_Path + "\\Sounds\\" + FWindow.FCurrentAsset + ".ogg"; // File.WriteAllBytes(path, s); //open sound /* if (FProp.Default.FOpenSounds) * { * FoldersUtility.OpenWithDefaultProgram(path); * }*/ } GC.Collect(); GC.WaitForPendingFinalizers(); return(JsonConvert.SerializeObject(sound.base_object, Formatting.Indented)); } } } } string stringData = JsonConvert.SerializeObject(ar.Exports, Formatting.Indented); return(stringData); } return(string.Empty); }
public override bool WriteCoinToJpeg(CloudCoin cloudCoin, string TemplateFile, string OutputFile, string tag) { OutputFile = OutputFile.Replace("\\\\", "\\"); bool fileSavedSuccessfully = true; /* BUILD THE CLOUDCOIN STRING */ String cloudCoinStr = "01C34A46494600010101006000601D05"; //THUMBNAIL HEADER BYTES for (int i = 0; (i < 25); i++) { cloudCoinStr = cloudCoinStr + cloudCoin.an[i]; } // end for each an //cloudCoinStr += "204f42455920474f4420262044454645415420545952414e545320";// Hex for " OBEY GOD & DEFEAT TYRANTS " //cloudCoinStr += "20466f756e6465727320372d352d3137";// Founders 7-5-17 cloudCoinStr += "4c6976652046726565204f7220446965"; // Live Free or Die cloudCoinStr += "00000000000000000000000000"; //Set to unknown so program does not Withdraw user data // for (int i =0; i < 25; i++) { // switch () { }//end switch pown char // }//end for each pown cloudCoinStr += "00"; // HC: Has comments. 00 = No cloudCoin.CalcExpirationDate(); cloudCoinStr += cloudCoin.edHex; // 01;//Expiration date Sep 2016 (one month after zero month) cloudCoinStr += "01"; // cc.nn;//network number String hexSN = cloudCoin.sn.ToString("X6"); String fullHexSN = ""; switch (hexSN.Length) { case 1: fullHexSN = ("00000" + hexSN); break; case 2: fullHexSN = ("0000" + hexSN); break; case 3: fullHexSN = ("000" + hexSN); break; case 4: fullHexSN = ("00" + hexSN); break; case 5: fullHexSN = ("0" + hexSN); break; case 6: fullHexSN = hexSN; break; } cloudCoinStr = (cloudCoinStr + fullHexSN); /* BYTES THAT WILL GO FROM 04 to 454 (Inclusive)*/ byte[] ccArray = this.hexStringToByteArray(cloudCoinStr); /* READ JPEG TEMPLATE*/ byte[] jpegBytes = null; switch (cloudCoin.getDenomination()) { case 1: jpegBytes = readAllBytes(this.TemplateFolder + "jpeg1.jpg"); break; case 5: jpegBytes = readAllBytes(this.TemplateFolder + "jpeg5.jpg"); break; case 25: jpegBytes = readAllBytes(this.TemplateFolder + "jpeg25.jpg"); break; case 100: jpegBytes = readAllBytes(this.TemplateFolder + "jpeg100.jpg"); break; case 250: jpegBytes = readAllBytes(this.TemplateFolder + "jpeg250.jpg"); break; }// end switch /* WRITE THE SERIAL NUMBER ON THE JPEG */ //Bitmap bitmapimage; SKBitmap bitmapimage; //using (var ms = new MemoryStream(jpegBytes)) { //bitmapimage = new Bitmap(ms); bitmapimage = SKBitmap.Decode(jpegBytes); } SKCanvas canvas = new SKCanvas(bitmapimage); //Graphics graphics = Graphics.FromImage(bitmapimage); //graphics.SmoothingMode = SmoothingMode.AntiAlias; //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; SKPaint textPaint = new SKPaint() { IsAntialias = true, Color = SKColors.White, TextSize = 14, Typeface = SKTypeface.FromFamilyName("Arial") }; //PointF drawPointAddress = new PointF(30.0F, 25.0F); canvas.DrawText(String.Format("{0:N0}", cloudCoin.sn) + " of 16,777,216 on Network: 1", 30, 40, textPaint); //graphics.DrawString(String.Format("{0:N0}", cc.sn) + " of 16,777,216 on Network: 1", new Font("Arial", 10), Brushes.White, drawPointAddress); //ImageConverter converter = new ImageConverter(); //byte[] snBytes = (byte[])converter.ConvertTo(bitmapimage, typeof(byte[])); SKImage image = SKImage.FromBitmap(bitmapimage); SKData data = image.Encode(SKEncodedImageFormat.Jpeg, 100); byte[] snBytes = data.ToArray(); List <byte> b1 = new List <byte>(snBytes); List <byte> b2 = new List <byte>(ccArray); b1.InsertRange(4, b2); if (tag == "random") { Random r = new Random(); int rInt = r.Next(100000, 1000000); //for ints tag = rInt.ToString(); } string fileName = WithdrawFolder + cloudCoin.FileName + tag + ".jpg"; File.WriteAllBytes(fileName, b1.ToArray()); Console.Out.WriteLine("Writing to " + fileName); CoreLogger.Log("Writing to " + fileName); return(fileSavedSuccessfully); }
public IList <YoloBoxRectangle> Detect(byte[] image) { return(Detect(SKImage.FromEncodedData(new MemoryStream(image)))); }
ISerializableObject SKImageToRepresentationImage(SKImage image) => ImageFromSKData(image.Encode(), image.Width, image.Height);
/// <summary> /// Get snapshot as image. /// </summary> /// <returns>Image snapshot.</returns> public SKImage GetSnapshot() { lock (_lock) return(SKImage.FromPixels(_bitmap.Info, _bitmap.GetPixels(), _bitmap.RowBytes)); }
private static unsafe void DrawWaves(ThumbnailsRenderContext ctx, MediaStream audioStream) { var height = 88; var width = 88; using var recorder = new SKPictureRecorder(); using var canvas = recorder.BeginRecording(SKRect.Create(width, height)); var columnCount = 88 * 2; var columnWidth = (float)width / columnCount; using var wavePaint = new SKPaint { Color = new SKColor(128, 128, 128, 76), StrokeWidth = columnWidth }; var totalSample = audioStream.SampleRate * audioStream.Duration; var columnMaxSample = (int)(totalSample / columnCount); var columns = new short[columnCount]; using var decoder = audioStream.CreateStreamDecoder(); using var filter = new AudioFormatFilter("sample_fmts=s16:channel_layouts=mono", audioStream, decoder); filter.Build(); long sum = 0; var n = 0; var c = 0; while (filter.MoveNext()) { var frame = filter.Current.Value; var p = (short *)frame->data[0]; for (var i = 0; i < frame->nb_samples; i++) { sum += SampleAbs(p[i]); n++; if (n == columnMaxSample && c < columnCount) { columns[c] = (short)(sum / n); n = 0; sum = 0; c++; } } } for (var i = 0; i < columnCount; i++) { var h = Math.Max((float)columns[i] * height / short.MaxValue, 0.5f); var x = i * columnWidth; canvas.DrawLine(x, (height - h) / 2.0f, x, (height + h) / 2.0f, wavePaint); } _cachedWaveformDecorationImage ??= SKImage.FromEncodedData(ReadWaveformDecorationImage()); canvas.DrawImage(_cachedWaveformDecorationImage, SKRect.Create((width - 28) / 2.0f, (height - 36) / 2.0f, 28, 36)); using var picture = recorder.EndRecording(); ThumbnailUtils.DrawShadowView( ctx, new SkPictureView( picture, new SKSize(88, 88))); }
public static SkiaSharp.SKImage ToSKImage(this SKImage image) { return(SkiaSharp.SKImage.FromEncodedData(image.Data)); }
public static Stream GetStreamImageFromPath(string AssetFullPath) { PakReader.PakReader reader = GetPakReader(AssetFullPath); if (reader != null) { List <FPakEntry> entriesList = GetPakEntries(AssetFullPath); Stream[] AssetStreamArray = new Stream[3]; foreach (FPakEntry entry in entriesList) { switch (Path.GetExtension(entry.Name.ToLowerInvariant())) { case ".ini": break; case ".uproject": case ".uplugin": case ".upluginmanifest": break; case ".locmeta": break; case ".locres": break; case ".udic": break; case ".bin": break; default: if (entry.Name.EndsWith(".uasset")) { AssetStreamArray[0] = reader.GetPackageStream(entry); } if (entry.Name.EndsWith(".uexp")) { AssetStreamArray[1] = reader.GetPackageStream(entry); } if (entry.Name.EndsWith(".ubulk")) { AssetStreamArray[2] = reader.GetPackageStream(entry); } break; } } AssetReader ar = GetAssetReader(AssetStreamArray); if (ar != null) { ExportObject eo = ar.Exports.FirstOrDefault(x => x is Texture2D); if (eo != null) { SKImage image = ((Texture2D)eo).GetImage(); if (image != null) { return(image.Encode().AsStream()); } } } } return(null); }
//public ImageSprite(ResourceId resourceId) //{ // var bitmap = Bitmaps.LoadBitmap(resourceId); // Image = SKImage.FromBitmap(bitmap); //} public ImageSprite(SKBitmap bitmap) { Image = SKImage.FromBitmap(bitmap); }
private byte[] CreateImage() { this.GetType().Assembly.GetManifestResourceNames(); var assembly = typeof(ReceiptPage).GetTypeInfo().Assembly; var canvasWidth = 1000; var canvasHeight = 800 + (Receipt.ItemList.Count * 170); sKCanvasView.HeightRequest = canvasHeight; sKCanvasView.WidthRequest = canvasWidth; toBitmap = new SKBitmap(canvasWidth, canvasHeight, SKColorType.Rgb565, SKAlphaType.Opaque); canvas = new SKCanvas(toBitmap); canvas.Clear(SKColors.White); canvas.ResetMatrix(); var defaultText = new SKPaint { Typeface = SKTypeface.Default, TextSize = 40.0f, IsAntialias = true, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Left }; var discountedItemPrice = new SKPaint { Typeface = SKTypeface.Default, TextSize = 40.0f, IsAntialias = true, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Right }; var smallText = new SKPaint { Typeface = SKTypeface.Default, TextSize = 30.0f, IsAntialias = true, Color = new SKColor(128, 128, 128, 255), TextAlign = SKTextAlign.Left }; var totalPricePaint = new SKPaint { Typeface = SKTypeface.Default, TextSize = 80.0f, IsAntialias = true, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Center }; var totalPaint = new SKPaint { Typeface = SKTypeface.Default, TextSize = 40.0f, IsAntialias = true, Color = new SKColor(128, 128, 128, 255), TextAlign = SKTextAlign.Center }; var originalPricePaint = new SKPaint { Typeface = SKTypeface.Default, TextSize = 30.0f, IsAntialias = true, Color = new SKColor(128, 128, 128, 255), TextAlign = SKTextAlign.Right, }; var linePaint = new SKPaint { Color = new SKColor(128, 128, 128, 255), StrokeWidth = 3, }; canvas.DrawText(Receipt.Total.ToString("#,##.00"), canvasWidth / 2, 100, totalPricePaint); canvas.DrawText("Total", canvasWidth / 2, 200, totalPaint); canvas.DrawText("Order: " + App.StoreName, 50, 300, defaultText); canvas.DrawText("Cashier: " + App.User, 50, 350, defaultText); canvas.DrawLine(new SKPoint() { X = 50, Y = 450 }, new SKPoint() { X = canvasWidth - 50, Y = 450 }, linePaint); int currentCursor = 500; foreach (var item in Receipt.ItemList) { currentCursor += 50; canvas.DrawText(item.ItemName, 50, currentCursor, defaultText); if (item.IsDiscounted) { canvas.DrawText(item.DiscountedPrice.ToString("#,0.00"), canvasWidth - 50, currentCursor, discountedItemPrice); canvas.DrawText(item.ItemPrice.ToString("#,0.00"), canvasWidth - 300, currentCursor, originalPricePaint); } else { canvas.DrawText(item.ItemPrice.ToString("#,0.00"), canvasWidth - 50, currentCursor, discountedItemPrice); } currentCursor += 40; canvas.DrawText(" x " + item.Quantity, 50, currentCursor, smallText); currentCursor += 40; canvas.DrawText($"+ {item.OptionName} ({item.OptionPrice.ToString("#,0.00")})", 50, currentCursor, smallText); currentCursor += 40; if (item.IsDiscounted) { if (item.IsDiscountPercentage) { canvas.DrawText($"Discount {item.ItemDiscount.ToString()}%", 50, currentCursor, smallText); } else { canvas.DrawText($"Discount {item.ItemDiscount.ToString("#,0.00")}", 50, currentCursor, smallText); } currentCursor += 40; } } if (Receipt.Discount > 0) { currentCursor += 60; canvas.DrawLine(new SKPoint() { X = 50, Y = currentCursor }, new SKPoint() { X = canvasWidth - 50, Y = currentCursor }, linePaint); currentCursor += 50; canvas.DrawText("Discount ", 50, currentCursor, defaultText); canvas.DrawText(Receipt.Discount.ToString("#,##.00"), canvasWidth - 50, currentCursor, discountedItemPrice); } currentCursor += 60; canvas.DrawLine(new SKPoint() { X = 50, Y = currentCursor }, new SKPoint() { X = canvasWidth - 50, Y = currentCursor }, linePaint); currentCursor += 50; canvas.DrawText("Total", 50, currentCursor, defaultText); canvas.DrawText(Receipt.Total.ToString("#,##.00"), canvasWidth - 50, currentCursor, discountedItemPrice); canvas.Flush(); var image = SKImage.FromBitmap(toBitmap); var data = image.Encode(SKEncodedImageFormat.Png, 90); return(data.ToArray()); }
public ImageSprite(SKImage image) { Image = image; }
private SKData GetImageData(string imagePath, ResizeParams resizeParams, DateTime lastWriteTimeUtc) { // check cache and return if cached long cacheKey; unchecked { cacheKey = imagePath.GetHashCode() + lastWriteTimeUtc.ToBinary() + resizeParams.ToString().GetHashCode(); } SKData imageData; byte[] imageBytes; bool isCached = _memoryCache.TryGetValue <byte[]>(cacheKey, out imageBytes); if (isCached) { _logger.LogInformation("Serving from cache"); return(SKData.CreateCopy(imageBytes)); } SKCodecOrigin origin; // this represents the EXIF orientation var bitmap = LoadBitmap(File.OpenRead(imagePath), out 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 != SKCodecOrigin.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 var paddedHeight = resizeParams.h; var 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") { var bitmapRatio = (float)bitmap.Width / bitmap.Height; var 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 var resizedImageInfo = new SKImageInfo(resizeParams.w, resizeParams.h, SKImageInfo.PlatformColorType, bitmap.AlphaType); var resizedBitmap = bitmap.Resize(resizedImageInfo, SKBitmapResizeMethod.Lanczos3); // optionally pad if (resizeParams.mode == "pad") { resizedBitmap = Pad(resizedBitmap, paddedWidth, paddedHeight, resizeParams.format != "png"); } // encode var resizedImage = SKImage.FromBitmap(resizedBitmap); var encodeFormat = resizeParams.format == "png" ? SKEncodedImageFormat.Png : SKEncodedImageFormat.Jpeg; imageData = resizedImage.Encode(encodeFormat, resizeParams.quality); // cache the result _memoryCache.Set <byte[]>(cacheKey, imageData.ToArray()); // cleanup resizedImage.Dispose(); bitmap.Dispose(); resizedBitmap.Dispose(); return(imageData); }
public IList <YoloBoxRectangle> Detect(string imageFile) { var image = SKImage.FromEncodedData(new MemoryStream(File.ReadAllBytes(imageFile))); return(Detect(image)); }
public static void CreateLogoImage(string input, string output) { try { var newWidth = 540; var newHeight = 540; using (var bitmap = SKBitmap.Decode(input)) { if (bitmap != null) { if (bitmap.Width < bitmap.Height) { newWidth = (int)((double)bitmap.Width / (double)bitmap.Height * 540); } if (bitmap.Height < bitmap.Width) { newHeight = (int)((double)bitmap.Height / (double)bitmap.Width * 540); } using (var scaledBitmap = bitmap.Resize(new SKImageInfo(newWidth, newHeight), SKBitmapResizeMethod.Lanczos3)) { if (scaledBitmap != null) { var toBitmap = new SKBitmap(540, 540); var canvas = new SKCanvas(toBitmap); var paint = new SKPaint() { Style = SKPaintStyle.Stroke, Color = SKColors.DimGray, StrokeWidth = 1, }; var x = (540 - scaledBitmap.Width) / 2; var y = (540 - scaledBitmap.Height) / 2; canvas.DrawBitmap(scaledBitmap, x, y); canvas.DrawRect(SKRect.Create(2, 2, 535, 535), paint); canvas.Flush(); using (var image = SKImage.FromBitmap(toBitmap)) { using (var png = image.Encode(SKEncodedImageFormat.Png, 100)) { using (var filestream = File.OpenWrite(output)) { png.SaveTo(filestream); } } } } } } } } catch { Plugin.Logger.Info("IMAGEHELPER > Could not create Logo Image: {0}", output); } }
public void DrawImage(SKImage image, Position position, Size size) => DrawImageFunc(image, position, size);
public static void SaveTo(this SKBitmap me, string filename) { using var fs = File.Create(filename); SKImage.FromBitmap(me).Encode().SaveTo(fs); }