Wednesday, June 5, 2019

ImageSharp: convert Image to System.Drawing.Bitmap and back

See also on GitHub Gist

namespace Vurdalakov
{
    using System;
    using System.IO;

    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Advanced;
    using SixLabors.ImageSharp.Formats.Png;
    using SixLabors.ImageSharp.PixelFormats;

    public static class ImageSharpExtensions
    {
        public static System.Drawing.Bitmap ToBitmap<TPixel>(this Image<TPixel> image) where TPixel : struct, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(PngFormat.Instance);
                image.Save(memoryStream, imageEncoder);

                memoryStream.Seek(0, SeekOrigin.Begin);

                return new System.Drawing.Bitmap(memoryStream);
            }
        }

        public static Image<TPixel> ToImageSharpImage<TPixel>(this System.Drawing.Bitmap bitmap) where TPixel : struct, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

                memoryStream.Seek(0, SeekOrigin.Begin);

                return Image.Load<TPixel>(memoryStream);
            }
        }
    }
}

Tuesday, June 4, 2019

ImageSharp: convert Image to byte array

See also on GitHub Gist

namespace Vurdalakov
{
    using System;
    using System.IO;
    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Advanced;
    using SixLabors.ImageSharp.Formats;
    using SixLabors.ImageSharp.PixelFormats;

    public static class ImageSharpExtensions
    {
        public static Byte[] ToArray<TPixel>(this Image<TPixel> image, IImageFormat imageFormat) where TPixel : struct, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(imageFormat);
                image.Save(memoryStream, imageEncoder);
                return memoryStream.ToArray();
            }
        }
    }
}

Usage example:

var image = Image.Load<Rgba32>("c:\\temp\\myimage.jpg");

var pngBytes = image.ToArray(PngFormat.Instance);

Thursday, May 30, 2019

Bluetooth/Mac address to string

public static String FormatMacAddress(UInt32 macAddress)
{
    return String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}",
        (macAddress >> 40) & 0xFF, (macAddress >> 32) & 0xFF, (macAddress >> 24) & 0xFF,
        (macAddress >> 16) & 0xFF, (macAddress >> 08) & 0xFF, (macAddress >> 00) & 0xFF);
}

Thursday, March 21, 2019

How to change Visual Studio installation nickname