Beispiel #1
0
        public static SixLabors.ImageSharp.Color GetDominentColor(SixLabors.ImageSharp.Image <Rgba32> img)
        {
            //img.Mutate(x => x.Resize(new ResizeOptions { Sampler = KnownResamplers.NearestNeighbor, Size = new Size(100, 0) }));
            int r           = 0;
            int g           = 0;
            int b           = 0;
            int totalPixels = 0;

            for (int x = 0; x < img.Width; x++)
            {
                for (int y = 0; y < img.Height; y++)
                {
                    var pixel = img[x, y];

                    r += Convert.ToInt32(pixel.R);
                    g += Convert.ToInt32(pixel.G);
                    b += Convert.ToInt32(pixel.B);

                    totalPixels++;
                }
            }

            r /= totalPixels;
            g /= totalPixels;
            b /= totalPixels;

            Rgba32 dominantColor = new Rgba32((byte)r, (byte)g, (byte)b, 255);

            return(dominantColor);
        }
            public Texture(string path)
            {
                using (Stream fontStream = new FileStream(path, FileMode.Open))
                    _graphic = SixLabors.ImageSharp.Image.Load(fontStream);

                ResourcePath = path;
            }
Beispiel #3
0
        void Merge(string addImageName)
        {
            SixLabors.ImageSharp.Image baseImage = SixLabors.ImageSharp.Image.Load(Path.Combine(temp_path, pictureBox1.Name));
            SixLabors.ImageSharp.Image addImage  = SixLabors.ImageSharp.Image.Load(Path.Combine(temp_path, addImageName));

            SixLabors.ImageSharp.Point toRight = new SixLabors.ImageSharp.Point(x: baseImage.Width, y: 0);
            SixLabors.ImageSharp.Point topLeft = new SixLabors.ImageSharp.Point(x: 0, y: 0);

            SixLabors.ImageSharp.Image newImage = new SixLabors.ImageSharp.Image <Rgba32>(baseImage.Width + addImage.Width, baseImage.Height);

            newImage = newImage.Clone(ipc =>
            {
                ipc.DrawImage(baseImage, topLeft, 1);
                ipc.DrawImage(addImage, toRight, 1);
            });
            using (MemoryStream memoryStream = new MemoryStream())
            {
                SixLabors.ImageSharp.Formats.IImageEncoder imageEncoder = newImage.GetConfiguration().ImageFormatsManager.FindEncoder(PngFormat.Instance);

                newImage.Save(memoryStream, imageEncoder);

                (new Bitmap(memoryStream)).Save(Path.Combine(temp_path, "generated.png"));
                Merge_Execution(new Bitmap(memoryStream));
            }
        }
Beispiel #4
0
        public void Sync()
        {
            if (!HasChanges)
            {
                return;
            }
            HasChanges = false;

            if (RendererTexture == null)
            {
                RendererTexture = new RendererTexture(Bitmap, Label);
            }
            else
            {
                if (BitmapChanged)
                {
                    BitmapChanged = false;
                    RendererTexture.SetData(Bitmap);
                    if (AutoDisposeBitmap)
                    {
                        Log.Verbose("Disposing Bitmap for {ObjectLabel}", RendererTexture.ObjectLabel);
                        Bitmap.Dispose();
                        Bitmap = null;
                    }
                }
            }
        }
        /// <summary>
        /// Add a password to the image.
        /// </summary>
        /// <param name="curImg">Image to add password to.</param>
        /// <param name="pass">Password to add to top left corner.</param>
        /// <returns>Image with the password in the top left corner.</returns>
        private (Stream, string) AddPassword(byte[] curImg, string pass)
        {
            // draw lower, it looks better
            pass = pass.TrimTo(10, true).ToLowerInvariant();
            using (var img = Image.Load(curImg, out var format))
            {
                // choose font size based on the image height, so that it's visible
                var font = _fonts.NotoSans.CreateFont(img.Height / 12, FontStyle.Bold);
                img.Mutate(x =>
                {
                    // measure the size of the text to be drawing
                    var size = TextMeasurer.Measure(pass, new RendererOptions(font, new PointF(0, 0)));

                    // fill the background with black, add 5 pixels on each side to make it look better
                    x.FillPolygon(Rgba32.FromHex("00000080"),
                                  new PointF(0, 0),
                                  new PointF(size.Width + 5, 0),
                                  new PointF(size.Width + 5, size.Height + 10),
                                  new PointF(0, size.Height + 10));

                    // draw the password over the background
                    x.DrawText(pass,
                               font,
                               Brushes.Solid(Rgba32.White),
                               new PointF(0, 0));
                });
                // return image as a stream for easy sending
                return(img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png");
            }
        }
        LoadImageFromUrlAsync(string url)
        {
            SixLabors.ImageSharp.Image <SixLabors.ImageSharp.Rgba32> image = null;

            try
            {
                //Note: don't new up HttpClient in practice
                //This should be stored in a shared field in practice
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                {
                    using (System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(url))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            using (System.IO.Stream inputStream = await response.Content.ReadAsStreamAsync())
                            {
                                image = SixLabors.ImageSharp.Image.Load(inputStream);
                            } // End Using inputStream
                        }     // End if (response.IsSuccessStatusCode)
                    }         // End Using response
                }             // End Using httpClient
            }
            catch
            {
                // Add error logging here
                throw;
            }

            return(image);
        } // End Function LoadImageFromUrl
        public Bitmap ExporteImagemSemTileMap(List <SixLabors.ImageSharp.Image> tiles, Bitmap imagemFinal)
        {
            if (tiles.Count > 0)
            {
                int contadorTiles = 0;

                using (SixLabors.ImageSharp.Image <Rgba32> image = new SixLabors.ImageSharp.Image <Rgba32>(imagemFinal.Width, imagemFinal.Height))
                {
                    for (int y = 0; y < imagemFinal.Height; y += 8)
                    {
                        Span <Rgba32> pixelRowSpan = image.GetPixelRowSpan(y);
                        for (int x = 0; x < imagemFinal.Width; x += 8)
                        {
                            image.Mutate(o => o.DrawImage(tiles[contadorTiles], new SixLabors.ImageSharp.Point(x, y), 1f));
                            tiles[contadorTiles].Dispose();
                            //pixelRowSpan[x] = new Rgba32(x / 255, y / 255, 50, 255);
                            contadorTiles++;
                        }
                    }


                    return(image.ToBitmap());
                }
            }

            return(null);
        }
Beispiel #8
0
        internal List <Pixel> ReadImage(string path)
        {
            var result = new List <Pixel>();

            byte[] imageBytes = null;
            using (var image = ImageSharp.Load(path))
            {
                imageBytes = ImageExtension.SavePixelData(image);
                for (int x = 0; x < image.Width; x++)
                {
                    for (int y = 0; y < image.Height; y++)
                    {
                        var baseIndex = (x + (y * image.Width)) * 4;
                        if (imageBytes[baseIndex + 3] > 0)
                        {
                            result.Add(new Pixel()
                            {
                                X = x,
                                Y = y,
                                R = imageBytes[baseIndex],
                                G = imageBytes[baseIndex + 1],
                                B = imageBytes[baseIndex + 2],
                                A = imageBytes[baseIndex + 3]
                            });
                        }
                    }
                }
            }
            return(result);
        }
        public Bitmap Exporte2bpp2D(int largura, int altura, byte[] imagem)
        {
            CoresPaleta = new List <Color>();
            CoresPaleta.Add(Color.FromArgb(0, 0, 0));
            CoresPaleta.Add(Color.FromArgb(255, 255, 255));
            CoresPaleta.Add(Color.FromArgb(169, 169, 169));
            CoresPaleta.Add(Color.FromArgb(100, 100, 100));
            int contador = 0;

            var bits = new BitArray(imagem);


            SixLabors.ImageSharp.Image <Rgba32> imagemFinal = new SixLabors.ImageSharp.Image <Rgba32>(largura, altura);

            for (int y = 0; y < imagemFinal.Height; y++)
            {
                Span <Rgba32> pixelRowSpan = imagemFinal.GetPixelRowSpan(y);
                for (int x = 0; x < imagemFinal.Width; x++)
                {
                    int valor1     = bits[contador] ? 1 : 0;
                    int valor2     = bits[contador + 1] ? 1 : 0;
                    int valorFinal = (valor2 << 1) | valor1;
                    pixelRowSpan[x] = new Rgba32(CoresPaleta[valorFinal].R, CoresPaleta[valorFinal].G, CoresPaleta[valorFinal].B);
                    contador       += 2;
                }
            }

            return(imagemFinal.ToBitmap());
        }
Beispiel #10
0
        public static Image FromStream(System.IO.Stream stream)
        {
            SixLabors.ImageSharp.Image <SixLabors.ImageSharp.Rgba32> img =
                SixLabors.ImageSharp.Image.Load(stream);

            return(new Image(img));
        } // End Function FromStream
Beispiel #11
0
        private static Bitmap ReadDDS(string filePath)
        {
            SixLabors.ImageSharp.Image <Rgba32> image = null;
            using FileStream fs = File.OpenRead(filePath);
            image = bcDecoder.Decode(fs);

            return(Utility.ToBitmap(image));
        }
Beispiel #12
0
        public void SetData(Image bitmap)
        {
            // if (bitmap.Width != Width || bitmap.Height != Height)
            //     throw new InvalidOperationException();

            Bitmap        = bitmap;
            BitmapChanged = true;
            HasChanges    = true;
        }
Beispiel #13
0
        public static async Task VerifyAvatarOrThrow(string url)
        {
            // List of MIME types we consider acceptable
            var acceptableMimeTypes = new[]
            {
                "image/jpeg",
                "image/gif",
                "image/png"
                // TODO: add image/webp once ImageSharp supports this
            };

            using (var client = new HttpClient())
            {
                Uri uri;
                try
                {
                    uri = new Uri(url);
                    if (!uri.IsAbsoluteUri)
                    {
                        throw Errors.InvalidUrl(url);
                    }
                }
                catch (UriFormatException)
                {
                    throw Errors.InvalidUrl(url);
                }

                var response = await client.GetAsync(uri);

                if (!response.IsSuccessStatusCode) // Check status code
                {
                    throw Errors.AvatarServerError(response.StatusCode);
                }
                if (response.Content.Headers.ContentLength == null) // Check presence of content length
                {
                    throw Errors.AvatarNotAnImage(null);
                }
                if (response.Content.Headers.ContentLength > Limits.AvatarFileSizeLimit) // Check content length
                {
                    throw Errors.AvatarFileSizeLimit(response.Content.Headers.ContentLength.Value);
                }
                if (!acceptableMimeTypes.Contains(response.Content.Headers.ContentType.MediaType)) // Check MIME type
                {
                    throw Errors.AvatarNotAnImage(response.Content.Headers.ContentType.MediaType);
                }

                // Parse the image header in a worker
                var stream = await response.Content.ReadAsStreamAsync();

                var image = await Task.Run(() => Image.Identify(stream));

                if (image.Width > Limits.AvatarDimensionLimit || image.Height > Limits.AvatarDimensionLimit) // Check image size
                {
                    throw Errors.AvatarDimensionsTooLarge(image.Width, image.Height);
                }
            }
        }
 public void ReadImages()
 {
     if (this.bmpStream == null)
     {
         this.bmpStream          = File.OpenRead(Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, TestImages.Bmp.Car));
         this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
         this.bmpStream.Position = 0;
     }
 }
        /// <summary>
        /// Add an image to the pdf page
        /// </summary>
        /// <param name="page">The page to add the image to</param>
        /// <param name="image">The image to add</param>
        /// <param name="matrix">The placement matrix</param>
        /// <returns>The same <see cref="PdfPage"/> to chain other calls.</returns>
        public static PdfPage AddImage(this PdfPage page, SixLabors.ImageSharp.Image image, Matrix matrix)
        {
            page.ContentStream
            .SaveState()
            .CTM(matrix)
            .Paint(page.AddImageToResources(image))
            .RestoreState();

            return(page);
        }
Beispiel #16
0
 public void ReadImages()
 {
     if (this.bmpStream == null)
     {
         this.bmpStream          = File.OpenRead("../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp");
         this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
         this.bmpStream.Position = 0;
         this.bmpDrawing         = Image.FromStream(this.bmpStream);
     }
 }
Beispiel #17
0
 public CoreSize JpegImageSharpPdfJs()
 {
     using (MemoryStream memoryStream = new MemoryStream(this.jpegBytes))
     {
         using (Image <Rgba32> image = CoreImage.Load <Rgba32>(memoryStream, new PdfJsJpegDecoder()))
         {
             return(new CoreSize(image.Width, image.Height));
         }
     }
 }
Beispiel #18
0
        public static Texture GetFromBitmap(Image bitmap, string name = null, bool autoDisposeBitmap = false)
        {
            var txt = new Texture(bitmap.Width, bitmap.Height)
            {
                Label             = name,
                AutoDisposeBitmap = autoDisposeBitmap,
            };

            txt.SetData(bitmap);
            return(txt);
        }
Beispiel #19
0
 public ImageSharpImageAdapter(SixLabors.ImageSharp.Image <Rgba32> image, bool preloadFrames = true)
 {
     Image = image;
     if (preloadFrames)
     {
         for (int i = 0; i < Frames.Count; i++)
         {
             GetFrame(i);
         }
     }
 }
Beispiel #20
0
 public Image(string filePath)
 {
     using (FileStream stream = File.OpenRead(filePath))
     {
         this.image = SixLabors.ImageSharp.Image.Load <SixLabors.ImageSharp.Rgba32>(stream);
         this.Data  = new Rgba32[this.image.Width * this.image.Height];
         this.image.SavePixelData <SixLabors.ImageSharp.Rgba32>(this.Data);
         this.Width  = this.image.Width;
         this.Height = this.image.Height;
     }
 }
Beispiel #21
0
 public Image(string filePath)
 {
     using (var stream = Utility.ReadFile(filePath))
     {
         this.image  = SixLabors.ImageSharp.Image.Load <SixLabors.ImageSharp.PixelFormats.Rgba32>(stream);
         this.Data   = new Rgba32[this.image.Width * this.image.Height];
         this.Data   = image.GetPixelSpan().ToArray();
         this.Width  = this.image.Width;
         this.Height = this.image.Height;
     }
 }
        /// <summary>
        /// Load the IMG as Color 2byte list
        /// </summary>
        /// <param name="filename">The Filepath/Filenamee to load</param>
        /// <param name="width">The width from the IMG</param>
        /// <param name="height">The Height from the IMG</param>
        /// <param name="animatedColor">Needed if alpha is 0 or 1</param>
        /// <param name="pixelsize">Pixelsize of a pixel needed for Colortable</param>
        /// <returns></returns>
        internal static List <UInt16> LoadImage(String filename, ref int width, ref int height, int animatedColor = 1, int pixelsize = 1, uint type = 0, int offsetx = 0, int offsety = 0)
        {
            if (Logger.Loggeractiv)
            {
                Logger.Log("LoadImage");
            }
            List <UInt16> colors = new List <UInt16>();

            try
            {
                var image = Image.Load(filename);
                if (width == 0)
                {
                    width = image.Width;
                }
                if (height == 0)
                {
                    height = image.Height;
                }
                for (int y = offsety; y < height + offsety; y += pixelsize)
                {
                    for (int x = offsetx; x < width + offsetx; x += pixelsize) //Bgra8888
                    {
                        var  pixel = image[x, y];
                        byte a     = (animatedColor >= 1 ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.TilesObject ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.Animations ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.TGXConstSize ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.NOCompression ||
                                      ((GM1FileHeader.DataType)type) == GM1FileHeader.DataType.NOCompression1) ? byte.MaxValue : byte.MinValue;
                        if (pixel.A == 0)
                        {
                            colors.Add((ushort)32767);
                        }
                        else
                        {
                            colors.Add(EncodeColorTo2Byte((uint)(pixel.B | pixel.G << 8 | pixel.R << 16 | a << 24)));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Logger.Loggeractiv)
                {
                    Logger.Log("Exception:\n" + e.Message);
                }
                MessageBoxWindow messageBox = new MessageBoxWindow(MessageBoxWindow.MessageTyp.Info, "Something went wrong: pls add a issue on the Github Page\n\nError:\n" + e.Message);
                messageBox.Show();
            }
            return(colors);
        }
Beispiel #23
0
        public void ReadImages()
        {
            if (this.bmpStream == null)
            {
                string path = this.LargeImage
                    ? "../ImageSharp.Tests/TestImages/Formats/Jpg/baseline/jpeg420exif.jpg"
                    : "../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp";

                this.bmpStream          = File.OpenRead(path);
                this.bmpCore            = CoreImage.Load <Rgba32>(this.bmpStream);
                this.bmpStream.Position = 0;
            }
        }
        private void CalculateLuminanceValues(SixLabors.ImageSharp.Image image, byte[] bytes)
        {
            var luminance = image.CloneAs <L8>();

            for (int i = 0; i < luminance.Height; i++)
            {
                var row = luminance.GetPixelRowSpan(i);

                byte[] rawBytes = MemoryMarshal.AsBytes(row).ToArray();
                var    offset   = i * (rawBytes.Length);
                Buffer.BlockCopy(rawBytes, 0, bytes, offset, rawBytes.Length);
            }
        }
        internal unsafe static WriteableBitmap LoadImageAsBitmap(String filename, ref int width, ref int height, int offsetx = 0, int offsety = 0)
        {
            if (Logger.Loggeractiv)
            {
                Logger.Log("LoadImage");
            }
            var image = Image.Load(filename);

            if (width == 0)
            {
                width = image.Width;
            }
            if (height == 0)
            {
                height = image.Height;
            }
            WriteableBitmap bitmap = new WriteableBitmap(new PixelSize(width, height), new Vector(300, 300), Avalonia.Platform.PixelFormat.Rgba8888);

            using (var bit = bitmap.Lock())
            {
                try
                {
                    int xBit = 0, yBit = 0;
                    for (int y = offsety; y < height + offsety; y++)
                    {
                        for (int x = offsetx; x < width + offsetx; x++) //Bgra8888
                        {
                            var pixel = image[x, y];

                            var ptr = (uint *)bit.Address;
                            ptr += (uint)((bitmap.PixelSize.Width * yBit) + xBit);
                            *ptr = pixel.PackedValue;
                            xBit++;
                        }
                        xBit = 0;
                        yBit++;
                    }
                }
                catch (Exception e)
                {
                    if (Logger.Loggeractiv)
                    {
                        Logger.Log("Exception:\n" + e.Message);
                    }
                    MessageBoxWindow messageBox = new MessageBoxWindow(MessageBoxWindow.MessageTyp.Info, "Something went wrong: pls add a issue on the Github Page\n\nError:\n" + e.Message);
                    messageBox.Show();
                }
            }

            return(bitmap);
        }
Beispiel #26
0
        public Image(SixLabors.ImageSharp.Image <Rgba32> image)
        {
            //ImageSharp loads from the top-left pixel, whereas OpenGL loads from the bottom-left.
            image.Mutate(context => context.Flip(FlipMode.Vertical));
            image.TryGetSinglePixelSpan(out var span);
            //CheckSize(image.Width, image.Height);
            var pixels = new byte[(image.Width * image.Height) << 2];

            for (var i = 0; i < span.Length; i++)
            {
                var rgba32 = span[i];
                var tmp1   = i << 2;
                pixels[tmp1]        = rgba32.R;
                pixels[tmp1 | 0b01] = rgba32.G;
        public static Result Decode(this SixLabors.ImageSharp.Image source)
        {
            var reader = new BarcodeReader
            {
                AutoRotate  = true,
                TryInverted = true,
                Options     = new DecodingOptions {
                    TryHarder = true
                }
            };
            var result = reader.Decode(new ImageLuminanceSource(source));

            return(result);
        }
        /// <summary>
        /// The event handler for the option image button clicked
        /// </summary>
        private void OptionImageButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
            };


            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _selectedModOption.Image         = Image.Load(openFileDialog.FileName);
                _selectedModOption.ImageFileName = openFileDialog.FileName;
                OptionImage.Source = new BitmapImage(new Uri(openFileDialog.FileName));
            }
        }
Beispiel #29
0
        public NewEntryView()
        {
            this.InitializeComponent();

            this.DataContext = this;

            this.WhenActivated(disposables =>
            {
                this.BindCommand(ViewModel,
                                 vm => vm.AddPhotoCommand,
                                 v => v.AddPhoto)
                .DisposeWith(disposables);

                this.OneWayBind(ViewModel,
                                vm => vm.Photos,
                                v => v.Photos.ItemsSource,
                                vmToViewConverterOverride: new BitmapImageConverter())
                .DisposeWith(disposables);

                this.ViewModel?.AddPhoto
                .RegisterHandler(async interaction =>
                {
                    var picker      = new FileOpenPicker();
                    picker.ViewMode = PickerViewMode.Thumbnail;
                    picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                    picker.FileTypeFilter.Add(".jpg");
                    picker.FileTypeFilter.Add(".jpeg");
                    picker.FileTypeFilter.Add(".png");

                    var photos = await picker.PickMultipleFilesAsync();
                    if (photos != null)
                    {
                        var convertedPhotos = new List <Image>();
                        foreach (var photo in photos)
                        {
                            var stream = await photo.OpenReadAsync();
                            var image  = Image.Load(stream.AsStreamForRead());
                            convertedPhotos.Add(image);
                        }

                        interaction.SetOutput(convertedPhotos);
                    }

                    var aaa = this.Photos.ItemsSource;
                })
                .DisposeWith(disposables);
            });
        }
Beispiel #30
0
        public static System.IO.Stream WriteTextToImage(string text)
        {
            using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image <SixLabors.ImageSharp.PixelFormats.Rgba32> .Load("Assets/share-bg.png"))
            {
                SixLabors.Fonts.FontCollection fontCollection = new SixLabors.Fonts.FontCollection();
                SixLabors.Fonts.Font           regularFont    = fontCollection.Install("Assets/TitilliumWeb-SemiBold.ttf").CreateFont(24, SixLabors.Fonts.FontStyle.Regular);
                SixLabors.Fonts.Font           italicFont     = fontCollection.Install("Assets/TitilliumWeb-BoldItalic.ttf").CreateFont(24, SixLabors.Fonts.FontStyle.Italic);

                image.Mutate(x => x.DrawText(text, regularFont, SixLabors.ImageSharp.Color.White, new SixLabors.ImageSharp.PointF(100, 100)));

                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                image.Save(stream, new SixLabors.ImageSharp.Formats.Png.PngEncoder());
                stream.Position = 0;
                return(stream);
            }
        }