Ejemplo n.º 1
0
        GetEncoder(SaveFormat saveFormat)
        {
            SixLabors.ImageSharp.Formats.IImageEncoder enc = null;
            switch (saveFormat)
            {
            case SaveFormat.Png:
                enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                break;

            case SaveFormat.Jpg:
                enc = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                break;

            case SaveFormat.Gif:
                enc = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
                break;

            case SaveFormat.Bmp:
                enc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                break;

            default:
                enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                break;
            }

            return(enc);
        } // End Function GetEncoder
Ejemplo n.º 2
0
        // 이미지를 팔레트화시킨다.
        // 팔레트에는 반드시 검은색과 흰색은 빠지도록 한다.
        private string ExecuteQuantize(string sourceFileName, int maxColor = 30)
        {
            var targetFileName = AppendToFileName(sourceFileName, "-Q");
            var quantizer      = new WuQuantizer(null, maxColor);
            var config         = Configuration.Default;

            using (var image = Image.Load <Rgba32>(sourceFileName))
                using (var quantizedResult = quantizer.CreateFrameQuantizer <Rgba32>(config).QuantizeFrame(image.Frames[0]))
                {
                    var quantizedPalette = new List <Color>();
                    foreach (var p in quantizedResult.Palette.Span)
                    {
                        var c = new Color(p);
                        // 팔레트에 흰색과 검은색은 반드시 빠지도록 한다.
                        if (c != Color.White && c != Color.Black)
                        {
                            quantizedPalette.Add(c);
                        }
                    }

                    using (var stream = new FileStream(targetFileName, FileMode.Create))
                    {
                        var encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder
                        {
                            Quantizer = new PaletteQuantizer(quantizedPalette.ToArray(), false),
                            ColorType = SixLabors.ImageSharp.Formats.Png.PngColorType.Palette,
                        };
                        image.SaveAsPng(stream, encoder);
                        stream.Close();
                    }

                    return(targetFileName);
                }
        }
Ejemplo n.º 3
0
        private void InternalImageSharpConvertImage(Stream inStream, Stream outStream, int width, int height, ThumbnailResizeType resizeType, ThumbnailFormatType formatType)
        {
            using var image = SixLabors.ImageSharp.Image.Load(inStream);
            image.Mutate(x =>
            {
                var resizeOptions = new ResizeOptions
                {
                    Position = AnchorPositionMode.Center,
                    Size     = new SixLabors.ImageSharp.Size(width, height),
                    Mode     = resizeType switch
                    {
                        ThumbnailResizeType.Pad => ResizeMode.Pad,
                        ThumbnailResizeType.Crop => ResizeMode.Crop,
                        _ => throw new NotSupportedException(),
                    },
                };

                x.Resize(resizeOptions);
            });

            if (formatType == ThumbnailFormatType.Png)
            {
                var encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                image.Save(outStream, encoder);
                return;
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 4
0
 public IImageEncoder ConvertEncoder()
 {
     SixLabors.ImageSharp.Formats.Png.PngEncoder encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
     if (_compressionLevel.HasValue)
     {
         encoder.CompressionLevel = _compressionLevel.Value;
     }
     return(encoder);
 }
Ejemplo n.º 5
0
        public static void fooo(string fileName, SaveFormat saveFormat)
        {
            //var imagePath = Microsoft.AspNetCore.Http.PathString.FromUriComponent("/" + url);
            //var fileInfo =  _fileProvider.GetFileInfo(imagePath);


            var fileInfo = new System.IO.FileInfo(fileName);
            //if (!fileInfo.Exists) { return NotFound(); }


            int width  = 100;
            int height = 100;

            byte[] data = null;


            using (MemoryStream outputStream = new MemoryStream())
            {
                using (System.IO.Stream inputStream = fileInfo.OpenRead())
                {
                    using (Image <Rgba32> image = Image.Load(inputStream))
                    {
                        image.Mutate(
                            delegate(IImageProcessingContext <Rgba32> mutant)
                        {
                            mutant.Resize(image.Width / 2, image.Height / 2);
                        }
                            );

                        IImageEncoder enc = null;

                        if (saveFormat == SaveFormat.Jpg)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                        }
                        else if (saveFormat == SaveFormat.Png)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                        }
                        else if (saveFormat == SaveFormat.Png)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
                        }
                        else if (saveFormat == SaveFormat.Bmp)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                        }

                        image.Save(outputStream, enc);
                    } // End Using image

                    data = outputStream.ToArray();
                } // End Using inputStream
            }     // End Using outputStream
        }         // End Sub fooo
Ejemplo n.º 6
0
        public IMAGEENCODER GetEncoder(SixLabors.ImageSharp.Formats.Png.PngColorType colorType)
        {
            var encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder
            {
                CompressionLevel = this.CompressionLevel,
                ColorType        = colorType,
            };

            void act(SDK.ExportContext ctx, IMAGE32 img) => ctx.WriteStream(s => img.Save(s, encoder));

            return(act);
        }
Ejemplo n.º 7
0
        public static byte[] ResizeImage(string fileName, SaveFormat saveFormat)
        {
            byte[] data = null;


            using (MemoryStream outputStream = new MemoryStream())
            {
                using (Image <Rgba32> image = Image.Load(fileName))
                {
                    image.Mutate(
                        delegate(IImageProcessingContext <Rgba32> mutant)
                    {
                        mutant.Resize(image.Width / 22, image.Height / 22);
                    }
                        );

                    IImageEncoder enc = null;

                    if (saveFormat == SaveFormat.Jpg)
                    {
                        enc = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                    }
                    else if (saveFormat == SaveFormat.Png)
                    {
                        enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                    }
                    else if (saveFormat == SaveFormat.GIF)
                    {
                        enc = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
                    }
                    else if (saveFormat == SaveFormat.Bmp)
                    {
                        enc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                    }

                    image.Save(@"D:\myfileformat." + saveFormat.ToString().ToLowerInvariant(), enc);

                    image.SaveAsJpeg(outputStream);
                } // End Using image

                data = outputStream.ToArray();
            } // End Using outputStream


            System.IO.File.WriteAllBytes(@"d:\myfile.jpg", data);

            return(data);
        } // End Sub ResizeImage
Ejemplo n.º 8
0
        public static void Initialize(Options options)
        {
            Stream resource = null;

            default_width  = options.DefaultDimension;
            default_image  = options.DefaultImage ?? "default.png";
            _persist_image = options.PersistImages;
            rootPath       = options.RootPath;
            _pngEncoder    = new SixLabors.ImageSharp.Formats.Png.PngEncoder();

            if (!String.IsNullOrEmpty(options.SpriteFile) &&
                File.Exists(options.SpriteFile))
            {
                resource = new FileStream(options.SpriteFile, FileMode.Open, FileAccess.Read);
            }
            else
            {
                var assembly = typeof(JAvatar.Generator).Assembly;
                resource = assembly.GetManifestResourceStream("JAvatar.JAvatars.png");
            }

            try
            {
                string javatarPath = System.IO.Path.Combine(rootPath, options.RoutePrefix);
                if (!Directory.Exists(javatarPath))
                {
                    Directory.CreateDirectory(javatarPath);
                }

                foreach (var f in options.Folders)
                {
                    string destPath = System.IO.Path.Combine(javatarPath, f.Name);
                    if (!Directory.Exists(destPath))
                    {
                        Directory.CreateDirectory(destPath);
                    }
                }
            } catch {
                throw new Exception("Invalid JAvatar folders");
            }

            Initialize(resource);
            resource.Dispose();
        }
Ejemplo n.º 9
0
        public void Save(System.IO.Stream strm, System.Drawing.Imaging.ImageFormat format)
        {
            SixLabors.ImageSharp.Formats.IImageEncoder enc = null;

            if (format == System.Drawing.Imaging.ImageFormat.Jpeg)
            {
                enc = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
            }
            else if (format == System.Drawing.Imaging.ImageFormat.Png)
            {
                enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
            }
            else if (format == System.Drawing.Imaging.ImageFormat.Gif)
            {
                enc = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
            }
            else if (format == System.Drawing.Imaging.ImageFormat.Bmp)
            {
                enc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
            }

            this.m_image.Save(strm, enc);
        }
        public async Task <bool> ApplyLogo()
        {
            var result = false;

            SetupInitialLogo();
            if (mainViewModel != null &&
                mainViewModel.originalWriteableBitmap != null &&
                SelectedForExport)
            {
                try
                {
                    int newLogoInsertHeight = ImageHeight - TopPadding - BottomPadding;

                    var config = new Configuration();

                    var backgroundPixel = new Rgba32();

                    if (mainViewModel.UseTransparentBackground)
                    {
                        backgroundPixel = SixLabors.ImageSharp.Color.Transparent;
                    }
                    else
                    {
                        backgroundPixel.R = mainViewModel.BackgroundColour.R;
                        backgroundPixel.G = mainViewModel.BackgroundColour.G;
                        backgroundPixel.B = mainViewModel.BackgroundColour.B;
                        backgroundPixel.A = mainViewModel.BackgroundColour.A;
                    }

                    var newLogo = new Image <Rgba32>(config, ImageWidth, ImageHeight, backgroundPixel);

                    var options = new ResizeOptions()
                    {
                        Mode     = ResizeMode.Max,
                        Position = AnchorPositionMode.Center,
                        Size     = new SixLabors.Primitives.Size(ImageWidth - TwentyPercentOf(ImageWidth), newLogoInsertHeight),
                        Sampler  = mainViewModel.SelectedResampler.Value
                    };

                    var inStream = await mainViewModel.OriginalLogoFile.OpenReadAsync();

                    var resizedOriginal = Image <Rgba32> .Load(inStream.AsStreamForRead());

                    //resize the image to fit the GIF frame bounds
                    resizedOriginal.Mutate(r => r.Resize(options));

                    //Get the top left point within the logo bounds
                    var left = HalfOf(ImageWidth) - HalfOf(resizedOriginal.Width);
                    var top  = HalfOf(ImageHeight) - HalfOf(resizedOriginal.Height);

                    newLogo.Mutate(w => w.DrawImage(resizedOriginal, new SixLabors.Primitives.Point(left, top), 1));
                    InMemoryRandomAccessStream myStream = new InMemoryRandomAccessStream();

                    SixLabors.ImageSharp.Formats.Png.PngEncoder encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                    newLogo.SaveAsPng(myStream.AsStream(), encoder);
                    myStream.Seek(0);
                    Logo = await BitmapFactory.FromStream(myStream);

                    NotifyPropertyChanged("Logo");
                    result = true;
                }
                catch (Exception ex)
                {
                }
                SavedSuccessfully = false;
            }

            return(result);
        }
Ejemplo n.º 11
0
        public static MemoryStream Mark(MemoryStream inStream, string text, string fontPath)
        {
            text = $"···甘井子区重点车辆管理系统·{text}···";
            //首先先判断该图片是否是 gif动画,如果为gif动画不对图片进行改动
            using (Image <Rgba32> img = Image.Load(inStream.ToArray(), out IImageFormat format))
            {
                FontCollection fonts      = new FontCollection();
                FontFamily     fontFamily = fonts.Install(fontPath);

                if (fontFamily == null)
                {
                    SystemFonts.TryFind("DejaVu Sans", out fontFamily);
                }
                if (fontFamily == null)
                {
                    SystemFonts.TryFind("Book", out fontFamily);
                }
                if (fontFamily == null)
                {
                    SystemFonts.TryFind("DengXian", out fontFamily);
                }
                if (fontFamily == null)
                {
                    SystemFonts.TryFind("SimSun", out fontFamily);
                }
                if (fontFamily == null)
                {
                    SystemFonts.TryFind("Arial", out fontFamily);
                }
                if (fontFamily == null)
                {
                    fontFamily = SystemFonts.Families.First(t => t.Name.Contains("Hei") || t.Name.Contains("黑"));
                }
                if (fontFamily == null)
                {
                    fontFamily = SystemFonts.Families.First();
                }
                var font = fontFamily.CreateFont(14f);
                using (var img2 = img.Clone(ctx => ctx.ApplyScalingWaterMark(font, text, Rgba32.FromHex("ffffffdd"), 20, false)))
                {
                    IImageEncoder encoder = null;
                    if (format == ImageFormats.Bmp)
                    {
                        encoder = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                    }
                    else if (format == ImageFormats.Jpeg)
                    {
                        encoder = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                    }
                    else if (format == ImageFormats.Png)
                    {
                        encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                    }
                    else if (format == ImageFormats.Gif)
                    {
                        encoder = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
                    }
                    MemoryStream outStream = new MemoryStream();
                    img2.Save(outStream, encoder);
                    outStream.Close();
                    return(outStream);
                }
            }
        }
Ejemplo n.º 12
0
        private static async Task UploadImageAsync(ChatMessage message)
        {
            if (isUploadingImage || message.ImageBase64.Length > 10_000_000)
            {
                throw new Exception();
            }
            isUploadingImage = true;

            byte[] binary = null;
            if (message.ImageBase64.StartsWith("http://") || message.ImageBase64.StartsWith("https://"))
            {
                using (var http = new HttpClient())
                {
                    binary = await http.GetByteArrayAsync(message.ImageBase64);
                }
            }
            else if (message.ImageBase64.StartsWith("data:image"))
            {
                // data:image/png;base64,iVB
                var strs = new string[] { "data:image/png;base64,", "data:image/jpg;base64,", "data:image/jpeg;base64,", "data:image/gif;base64,", "data:image/bmp;base64,", };
                foreach (var str in strs)
                {
                    if (message.ImageBase64.StartsWith(str))
                    {
                        message.ImageBase64 = message.ImageBase64.Substring(str.Length);
                        binary = Convert.FromBase64String(message.ImageBase64);
                        break;
                    }
                }
            }
            else
            {
                binary = Convert.FromBase64String(message.ImageBase64);
            }

            var imageKey     = RandomService.Next(1, 65535);
            var saveFileName = Config.Game.UploadedIconDirectory + $"c_{message.Id}_{imageKey}.png";

            try
            {
                using (Image <Rgba32> image = binary != null ? Image.Load(binary) : Image.Load(message.ImageBase64))
                {
                    var width    = image.Width;
                    var height   = image.Height;
                    var isResize = false;

                    if (width > 1200)
                    {
                        height   = (int)(height * ((float)1200 / width));
                        width    = 1200;
                        isResize = true;
                    }
                    if (height > 1200)
                    {
                        width    = (int)(width * ((float)1200 / height));
                        height   = 1200;
                        isResize = true;
                    }

                    if (isResize)
                    {
                        image.Mutate(x =>
                        {
                            x.Resize(width, height);
                        });
                    }

                    using (var stream = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        var encoder = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                        image.Save(stream, encoder);
                    }
                }

                message.ImageKey = imageKey;
                Task.Run(() =>
                {
                    Task.Delay(10_000).Wait();
                    isUploadingImage = false;
                });
            }
            catch (Exception ex)
            {
                message.ImageKey = 0;
                Task.Run(() =>
                {
                    Task.Delay(10_000).Wait();
                    isUploadingImage = false;
                });
                throw ex;
            }
        }