Esempio n. 1
0
        private async Task <Stream> GetQueryResultImage()
        {
            Stopwatch watchDraw = new Stopwatch();

            watchDraw.Start();

            // todo make dynamic
            int width  = Width;
            int height = 10000;

            SKBitmap bitmap = new SKBitmap(width, height); // TODO insert into constructor
            SKCanvas canvas = new SKCanvas(bitmap);

            canvas.Clear(DrawingHelper.DiscordBackgroundColor);

            int padding = 20;

            int xSize = width - padding * 2;

            if (Header.Count == 0)
            {
                // TODO draw no results on image
                //await Context.Channel.SendMessageAsync("No results", false, null, null, null, new Discord.MessageReference(Context.Message.Id));
                return(null);
            }

            int cellWidth = xSize / Header.Count;

            int currentHeight = padding;

            List <int> widths = DefineTableCellWidths(cellWidth, DrawingHelper.TitleTextPaint, DrawingHelper.DefaultTextPaint);

            string cellWithInfo = "normal" + cellWidth + " " + string.Join(", ", widths);

            //await Context.Channel.SendMessageAsync(cellWithInfo, false, null, null, null, new Discord.MessageReference(Context.Message.Id));
            currentHeight = DrawRow(canvas, Header, -1, padding, currentHeight + 10, widths, true);


            int failedDrawLineCount = 0;
            int rowId = 0;

            foreach (var row in Data)
            {
                try
                {
                    canvas.DrawLine(padding, currentHeight - 13, Math.Max(width - padding, 0), currentHeight - 13, DrawingHelper.DefaultDrawing);
                }
                catch (Exception ex)
                {
                    failedDrawLineCount++;
                }
                try
                {
                    currentHeight  = DrawRow(canvas, row, rowId, padding, currentHeight, widths);
                    currentHeight += 5;
                }
                catch (Exception ex)
                {
                    // TODO send exception
                    //Context.Channel.SendMessageAsync(ex.ToString());
                    break;
                }

                rowId++;
            }

            try
            {
                canvas.DrawLine(padding, currentHeight - 13, Math.Max(width - padding, 0), currentHeight - 13, DrawingHelper.DefaultDrawing);
            }
            catch (Exception ex)
            {
                failedDrawLineCount++;
            }

            if (failedDrawLineCount > 0)
            {
                //Context.Channel.SendMessageAsync($"Failed to draw {failedDrawLineCount} lines, widths: {string.Join(",", widths)}");
            }

            int currentWidth = padding;

            foreach (var curWidth in widths)
            {
                canvas.DrawLine(currentWidth, padding - 5, currentWidth, currentHeight - 13, DrawingHelper.DefaultDrawing);
                currentWidth += curWidth;
            }

            canvas.DrawLine(currentWidth, padding - 5, currentWidth, currentHeight - 13, DrawingHelper.DefaultDrawing);

            watchDraw.Stop();
            //
            canvas.DrawText($"{AdditionalString} DrawTime: {watchDraw.ElapsedMilliseconds.ToString("N0")}ms",
                            new SKPoint(padding, currentHeight + padding),
                            DrawingHelper.TitleTextPaint); // TODO Different color for text

            //List<int> rowHeight = new List<int>();
            //Rectangle DestinationRectangle = new Rectangle(10, 10, cellWidth, 500);

            //var size = Graphics.MeasureCharacterRanges("", drawFont2, DestinationRectangle, null);
            //Graphics.DrawString($"{(int)((maxValue / yNum) * i)}", drawFont2, b, new Point(40, 10 + ySize - (ySize / yNum) * i));

            bitmap = DrawingHelper.CropImage(bitmap, new SKRect(0, 0, Width, currentHeight + padding * 3));

            var stream = CommonHelper.GetStream(bitmap);

            bitmap.Dispose();
            canvas.Dispose();
            return(stream);
        }
        //private int GetNextIndex()
        //{
        //    var nextIndex = currentIndex + 1;
        //    if (nextIndex > Location.LocationPages.Count - 1) nextIndex = 0;
        //    return nextIndex;
        //}

        private void UpdateOffScreenElements()
        {
            offscreenHeading.Text = viewModel.NextLocation.Title;
            offscreenBody.Text    = viewModel.NextLocation.Description;
            offscreenBitmap       = BitmapExtensions.LoadBitmapResource(this.GetType(), viewModel.NextLocation.ImageResource);
        }
Esempio n. 3
0
 public void SaveImage(SKBitmap image, Stream stream)
 {
     image.Encode(stream, SKEncodedImageFormat.Webp, Quality);
 }
Esempio n. 4
0
 public override Stream Resize(Stream stream, int newWidth, int newHeight)
 {
     using var img = SKBitmap.Decode(stream);
     return(ResizeToPng(img, newWidth, newHeight));
 }
Esempio n. 5
0
        /// <summary>
        /// i don't cache images because i don't wanna store a lot of SKCanvas in the memory
        /// </summary>
        /// <returns>true if an icon has been drawn</returns>
        public static bool TryDrawIcon(string assetPath, FName[] exportTypes, IUExport[] exports)
        {
            var    d           = new DirectoryInfo(assetPath);
            string assetName   = d.Name;
            string assetFolder = d.Parent.Name;

            if (Text.TypeFaces.NeedReload(false))
            {
                Text.TypeFaces = new Typefaces(); // when opening bundle creator settings without loading paks first
            }
            int index;
            {
                if (Globals.Game.ActualGame == EGame.Valorant || Globals.Game.ActualGame == EGame.Spellbreak)
                {
                    index = 1;
                }
                else
                {
                    index = 0;
                }
            }
            string exportType;

            {
                if (exportTypes.Length > index && exportTypes[index].String == "BlueprintGeneratedClass")
                {
                    index++;
                }

                exportType = exportTypes.Length > index ? exportTypes[index].String : string.Empty;
            }

            switch (exportType)
            {
            case "AthenaConsumableEmoteItemDefinition":
            case "AthenaSkyDiveContrailItemDefinition":
            case "AthenaLoadingScreenItemDefinition":
            case "AthenaVictoryPoseItemDefinition":
            case "AthenaPetCarrierItemDefinition":
            case "AthenaMusicPackItemDefinition":
            case "AthenaBattleBusItemDefinition":
            case "AthenaCharacterItemDefinition":
            case "FortAlterationItemDefinition":
            case "AthenaBackpackItemDefinition":
            case "AthenaPickaxeItemDefinition":
            case "AthenaGadgetItemDefinition":
            case "AthenaGliderItemDefinition":
            case "AthenaDailyQuestDefinition":
            case "FortBackpackItemDefinition":
            case "AthenaSprayItemDefinition":
            case "AthenaDanceItemDefinition":
            case "AthenaEmojiItemDefinition":
            case "AthenaItemWrapDefinition":
            case "AthenaToyItemDefinition":
            case "FortHeroType":
            case "FortTokenType":
            case "FortAbilityKit":
            case "FortWorkerType":
            case "RewardGraphToken":
            case "FortBannerTokenType":
            case "FortVariantTokenType":
            case "FortDecoItemDefinition":
            case "FortFeatItemDefinition":
            case "FortStatItemDefinition":
            case "FortTrapItemDefinition":
            case "FortAmmoItemDefinition":
            case "FortQuestItemDefinition":
            case "FortBadgeItemDefinition":
            case "FortAwardItemDefinition":
            case "FortGadgetItemDefinition":
            case "FortPlaysetItemDefinition":
            case "FortGiftBoxItemDefinition":
            case "FortSpyTechItemDefinition":
            case "FortOutpostItemDefinition":
            case "FortAccoladeItemDefinition":
            case "FortCardPackItemDefinition":
            case "FortDefenderItemDefinition":
            case "FortCurrencyItemDefinition":
            case "FortResourceItemDefinition":
            case "FortCodeTokenItemDefinition":
            case "FortSchematicItemDefinition":
            case "FortExpeditionItemDefinition":
            case "FortIngredientItemDefinition":
            case "FortAccountBuffItemDefinition":
            case "FortWeaponMeleeItemDefinition":
            case "FortContextTrapItemDefinition":
            case "FortPlayerPerksItemDefinition":
            case "FortPlaysetPropItemDefinition":
            case "FortHomebaseNodeItemDefinition":
            case "FortWeaponRangedItemDefinition":
            case "FortNeverPersistItemDefinition":
            case "RadioContentSourceItemDefinition":
            case "FortPlaysetGrenadeItemDefinition":
            case "FortPersonalVehicleItemDefinition":
            case "FortGameplayModifierItemDefinition":
            case "FortHardcoreModifierItemDefinition":
            case "FortConsumableAccountItemDefinition":
            case "FortConversionControlItemDefinition":
            case "FortAccountBuffCreditItemDefinition":
            case "FortPersistentResourceItemDefinition":
            case "FortHomebaseBannerIconItemDefinition":
            case "FortCampaignHeroLoadoutItemDefinition":
            case "FortConditionalResourceItemDefinition":
            case "FortChallengeBundleScheduleDefinition":
            case "FortWeaponMeleeDualWieldItemDefinition":
            case "FortDailyRewardScheduleTokenDefinition":
            case "FortCreativeRealEstatePlotItemDefinition":
            {
                BaseIcon icon   = new BaseIcon(exports[index], exportType, ref assetName);
                int      height = icon.Size + icon.AdditionalSize;
                using (var ret = new SKBitmap(icon.Size, height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            Rarity.DrawRarity(c, icon);
                        }

                        LargeSmallImage.DrawPreviewImage(c, icon);

                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoText)
                            {
                                Text.DrawBackground(c, icon);
                                Text.DrawDisplayName(c, icon);
                                Text.DrawDescription(c, icon);
                                if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.Mini)
                                {
                                    if (!icon.ShortDescription.Equals(icon.DisplayName) &&
                                        !icon.ShortDescription.Equals(icon.Description))
                                    {
                                        Text.DrawToBottom(c, icon, ETextSide.Left, icon.ShortDescription);
                                    }
                                    Text.DrawToBottom(c, icon, ETextSide.Right, icon.CosmeticSource);
                                }
                            }

                            UserFacingFlag.DrawUserFacingFlags(c, icon);

                            // has more things to show
                            if (height > icon.Size)
                            {
                                Statistics.DrawStats(c, icon);
                            }
                        }

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "FortPlaylistAthena":
            {
                BasePlaylist icon = new BasePlaylist(exports[index]);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            Rarity.DrawRarity(c, icon);
                        }

                        LargeSmallImage.DrawNotStretchedPreviewImage(c, icon);

                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoText)
                            {
                                Text.DrawBackground(c, icon);
                                Text.DrawDisplayName(c, icon);
                                Text.DrawDescription(c, icon);
                            }
                        }

                        // Watermark.DrawWatermark(c); // boi why would you watermark something you don't own ¯\_(ツ)_/¯
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "AthenaSeasonItemDefinition":
            {
                BaseSeason icon = new BaseSeason(exports[index], assetFolder);
                using (var ret = new SKBitmap(icon.Width, icon.HeaderHeight + icon.AdditionalSize,
                                              SKColorType.Rgba8888, SKAlphaType.Opaque))
                    using (var c = new SKCanvas(ret))
                    {
                        icon.Draw(c);

                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "FortMtxOfferData":
            {
                BaseOffer icon = new BaseOffer(exports[index]);
                using (var ret = new SKBitmap(icon.Size, icon.Size, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            icon.DrawBackground(c);
                        }

                        icon.DrawImage(c);

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "MaterialInstanceConstant":
            {
                if (assetFolder.Equals("MI_OfferImages"))
                {
                    BaseOfferMaterial icon = new BaseOfferMaterial(exports[index]);
                    using (var ret = new SKBitmap(icon.Size, icon.Size, SKColorType.Rgba8888, SKAlphaType.Premul))
                        using (var c = new SKCanvas(ret))
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                            {
                                icon.DrawBackground(c);
                            }

                            icon.DrawImage(c);

                            Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                            ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                        }

                    return(true);
                }

                return(false);
            }

            case "FortItemSeriesDefinition":
            {
                BaseIcon icon = new BaseIcon();
                using (var ret = new SKBitmap(icon.Size, icon.Size, SKColorType.Rgba8888, SKAlphaType.Opaque))
                    using (var c = new SKCanvas(ret))
                    {
                        Serie.GetRarity(icon, exports[index]);
                        Rarity.DrawRarity(c, icon);

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "PlaylistUserOptionEnum":
            case "PlaylistUserOptionBool":
            case "PlaylistUserOptionString":
            case "PlaylistUserOptionIntEnum":
            case "PlaylistUserOptionIntRange":
            case "PlaylistUserOptionColorEnum":
            case "PlaylistUserOptionFloatEnum":
            case "PlaylistUserOptionFloatRange":
            case "PlaylistUserOptionPrimaryAsset":
            case "PlaylistUserOptionCollisionProfileEnum":
            {
                BaseUserOption icon = new BaseUserOption(exports[index]);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Opaque))
                    using (var c = new SKCanvas(ret))
                    {
                        icon.Draw(c);

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "FortChallengeBundleItemDefinition":
            {
                BaseBundle icon = new BaseBundle(exports[index], assetFolder);
                using (var ret = new SKBitmap(icon.Width, icon.HeaderHeight + icon.AdditionalSize,
                                              SKColorType.Rgba8888, SKAlphaType.Opaque))
                    using (var c = new SKCanvas(ret))
                    {
                        HeaderStyle.DrawHeaderPaint(c, icon);
                        HeaderStyle.DrawHeaderText(c, icon);
                        QuestStyle.DrawQuests(c, icon);
                        QuestStyle.DrawCompletionRewards(c, icon);

                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "FortItemAccessTokenType":
            {
                BaseItemAccess icon = new BaseItemAccess(exports[index]);
                using (var ret = new SKBitmap(icon.Size, icon.Size, SKColorType.Rgba8888, SKAlphaType.Opaque))
                    using (var c = new SKCanvas(ret))
                    {
                        icon.Draw(c);

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "MapUIData":
            {
                BaseMapUIData icon = new BaseMapUIData(exports[index]);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        icon.Draw(c);
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "ArmorUIData":
            case "SprayUIData":
            case "ThemeUIData":
            case "ContractUIData":
            case "CurrencyUIData":
            case "GameModeUIData":
            case "CharacterUIData":
            case "SprayLevelUIData":
            case "EquippableUIData":
            case "PlayerCardUIData":
            case "Gun_UIData_Base_C":
            case "CharacterRoleUIData":
            case "EquippableSkinUIData":
            case "EquippableCharmUIData":
            case "EquippableSkinLevelUIData":
            case "EquippableSkinChromaUIData":
            case "EquippableCharmLevelUIData":
            {
                BaseUIData icon = new BaseUIData(exports, index);
                using (var ret = new SKBitmap(icon.Width + icon.AdditionalWidth, icon.Height, SKColorType.Rgba8888,
                                              SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        icon.Draw(c);

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            //case "StreamedVideoDataAsset": // must find a way to automatically gets the right version in the url
            //    {
            //        if (Globals.Game.ActualGame == EGame.Valorant && exports[index].GetExport<StructProperty>("Uuid") is StructProperty s && s.Value is FGuid uuid)
            //        {
            //            Process.Start(new ProcessStartInfo
            //            {
            //                FileName = string.Format(
            //                    "http://valorant.dyn.riotcdn.net/x/videos/release-01.05/{0}_default_universal.mp4",
            //                    $"{uuid.A:x8}-{uuid.B >> 16:x4}-{uuid.B & 0xFFFF:x4}-{uuid.C >> 16:x4}-{uuid.C & 0xFFFF:x4}{uuid.D:x8}"),
            //                UseShellExecute = true
            //            });
            //        }
            //        return false;
            //    }
            case "GQuest":
            case "GAccolade":
            case "GCosmeticSkin":
            case "GCharacterPerk":
            case "GCosmeticTitle":
            case "GCosmeticBadge":
            case "GCosmeticEmote":
            case "GCosmeticTriumph":
            case "GCosmeticRunTrail":
            case "GCosmeticArtifact":
            case "GCosmeticDropTrail":
            {
                BaseGCosmetic icon = new BaseGCosmetic(exports[index], exportType);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign == EIconDesign.Flat)
                        {
                            icon.Draw(c);
                        }
                        else if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            Rarity.DrawRarity(c, icon);
                        }

                        LargeSmallImage.DrawPreviewImage(c, icon);

                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground &&
                            (EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoText)
                        {
                            Text.DrawBackground(c, icon);
                            Text.DrawDisplayName(c, icon);
                            Text.DrawDescription(c, icon);
                        }

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            case "GCosmeticCard":
            {
                BaseGCosmetic icon = new BaseGCosmetic(exports[index], exportType);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign == EIconDesign.Flat)
                        {
                            icon.Draw(c);
                        }
                        else
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                            {
                                Rarity.DrawRarity(c, icon);
                            }
                        }

                        LargeSmallImage.DrawPreviewImage(c, icon);

                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoText)
                            {
                                Text.DrawBackground(c, icon);
                                Text.DrawDisplayName(c, icon);
                                Text.DrawDescription(c, icon);
                            }
                        }

                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }

            // Battle Breakers
            case "WExpGenericAccountItemDefinition":
            {
                BaseBBDefinition icon = new BaseBBDefinition(exports[index], exportType);
                using (var ret = new SKBitmap(icon.Width, icon.Height, SKColorType.Rgba8888, SKAlphaType.Premul))
                    using (var c = new SKCanvas(ret))
                    {
                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            if (icon.RarityBackgroundImage != null)
                            {
                                c.DrawBitmap(icon.RarityBackgroundImage, new SKRect(icon.Margin, icon.Margin, icon.Width - icon.Margin, icon.Height - icon.Margin),
                                             new SKPaint {
                                        FilterQuality = SKFilterQuality.High, IsAntialias = true
                                    });
                            }
                            else
                            {
                                Rarity.DrawRarity(c, icon);
                            }
                        }

                        LargeSmallImage.DrawPreviewImage(c, icon);

                        if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoBackground)
                        {
                            if ((EIconDesign)Properties.Settings.Default.AssetsIconDesign != EIconDesign.NoText)
                            {
                                Text.DrawBackground(c, icon);
                                Text.DrawDisplayName(c, icon);
                                Text.DrawDescription(c, icon);
                            }
                        }

                        Watermark.DrawWatermark(c); // watermark should only be applied on icons with width = 512
                        ImageBoxVm.imageBoxViewModel.Set(ret, assetName);
                    }

                return(true);
            }
            }

            return(false);
        }
Esempio n. 6
0
 public Bitmap(Stream stream)
 {
     nativeSkBitmap = SKBitmap.Decode(stream);
 }
Esempio n. 7
0
 public Bitmap(string filename)
 {
     using (var f = File.OpenRead(filename))
         nativeSkBitmap = SKBitmap.Decode(f);
 }
Esempio n. 8
0
 public FieldFrameGenerator(int width, int height)
 {
     Field  = new Field(width, height);
     Bitmap = new SKBitmap(width, height);
     Canvas = new SKCanvas(Bitmap);
 }
Esempio n. 9
0
 static void save(SKBitmap image, string file)
 {
     using var stream = File.OpenWrite(file);
     image.Encode(stream, SKEncodedImageFormat.Png, 9);
 }
Esempio n. 10
0
 public SkiaImage(SKBitmap image)
 {
     _image = image;
 }
Esempio n. 11
0
 public FieldFrameGenerator(Field field)
 {
     Field  = field;
     Bitmap = new SKBitmap((int)field.Width, (int)field.Height);
     Canvas = new SKCanvas(Bitmap);
 }
Esempio n. 12
0
 public void Dispose()
 {
     bmp?.Dispose();
     bmp = null;
 }
Esempio n. 13
0
        /// <inheritdoc/>
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (inputPath.Length == 0)
            {
                throw new ArgumentException("String can't be empty.", nameof(inputPath));
            }

            if (outputPath.Length == 0)
            {
                throw new ArgumentException("String can't be empty.", nameof(outputPath));
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new InvalidDataException($"Skia unable to read image {inputPath}");
                }

                var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);

                if (!options.CropWhiteSpace &&
                    options.HasDefaultOptions(inputPath, originalImageSize) &&
                    !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = newImageSize.Width;
                var height = newImageSize.Height;

                using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                        using (var outputStream = new SKFileWStream(outputPath))
                            using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
                            {
                                pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                return(outputPath);
                            }
                    }

                    // create bitmap to use for canvas drawing used to draw into bitmap
                    using (var saveBitmap = new SKBitmap(width, height)) // , bitmap.ColorType, bitmap.AlphaType))
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                // create image from resized bitmap to apply blur
                                using (var paint = new SKPaint())
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                if (!double.TryParse(options.ForegroundLayer, out double opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
                                {
                                    pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                }
                            }
                        }
                }
            }

            return(outputPath);
        }
Esempio n. 14
0
        private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
        {
            switch (origin)
            {
            case SKEncodedOrigin.TopRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.BottomRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = (float)bitmap.Width / 2;
                    float py = (float)bitmap.Height / 2;

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.BottomLeft:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = (float)bitmap.Width / 2;

                    float py = (float)bitmap.Height / 2;

                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.LeftTop:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(rotated.Width, 0);

                        surface.RotateDegrees(90);

                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKEncodedOrigin.RightTop:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.RotateDegrees(90);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.RightBottom:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(0, rotated.Height);
                        surface.RotateDegrees(270);
                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKEncodedOrigin.LeftBottom:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(0, rotated.Height);
                    surface.RotateDegrees(270);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            default: return(bitmap);
            }
        }
Esempio n. 15
0
 public Bitmap(int width, int height, int stride, PixelFormat bgra8888 = (Drawing.PixelFormat.Format32bppArgb),
               IntPtr data = default(IntPtr))
 {
     nativeSkBitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Bgra8888));
     nativeSkBitmap.SetPixels(data);
 }
Esempio n. 16
0
        public async Task <DataResolverResult> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            ImageSource source = parameters.Source;

            if (!string.IsNullOrWhiteSpace(parameters.LoadingPlaceholderPath) && parameters.LoadingPlaceholderPath == identifier)
            {
                source = parameters.LoadingPlaceholderSource;
            }
            else if (!string.IsNullOrWhiteSpace(parameters.ErrorPlaceholderPath) && parameters.ErrorPlaceholderPath == identifier)
            {
                source = parameters.ErrorPlaceholderSource;
            }

            var resolvedData = await(Configuration.DataResolverFactory ?? new DataResolverFactory())
                               .GetResolver(identifier, source, parameters, Configuration)
                               .Resolve(identifier, parameters, token).ConfigureAwait(false);

            if (resolvedData?.Stream == null)
            {
                throw new FileNotFoundException(identifier);
            }

            var svg = new SKSvg()
            {
                ThrowOnUnsupportedElement = false,
            };
            SKPicture picture;

            if (ReplaceStringMap == null || ReplaceStringMap.Count == 0)
            {
                using (var svgStream = resolvedData.Stream)
                {
                    picture = svg.Load(svgStream);
                }
            }
            else
            {
                using (var svgStream = resolvedData.Stream)
                    using (var reader = new StreamReader(svgStream))
                    {
                        var inputString = await reader.ReadToEndAsync();

                        foreach (var map in ReplaceStringMap
                                 .Where(v => v.Key.StartsWith("regex:")))
                        {
                            inputString = Regex.Replace(inputString, map.Key.Substring(6), map.Value);
                        }

                        var builder = new StringBuilder(inputString);

                        foreach (var map in ReplaceStringMap
                                 .Where(v => !v.Key.StartsWith("regex:", StringComparison.OrdinalIgnoreCase)))
                        {
                            builder.Replace(map.Key, map.Value);
                        }

                        using (var svgFinalStream = new MemoryStream(Encoding.UTF8.GetBytes(builder.ToString())))
                        {
                            picture = svg.Load(svgFinalStream);
                        }
                    }
            }

            double sizeX = 0;
            double sizeY = 0;

            if (VectorWidth <= 0 && VectorHeight <= 0)
            {
                if (picture.CullRect.Width > 0)
                {
                    sizeX = picture.CullRect.Width;
                }
                else
                {
                    sizeX = 300;
                }

                if (picture.CullRect.Height > 0)
                {
                    sizeY = picture.CullRect.Height;
                }
                else
                {
                    sizeY = 300;
                }
            }
            else if (VectorWidth > 0 && VectorHeight > 0)
            {
                sizeX = VectorWidth;
                sizeY = VectorHeight;
            }
            else if (VectorWidth > 0)
            {
                sizeX = VectorWidth;
                sizeY = (VectorWidth / picture.CullRect.Width) * picture.CullRect.Height;
            }
            else
            {
                sizeX = (VectorHeight / picture.CullRect.Height) * picture.CullRect.Width;
                sizeY = VectorHeight;
            }

            if (UseDipUnits)
            {
                sizeX = sizeX.DpToPixels();
                sizeY = sizeY.DpToPixels();
            }

            lock (_encodingLock)
            {
                using (var bitmap = new SKBitmap(new SKImageInfo((int)sizeX, (int)sizeY)))
                    //using (var bitmap = new SKBitmap((int)sizeX, (int)sizeY))
                    using (var canvas = new SKCanvas(bitmap))
                        using (var paint = new SKPaint())
                        {
                            canvas.Clear(SKColors.Transparent);
                            float scaleX = (float)sizeX / picture.CullRect.Width;
                            float scaleY = (float)sizeY / picture.CullRect.Height;
                            var   matrix = SKMatrix.MakeScale(scaleX, scaleY);

                            canvas.DrawPicture(picture, ref matrix, paint);
                            canvas.Flush();

                            using (var image = SKImage.FromBitmap(bitmap))
                                //using (var data = image.Encode(SKImageEncodeFormat.Png, 100))  //TODO disabled because of https://github.com/mono/SkiaSharp/issues/285
                                using (var data = image.Encode())
                                {
                                    var stream = new MemoryStream();
                                    data.SaveTo(stream);
                                    stream.Position = 0;
                                    resolvedData.ImageInformation.SetType(ImageInformation.ImageType.SVG);
                                    return(new DataResolverResult(stream, resolvedData.LoadingResult, resolvedData.ImageInformation));
                                }
                        }
            }
        }
Esempio n. 17
0
 public Bitmap(int width, int height, SKColorType colorType = (SKColorType.Bgra8888))
 {
     nativeSkBitmap = new SKBitmap(new SKImageInfo(width, height, colorType));
     nativeSkBitmap.Erase(SKColor.Empty);
 }
Esempio n. 18
0
        private SKBitmap CropWhiteSpace(SKBitmap bitmap)
        {
            var topmost = 0;

            for (int row = 0; row < bitmap.Height; ++row)
            {
                if (IsTransparentRow(bitmap, row))
                {
                    topmost = row + 1;
                }
                else
                {
                    break;
                }
            }

            int bottommost = bitmap.Height;

            for (int row = bitmap.Height - 1; row >= 0; --row)
            {
                if (IsTransparentRow(bitmap, row))
                {
                    bottommost = row;
                }
                else
                {
                    break;
                }
            }

            int leftmost = 0, rightmost = bitmap.Width;

            for (int col = 0; col < bitmap.Width; ++col)
            {
                if (IsTransparentColumn(bitmap, col))
                {
                    leftmost = col + 1;
                }
                else
                {
                    break;
                }
            }

            for (int col = bitmap.Width - 1; col >= 0; --col)
            {
                if (IsTransparentColumn(bitmap, col))
                {
                    rightmost = col;
                }
                else
                {
                    break;
                }
            }

            var newRect = SKRectI.Create(leftmost, topmost, rightmost - leftmost, bottommost - topmost);

            using (var image = SKImage.FromBitmap(bitmap))
            {
                using (var subset = image.Subset(newRect))
                {
                    return(SKBitmap.FromImage(subset));
                }
            }
        }
Esempio n. 19
0
 public Bitmap(int clientSizeWidth, int clientSizeHeight, Graphics realDc)
 {
     nativeSkBitmap = new SKBitmap(new SKImageInfo(clientSizeWidth, clientSizeHeight, SKColorType.Bgra8888));
     nativeSkBitmap.Erase(SKColor.Empty);
     //nativeSkBitmap.SetPixels(realDc._surface.);
 }
Esempio n. 20
0
        private SKBitmap OrientImage(SKBitmap bitmap, SKCodecOrigin origin)
        {
            //var transformations = {
            //    2: { rotate: 0, flip: true},
            //    3: { rotate: 180, flip: false},
            //    4: { rotate: 180, flip: true},
            //    5: { rotate: 90, flip: true},
            //    6: { rotate: 90, flip: false},
            //    7: { rotate: 270, flip: true},
            //    8: { rotate: 270, flip: false},
            //}

            switch (origin)
            {
            case SKCodecOrigin.TopRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKCodecOrigin.BottomRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = bitmap.Width;
                    px /= 2;

                    float py = bitmap.Height;
                    py /= 2;

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKCodecOrigin.BottomLeft:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = bitmap.Width;
                    px /= 2;

                    float py = bitmap.Height;
                    py /= 2;

                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKCodecOrigin.LeftTop:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(rotated.Width, 0);

                        surface.RotateDegrees(90);

                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKCodecOrigin.RightTop:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.RotateDegrees(90);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKCodecOrigin.RightBottom:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(0, rotated.Height);
                        surface.RotateDegrees(270);
                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKCodecOrigin.LeftBottom:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(0, rotated.Height);
                    surface.RotateDegrees(270);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            default:
                return(bitmap);
            }
        }
Esempio n. 21
0
 public Bitmap(byte[] largeIconsImage, Size clientSizeHeight)
 {
     nativeSkBitmap = SKBitmap.Decode(SKData.CreateCopy(largeIconsImage)).Resize(
         new SKImageInfo(clientSizeHeight.Width, clientSizeHeight.Height),
         SKFilterQuality.High);
 }
Esempio n. 22
0
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("outputPath");
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new ArgumentOutOfRangeException(string.Format("Skia unable to read image {0}", inputPath));
                }

                //_logger.Info("Color type {0}", bitmap.Info.ColorType);

                var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);

                if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = Convert.ToInt32(Math.Round(newImageSize.Width));
                var height = Convert.ToInt32(Math.Round(newImageSize.Height));

                using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    var resizeMethod = SKBitmapResizeMethod.Lanczos3;

                    bitmap.Resize(resizedBitmap, resizeMethod);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
                        using (var outputStream = new SKFileWStream(outputPath))
                        {
                            resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            return(outputPath);
                        }
                    }

                    // create bitmap to use for canvas drawing
                    using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                    {
                        // create canvas used to draw into bitmap
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                using (var paint = new SKPaint())
                                {
                                    // create image from resized bitmap to apply blur
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                                }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                Double opacity;
                                if (!Double.TryParse(options.ForegroundLayer, out opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            }
                        }
                    }
                }
            }
            return(outputPath);
        }
Esempio n. 23
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual async Task <string> GetPictureUrl(Picture picture,
                                                         int targetSize                 = 0,
                                                         bool showDefaultPicture        = true,
                                                         string storeLocation           = null,
                                                         PictureType defaultPictureType = PictureType.Entity)
        {
            if (picture == null)
            {
                return(showDefaultPicture ? await GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation) : string.Empty);
            }

            byte[] pictureBinary = null;

            if (picture.IsNew)
            {
                if ((picture.PictureBinary?.Length ?? 0) == 0)
                {
                    pictureBinary = await LoadPictureBinary(picture);
                }
                else
                {
                    pictureBinary = picture.PictureBinary;
                }

                await DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = await UpdatePicture(picture.Id,
                                              pictureBinary,
                                              picture.MimeType,
                                              picture.SeoFilename,
                                              picture.AltAttribute,
                                              picture.TitleAttribute,
                                              false,
                                              false);
            }

            string seoFileName = picture.SeoFilename;
            string lastPart    = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}.{2}", picture.Id, seoFileName, lastPart) :
                                string.Format("{0}.{1}", picture.Id, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                if (await GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    return(GetThumbUrl(thumbFileName, storeLocation));
                }

                pictureBinary = pictureBinary ?? await LoadPictureBinary(picture);

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    mutex.WaitOne();

                    await SaveThumb(thumbFilePath, thumbFileName, pictureBinary);

                    mutex.ReleaseMutex();
                }
            }
            else
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}_{2}.{3}", picture.Id, seoFileName, targetSize, lastPart) :
                                string.Format("{0}_{1}.{2}", picture.Id, targetSize, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                if (await GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    return(GetThumbUrl(thumbFileName, storeLocation));
                }

                pictureBinary = pictureBinary ?? await LoadPictureBinary(picture);

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    mutex.WaitOne();
                    if (pictureBinary != null)
                    {
                        try
                        {
                            using (var image = SKBitmap.Decode(pictureBinary))
                            {
                                pictureBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);
                            }
                        }
                        catch { }
                    }
                    await SaveThumb(thumbFilePath, thumbFileName, pictureBinary);

                    mutex.ReleaseMutex();
                }
            }
            return(GetThumbUrl(thumbFileName, storeLocation));
        }
Esempio n. 24
0
        public override void Draw(object g)
        {
            var canvas = (SKCanvas)g;

            base.Draw(g);

            if (Flowsheet != null)
            {
                IPlotModel model = null;

                if (OwnerID != null)
                {
                    if (Flowsheet.SimulationObjects.ContainsKey(OwnerID))
                    {
                        var obj = Flowsheet.SimulationObjects[OwnerID];

                        try
                        {
                            model = (IPlotModel)(obj.GetChartModel(ModelName));
                        }
                        catch
                        {
                            PaintInstructions(canvas, "Chart model not found.");
                            return;
                        }
                    }
                    else if (OwnerID == "Dynamic Mode Integrators")
                    {
                        var obj = Flowsheet.DynamicsManager.IntegratorList.Where(x => x.Value.Description == ModelName).FirstOrDefault();

                        try
                        {
                            model = (IPlotModel)(Flowsheet.DynamicsManager.GetChartModel(obj.Key));
                        }
                        catch
                        {
                            PaintInstructions(canvas, "Chart model not found.");
                            return;
                        }
                    }
                    else
                    {
                        PaintInstructions(canvas, "Referenced object not found.");
                        return;
                    }

                    if (model != null)
                    {
                        ClipboardData = GetClipboardData((PlotModel)model);
                        try
                        {
                            using (var bmp = new SKBitmap(Width * 2, Height * 2))
                            {
                                using (var bmpcanvas = new SKCanvas(bmp))
                                {
                                    bmpcanvas.Clear(GetBackColor());
                                    bmpcanvas.Scale(2.0f);
                                    renderer.SetTarget(bmpcanvas);
                                    model.Update(true);
                                    model.Render(renderer, Width, Height);
                                    var paint = GetPaint(GetForeColor());
                                    paint.FilterQuality = SKFilterQuality.High;
                                    paint.IsAutohinted  = true;
                                    paint.IsAntialias   = true;
                                    canvas.DrawBitmap(bmp, new SKRect(X, Y, X + Width, Y + Height), paint);
                                    canvas.DrawRect(new SKRect(X, Y, X + Width, Y + Height), GetStrokePaint(GetForeColor(), 1.0f));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            PaintInstructions(canvas, "Error drawing chart: " + ex.Message.ToString());
                        }
                    }
                    else
                    {
                        PaintInstructions(canvas, "Chart model not found.");
                        return;
                    }
                }
            }
            else
            {
                PaintInstructions(canvas, "Flowsheet not defined.");
                return;
            }
        }
Esempio n. 25
0
        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);
        }
Esempio n. 26
0
 public BitMapArea(SKBitmap bitMap)
 {
     this.bitMap = bitMap;
     this.bitMapDirectorySource = DependencyService.Get <IPicturePicker>().GetImageRealPath();
 }
Esempio n. 27
0
        public IMycoDrawable SKBitmapFromImageSource(ImageSource source)
        {
            if (source is FileImageSource)
            {
                string fullPath = ((FileImageSource)source).File;

                IMycoDrawable drawable = null;

                if (!_cache.TryGetValue(fullPath, out drawable))
                {
                    SKBitmap bitmap;

                    if (System.IO.File.Exists(fullPath))
                    {
                        bitmap = SKBitmap.Decode(fullPath);
                    }
                    else
                    {
                        string fileId = System.IO.Path.GetFileNameWithoutExtension(fullPath).ToLower();

                        bool isNinePatch = false;

                        if (System.IO.Path.GetExtension(fileId) == ".9p")
                        {
                            fileId      = System.IO.Path.GetFileNameWithoutExtension(fileId).ToLower();
                            isNinePatch = true;
                        }

                        var id = Android.App.Application.Context.Resources.GetIdentifier(fileId, "drawable", Android.App.Application.Context.PackageName);

                        const int bytesPerPixel = 4;

                        BitmapFactory.Options opts = new BitmapFactory.Options {
                            InPreferredConfig = Bitmap.Config.Argb8888, InScaled = !isNinePatch
                        };

                        using (var nativeBitmap = BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, id, opts))
                        {
                            int size      = nativeBitmap.Width * nativeBitmap.Height * bytesPerPixel;
                            var pixelData = new byte[size];
                            using (var byteBuffer = Java.Nio.ByteBuffer.AllocateDirect(size))
                            {
                                nativeBitmap.CopyPixelsToBuffer(byteBuffer);
                                Marshal.Copy(byteBuffer.GetDirectBufferAddress(), pixelData, 0, size);
                            }

                            bitmap = new SKBitmap(nativeBitmap.Width, nativeBitmap.Height, SKColorType.Rgba_8888, SKAlphaType.Premul);

                            IntPtr length;

                            bitmap.LockPixels();
                            try
                            {
                                // wish there was a way to IntPtr to IntPtr copy
                                var pixels = bitmap.GetPixels(out length);
                                Marshal.Copy(pixelData, 0, pixels, size);
                            }
                            finally
                            {
                                bitmap.UnlockPixels();
                            }
                        }

                        if (bitmap != null)
                        {
                            drawable = isNinePatch ? new MycoDrawableNinePatch(bitmap) as IMycoDrawable : new MycoDrawableBitmap(bitmap) as IMycoDrawable;
                            _cache.Add(fullPath, drawable);
                        }
                    }
                }

                return(drawable);
            }

            return(null);
        }
Esempio n. 28
0
 public Bitmap(int width, int height, int stride, SKColorType bgra8888 = (SKColorType.Bgra8888),
               IntPtr data = default(IntPtr))
 {
     nativeSkBitmap = new SKBitmap(new SKImageInfo(width, height, bgra8888));
     nativeSkBitmap.SetPixels(data);
 }
Esempio n. 29
0
        private void CreateFeature()
        {
            lock (_sync)
            {
                if (_feature == null)
                {
                    // Create a new one
                    _feature = new Feature
                    {
                        Geometry  = Position.ToMapsui(),
                        ["Label"] = Label,
                    };
                    if (_callout != null)
                    {
                        _callout.Feature.Geometry = Position.ToMapsui();
                    }
                }
                // Check for bitmapId
                if (_bitmapId != -1)
                {
                    // There is already a registered bitmap, so delete it
                    BitmapRegistry.Instance.Unregister(_bitmapId);
                    // We don't have any bitmap up to now
                    _bitmapId = -1;
                }

                Stream stream = null;

                switch (Type)
                {
                case PinType.Svg:
                    // Load the SVG document
                    if (!string.IsNullOrEmpty(Svg))
                    {
                        stream = new MemoryStream(Encoding.UTF8.GetBytes(Svg));
                    }
                    if (stream == null)
                    {
                        return;
                    }
                    _bitmapId = BitmapRegistry.Instance.Register(stream);
                    break;

                case PinType.Pin:
                    // First we have to create a bitmap from Svg code
                    // Create a new SVG object
                    var svg = new SkiaSharp.Extended.Svg.SKSvg();
                    // Load the SVG document
                    stream = Utilities.EmbeddedResourceLoader.Load("Images.Pin.svg", typeof(Pin));
                    if (stream == null)
                    {
                        return;
                    }
                    svg.Load(stream);
                    Width  = svg.CanvasSize.Width * Scale;
                    Height = svg.CanvasSize.Height * Scale;
                    // Create bitmap to hold canvas
                    var info = new SKImageInfo((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height)
                    {
                        AlphaType = SKAlphaType.Premul
                    };
                    var bitmap = new SKBitmap(info);
                    var canvas = new SKCanvas(bitmap);
                    // Now draw Svg image to bitmap
                    using (var paint = new SKPaint())
                    {
                        // Replace color while drawing
                        paint.ColorFilter = SKColorFilter.CreateBlendMode(Color.ToSKColor(), SKBlendMode.SrcIn);     // use the source color
                        canvas.Clear();
                        canvas.DrawPicture(svg.Picture, paint);
                    }
                    // Now convert canvas to bitmap
                    using (var image = SKImage.FromBitmap(bitmap))
                        using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                        {
                            _bitmapData = data.ToArray();
                        }
                    _bitmapId = BitmapRegistry.Instance.Register(new MemoryStream(_bitmapData));
                    break;

                case PinType.Icon:
                    if (Icon != null)
                    {
                        using (var image = SKBitmap.Decode(Icon))
                        {
                            Width     = image.Width * Scale;
                            Height    = image.Height * Scale;
                            _bitmapId = BitmapRegistry.Instance.Register(new MemoryStream(Icon));
                        }
                    }
                    break;
                }

                // If we have a bitmapId (and we should have one), than draw bitmap, otherwise nothing
                if (_bitmapId != -1)
                {
                    // We only want to have one style
                    _feature.Styles.Clear();
                    _feature.Styles.Add(new SymbolStyle
                    {
                        BitmapId       = _bitmapId,
                        SymbolScale    = Scale,
                        SymbolRotation = Rotation,
                        SymbolOffset   = new Offset(Anchor.X, Anchor.Y),
                        Opacity        = 1 - Transparency,
                        Enabled        = IsVisible,
                    });
                }
            }
        }
Esempio n. 30
0
        private List <int> DefineTableCellWidths(int normalCellWidth, SKPaint headerPaint, SKPaint normalPaint)
        {
            var      bitmap = new SKBitmap(2000, 2000); // TODO insert into constructor
            SKCanvas canvas = new SKCanvas(bitmap);

            canvas.Clear(DrawingHelper.DiscordBackgroundColor);

            int[] maxWidthNeeded = new int[Header.Count];

            // the minimum size is the header text size
            for (int i = 0; i < Header.Count; i++)
            {
                var width = headerPaint.MeasureText(Header[i]);
                maxWidthNeeded[i] = (int)width + 10;
            }

            // find the max column size in the content
            for (int i = 0; i < maxWidthNeeded.Length; i++)
            {
                foreach (var row in Data)
                {
                    var width        = normalPaint.MeasureText(row[i]);
                    int currentWidth = (int)width + 10;

                    if (maxWidthNeeded[i] < currentWidth)
                    {
                        maxWidthNeeded[i] = currentWidth;
                    }
                }
            }
            // find columns that need the flex property
            List <int> flexColumns = new List <int>();
            int        freeRoom    = 0;
            int        flexContent = 0;

            for (int i = 0; i < maxWidthNeeded.Length; i++)
            {
                if (maxWidthNeeded[i] > normalCellWidth)
                {
                    flexColumns.Add(i);
                    flexContent += maxWidthNeeded[i] - normalCellWidth; // only the oversize
                }
                else
                {
                    freeRoom += normalCellWidth - maxWidthNeeded[i];
                }
            }


            if (flexColumns.Count == 0)
            {
                // no columns need flex so we distribute all even
                for (int i = 0; i < maxWidthNeeded.Length; i++)
                {
                    maxWidthNeeded[i] = normalCellWidth;
                }
            }
            else
            {
                // we need to distribute the free room over the flexContent by %
                foreach (var column in flexColumns)
                {
                    float percentNeeded    = (maxWidthNeeded[column] - normalCellWidth) / (float)flexContent;
                    float gettingFreeSpace = freeRoom * percentNeeded;
                    maxWidthNeeded[column] = normalCellWidth + (int)gettingFreeSpace;
                }
            }

            canvas.Dispose();
            bitmap.Dispose();

            return(maxWidthNeeded.ToList());
        }