private static ISupportedImageFormat GetFormatFromSelectedOutput(ImageFormat convertTo)
        {
            ISupportedImageFormat format = null;

            switch (convertTo.ToString())
            {
            case "Jpeg":
                format = new JpegFormat {
                };
                break;

            case "Png":
                format = new PngFormat {
                };
                break;

            case "Tiff":
                format = new TiffFormat {
                };
                break;

            default:
                break;
            }
            return(format);
        }
Ejemplo n.º 2
0
        private ISupportedImageFormat GetFormat(string extension, ImageInstruction ins)
        {
            ISupportedImageFormat format = null;

            if (extension.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || extension.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                format = new JpegFormat {
                    Quality = ins.JpegQuality
                }
            }
            ;
            else
            if (extension.Equals(".gif", StringComparison.OrdinalIgnoreCase))
            {
                format = new GifFormat {
                }
            }
            ;
            else if (extension.Equals(".png", StringComparison.OrdinalIgnoreCase))
            {
                format = new PngFormat {
                }
            }
            ;

            return(format);
        }
Ejemplo n.º 3
0
        public static byte[] ReduceImage(byte[] imageBytes, int maxWidth = 400)
        {
            if (imageBytes == null || imageBytes.Length <= 0)
            {
                return(null);
            }

            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };
            Size size = new Size(maxWidth, 0);

            using (MemoryStream inStream = new MemoryStream(imageBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(true))
                    {
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(inStream)
                        .Resize(size)
                        .Format(format)
                        .Save(outStream);
                    }

                    // Do something with the stream.
                    return(outStream.ToArray());
                }
            }
        }
Ejemplo n.º 4
0
        public void SavePicture(HttpPostedFileBase file, string name, Size size, string formatFile = "jpg")
        {
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                // Format is automatically detected though can be changed.
                ISupportedImageFormat format = new JpegFormat {
                    Quality = 90
                };

                if (formatFile == "png")
                {
                    format = new PngFormat()
                    {
                        Quality = 90
                    }
                }
                ;

                //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                {
                    var path = Path.Combine(Server.MapPath("~/images/community"), string.Format("{0}.{1}", name, formatFile));

                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(file.InputStream)
                    .Resize(size)
                    .Format(format)
                    .Save(path);
                }
            }
        }
            //ExEnd:SourcePngFilePath
            /// <summary>
            ///Gets XMP properties from Png file
            /// </summary>
            public static void GetXMPProperties()
            {
                try
                {
                    //ExStart:GetXMPPropertiesPngImage
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get XMP data
                    XmpProperties xmpProperties = pngFormat.GetXmpProperties();
                    if (xmpProperties != null)
                    {
                        // show XMP data
                        foreach (string key in xmpProperties.Keys)
                        {
                            XmpNodeView xmpNodeView = xmpProperties[key];
                            Console.WriteLine("[{0}] = {1}", xmpNodeView.Name, xmpNodeView.Value);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No XMP data found.");
                    }
                    //ExEnd:GetXMPPropertiesPngImage
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
Ejemplo n.º 6
0
 public void processImage (){
     byte[] photoBytes = File.ReadAllBytes("input.png");
     // Format is automatically detected though can be changed.
     ISupportedImageFormat format = new PngFormat { Quality = 100 };
     Size size = new Size(
         resolution_width,
         resolution_height
     );
     using (MemoryStream inStream = new MemoryStream(photoBytes))
     {
         using (MemoryStream outStream = new MemoryStream())
         {
             using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
             {
                 imageFactory.Load(inStream)
                             .Resize(size)
                             .Format(format)
                             .Saturation(-100)
                             .Pixelate(resolution_pixel)
                             .Filter(MatrixFilters.BlackWhite)
                             .Save(outStream);
             }
             File.WriteAllBytes("output.png", outStream.ToArray());
         }
     }
     if (debug) Console.WriteLine("finished processing image");
 }
Ejemplo n.º 7
0
        private void GetImage(string iconPath)
        {
            byte[] photoBytes = File.ReadAllBytes(iconPath);
            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new PngFormat {
                Quality = 100
            };

            //Size size = new Size(150, 0);
            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(inStream)
                        //.Resize(size)
                        .Format(format)
                        .Save(outStream);
                    }
                    // Do something with the stream.
                }
            }
        }
Ejemplo n.º 8
0
        public string SaveBrandImage(Image image, PngFormat imageFormat, Tenant tenant)
        {
            var pathFileStorageDirectory = AppSettingConfigurationHelper.GetSection("PathFileStorageDirectory").Value;

            if (pathFileStorageDirectory == null || pathFileStorageDirectory.Equals(string.Empty))
            {
                throw new Exception("File configuration must have App Setting with key PathFileStorageDirectory");
            }

            var pathDirectoryProduct = Path.Combine(pathFileStorageDirectory, "Images", "Tenants", tenant.TenancyName);

            var directoryProductInfo = new DirectoryInfo(pathDirectoryProduct);

            if (!Directory.Exists(pathDirectoryProduct))
            {
                Directory.CreateDirectory(pathDirectoryProduct);
            }

            var resizedImage = ImageResizer.FixedSize(image, 100, 100);
            var filePath     = Path.Combine(directoryProductInfo.FullName, string.Format("{0}{1}", "brand", imageFormat.GetFileExtension()));

            var encoder = imageFormat.GetEncoder();

            resizedImage.Save(filePath, encoder);
            resizedImage.Dispose();
            return(Path.Combine("Images", "Tenants", tenant.TenancyName, "brand" + imageFormat.GetFileExtension()));
        }
        protected override void CreateInternal(byte[] data)
        {
            byte[] pixels  = null;
            var    width   = 0;
            var    height  = 0;
            var    flipped = false; // Whether the image was uploaded flipped - top to bottom.

            PerfProfiler.ProfilerEventStart("Decoding Image", "Loading");

            // Check if PNG.
            if (PngFormat.IsPng(data))
            {
                pixels = PngFormat.Decode(data, out PngFileHeader header);
                width  = header.Width;
                height = header.Height;
            }
            // Check if BMP.
            else if (BmpFormat.IsBmp(data))
            {
                pixels  = BmpFormat.Decode(data, out BmpFileHeader header);
                width   = header.Width;
                height  = header.Height;
                flipped = true;
            }

            if (pixels == null || width == 0 || height == 0)
            {
                Engine.Log.Warning($"Couldn't load texture - {Name}.", MessageSource.AssetLoader);
                return;
            }

            PerfProfiler.ProfilerEventEnd("Decoding Image", "Loading");
            UploadTexture(new Vector2(width, height), pixels, flipped);
        }
Ejemplo n.º 10
0
        public void DecodePngInterlaced()
        {
            string png = Path.Join("Assets", "Images", "spritesheetAnimation.png");

            byte[] bytes = File.ReadAllBytes(png);
            Assert.True(PngFormat.IsPng(bytes));

            byte[] decodedPixelData = PngFormat.Decode(bytes, out PngFileHeader fileHeader);
            Assert.True(decodedPixelData != null);
            Assert.True(fileHeader.InterlaceMethod == 1);

            Runner.ExecuteAsLoop(_ =>
            {
                var r = new Texture(
                    fileHeader.Size,
                    decodedPixelData,
                    fileHeader.PixelFormat);

                RenderComposer composer = Engine.Renderer.StartFrame();
                composer.RenderSprite(Vector3.Zero, fileHeader.Size, Color.White, r);
                Engine.Renderer.EndFrame();
                Runner.VerifyScreenshot(ResultDb.PngDecodeInterlaced);
                r.Dispose();
            }).WaitOne();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取指定图片的缩略(指定大小)
        /// </summary>
        /// <remarks>@FrancisTan 2016-05-17</remarks>
        /// <param name="imgStream">图片二进制流</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图宽度</param>
        /// <param name="quality">图片质量百分比,它必须是0~100之间的整数</param>
        /// <exception cref="ArgumentNullException">图片文件流为空</exception>
        /// <returns>缩略图二进制流</returns>
        public static Stream GetThumbnailStream(Stream imgStream, int width, int height, int quality)
        {
            if (imgStream == null || imgStream.Length == 0)
            {
                throw new ArgumentNullException("imgStream");
            }
            if (width <= 0)
            {
                throw new ArgumentOutOfRangeException("width", "图片宽度必须大于0");
            }
            if (height <= 0)
            {
                throw new ArgumentOutOfRangeException("height", "图片高度必须大于0");
            }
            if (quality <= 0 || quality > 100)
            {
                throw new ArgumentOutOfRangeException("quality", "图片质量百分比须在0~100之间");
            }

            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new PngFormat();
            Size size = new Size(width, height);

            using (ImageFactory factory = new ImageFactory(preserveExifData: true))
            {
                factory.Load(imgStream)
                .Format(format);

                var scaling   = GetScaling(factory.Image.Size, size);
                var scaleSize = GetScaleSize(factory.Image.Size, scaling);
                factory.Constrain(scaleSize);

                return(CropAroundCenterPoint(factory, size));
            }
        }
Ejemplo n.º 12
0
        private void ConvertToPNG(string path)
        {
            ISupportedImageFormat pngFormat = new PngFormat {
                Quality = 100
            };

            ConvertWebPToImage(path, pngFormat, ".png");
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Processes the loaded image. Inheritors should NOT save the image, this is done by the main method.
        /// </summary>
        /// <param name="query">Query</param>
        /// <param name="processor">Processor instance</param>
        protected virtual void ProcessImageCore(ProcessImageQuery query, ImageFactory processor)
        {
            // Resize
            var size = query.MaxWidth != null || query.MaxHeight != null
                                ? new Size(query.MaxWidth ?? 0, query.MaxHeight ?? 0)
                                : Size.Empty;

            if (!size.IsEmpty)
            {
                processor.Resize(new ResizeLayer(
                                     size,
                                     resizeMode: ConvertScaleMode(query.ScaleMode),
                                     anchorPosition: ConvertAnchorPosition(query.AnchorPosition),
                                     upscale: false));
            }

            if (query.BackgroundColor.HasValue())
            {
                processor.BackgroundColor(ColorTranslator.FromHtml(query.BackgroundColor));
            }

            // Format
            if (query.Format != null)
            {
                var format = query.Format as ISupportedImageFormat;

                if (format == null && query.Format is string)
                {
                    var requestedFormat = ((string)query.Format).ToLowerInvariant();
                    switch (requestedFormat)
                    {
                    case "jpg":
                    case "jpeg":
                        format = new JpegFormat();
                        break;

                    case "png":
                        format = new PngFormat();
                        break;

                    case "gif":
                        format = new GifFormat();
                        break;
                    }
                }

                if (format != null)
                {
                    processor.Format(format);
                }
            }

            // Set Quality
            if (query.Quality.HasValue)
            {
                processor.Quality(query.Quality.Value);
            }
        }
        /// <summary>
        ///     Creates the favicon.
        /// </summary>
        /// <param name="rootFolder">The root folder.</param>
        /// <param name="originalFile">The original file.</param>
        /// <param name="filePrefix">The file prefix.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        public override void CreateFavicon(
            ContentReference rootFolder,
            Stream originalFile,
            string filePrefix,
            int width,
            int height)
        {
            //Get a suitable MediaData type from extension
            Type mediaType = this.ContentMediaResolver.Service.GetFirstMatching(".png");

            ContentType contentType = this.ContentTypeRepository.Service.Load(mediaType);

            try
            {
                //Get a new empty file data
                ImageData media = this.ContentRepository.Service.GetDefault<ImageData>(rootFolder, contentType.ID);

                media.Name = string.Format(CultureInfo.InvariantCulture, "{0}-{1}x{2}.png", filePrefix, width, height);

                //Create a blob in the binary container
                Blob blob = this.BlobFactory.Service.CreateBlob(media.BinaryDataContainer, ".png");

                ISupportedImageFormat format = new PngFormat();
                Size size = new Size(width, height);

                using (MemoryStream outStream = new MemoryStream())
                {
                    // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(originalFile)
                                    .Resize(size)
                                    .Format(format)
                                    .Save(outStream);
                    }

                    //Assign to file and publish changes
                    media.BinaryData = blob;
                    this.ContentRepository.Service.Save(media, SaveAction.Publish);
                }
            }
            catch (AccessDeniedException accessDeniedException)
            {
                Logger.Error("[Favicons] Error creating icon.", accessDeniedException);
            }
            catch (ArgumentNullException argumentNullException)
            {
                Logger.Error("[Favicons] Error creating icon.", argumentNullException);
            }
            catch (FormatException formatException)
            {
                Logger.Error("[Favicons] Error creating icon.", formatException);
            }
        }
            /// <summary>
            /// Updates XMP data of Png file and creates output file
            /// </summary>
            public static void UpdateXMPData()
            {
                try
                {
                    //ExStart:UpdateXMPPropertiesPngImage
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get xmp wrapper
                    XmpPacketWrapper xmpPacket = pngFormat.GetXmpData();

                    // create xmp wrapper if not exists
                    if (xmpPacket == null)
                    {
                        xmpPacket = new XmpPacketWrapper();
                    }

                    // check if DublinCore schema exists
                    if (!xmpPacket.ContainsPackage(Namespaces.DublinCore))
                    {
                        // if not - add DublinCore schema
                        xmpPacket.AddPackage(new DublinCorePackage());
                    }

                    // get DublinCore package
                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);

                    string authorName  = "New author";
                    string description = "New description";
                    string subject     = "New subject";
                    string publisher   = "New publisher";
                    string title       = "New title";
                    // set author
                    dublinCorePackage.SetAuthor(authorName);
                    // set description
                    dublinCorePackage.SetDescription(description);
                    // set subject
                    dublinCorePackage.SetSubject(subject);
                    // set publisher
                    dublinCorePackage.SetPublisher(publisher);
                    // set title
                    dublinCorePackage.SetTitle(title);
                    // update XMP package
                    pngFormat.SetXmpData(xmpPacket);

                    // commit changes
                    pngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdateXMPPropertiesPngImage
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
Ejemplo n.º 16
0
        protected override void writeCustomXml(XmlTextWriter writer)
        {
            writer.WriteStartElement("image");
            string    fileName = Path.GetTempPath() + "mazioPictureShape.png";
            PngFormat format   = new PngFormat();

            Img.Save(fileName, format.getCodecInfo(), format.getParameters());
            byte[] bytes = File.ReadAllBytes(fileName);
            writer.WriteBase64(bytes, 0, bytes.Length);
            writer.WriteEndElement();
        }
        public void GetPng()
        {
            var expected = new PngFormat();
            var i        = new Imaging();

            foreach (var extension in expected.FileExtensions)
            {
                var format = i.Get(extension);
                Assert.AreEqual(expected.GetType(), format.GetType());
            }
        }
Ejemplo n.º 18
0
        public async Task <UploadedImage> CreateUploadedImage(string imageUrl, string imageName, string imagePath = "")
        {
            if (!string.IsNullOrEmpty(imageName))
            {
                byte[] fileBytes = await LoadImage(new Uri(imageUrl));

                if (fileBytes == null)
                {
                    return(null);
                }

                ISupportedImageFormat format = new PngFormat(); {   };
                //   Size size = new Size(150, 0)
                using (MemoryStream inStream = new MemoryStream(fileBytes))
                {
                    using (MemoryStream outStream = new MemoryStream())
                    {
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(inStream)
                            // .Resize(size)
                            .Format(format)
                            .Save(outStream);
                        }
                        // Do something with the stream.
                        var imageFileName = imagePath + imageName + ".png";
                        var fi            = new FileInfo(imageFileName);
                        if (!fi.Exists)
                        {
                            using (
                                var fileStream = new FileStream(imageFileName, FileMode.CreateNew,
                                                                FileAccess.ReadWrite))
                            {
                                outStream.Position = 0;
                                outStream.CopyTo(fileStream);
                            }
                        }
                    }
                }

                return(new UploadedImage
                {
                    ContentType = "image/png",
                    Data = fileBytes,
                    Name = imageName,
                    Url = $"{_imageRootPath}/{imageName}"
                });
            }
            return(null);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Save an image for reference.
        /// </summary>
        /// <param name="fileName">The image name.</param>
        /// <param name="size">The image size.</param>
        /// <param name="pixels">The image pixels.</param>
        public static void SaveReferenceImage(string fileName, Vector2 size, byte[] pixels)
        {
            if (!_runnerFolderCreated)
            {
                Directory.CreateDirectory(RunnerReferenceImageFolder);
                _runnerFolderCreated = true;
            }

            string filePath = Path.Join(RunnerReferenceImageFolder, fileName);

            byte[] file = PngFormat.Encode(ImageUtil.FlipImageYNoMutate(pixels, (int)size.Y), size, PixelFormat.Rgba);
            File.WriteAllBytes(filePath, file);
        }
Ejemplo n.º 20
0
        public static CalorieImage ProcessImage(MemoryStream Input)
        {
            var NewImg = new CalorieImage();

            ISupportedImageFormat format = new PngFormat {
                Quality = 99
            };


            //image
            using (MemoryStream maxStream = new MemoryStream())
            {
                var RL = new ImageProcessor.Imaging.ResizeLayer(new Size(500, 500),
                                                                ImageProcessor.Imaging.ResizeMode.Pad)
                {
                    Upscale = false
                };

                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    imageFactory.Load(Input).Resize(RL)
                    .Format(format)
                    .BackgroundColor(Color.Transparent)
                    .Save(maxStream);
                }

                NewImg.ImageData = maxStream.ToArray();
            }

            //thumbnail
            using (MemoryStream thumbStream = new MemoryStream())
            {
                var RL = new ImageProcessor.Imaging.ResizeLayer(new Size(100, 100),
                                                                ImageProcessor.Imaging.ResizeMode.Pad)
                {
                    Upscale = false
                };

                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    imageFactory.Load(Input).Resize(RL)
                    .Format(format)
                    .BackgroundColor(Color.Transparent)
                    .Save(thumbStream);
                }

                NewImg.ThumbData = thumbStream.ToArray();
            }

            return(NewImg);
        }
Ejemplo n.º 21
0
        private FormattedImage CreateFormattedImage(Image <Rgba32> image, PngFormat format)
        {
            // Again, the constructor of FormattedImage useful for tests is internal, so we need to use reflection.
            Type type     = typeof(FormattedImage);
            var  instance = type.Assembly.CreateInstance(
                type.FullName,
                false,
                BindingFlags.Instance | BindingFlags.NonPublic,
                null,
                new object[] { image, format },
                null,
                null);

            return((FormattedImage)instance);
        }
Ejemplo n.º 22
0
        private static void CropImage(string file, MapConfiguration config, MemoryStream inStream)
        {
            // this was done all to the documentation
            ISupportedImageFormat format = new PngFormat();
            Size      size = new Size(config.ImgWidth * config.Scale, config.ImgHeight * config.Scale);
            Rectangle crop = new Rectangle(new Point(0, config.Scale * MapConfiguration.LOGO_BLEED / 2), size);

            using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
            {
                imageFactory.Load(inStream)
                .Crop(crop)
                .Resize(size)
                .Format(format)
                .Save(file);
            }
        }
Ejemplo n.º 23
0
        private ISupportedImageFormat GetImageFormat(string filename)
        {
            ISupportedImageFormat format = null;
            String temp = filename;

            temp.ToLower();

            if (temp.EndsWith(".png"))
            {
                format = new PngFormat {
                    Quality = 70
                }
            }
            ;

            if (temp.EndsWith(".gif"))
            {
                format = new GifFormat {
                    Quality = 70
                }
            }
            ;

            if (temp.EndsWith(".jpeg"))
            {
                format = new JpegFormat {
                    Quality = 70
                }
            }
            ;
            if (temp.EndsWith(".jpg"))
            {
                format = new JpegFormat {
                    Quality = 70
                }
            }
            ;
            if (format == null)
            {
                format = new JpegFormat {
                    Quality = 70
                };
            }

            return(format);
        }
Ejemplo n.º 24
0
        private static MemoryStream Filter(byte[] photoBytes, IMatrixFilter e)
        {
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };

            using MemoryStream inStream = new MemoryStream(photoBytes);
            MemoryStream outStream = new MemoryStream();

            using (ImageFactory imageFactory = new ImageFactory())
            {
                imageFactory.Load(inStream)
                .Filter(e)
                .Format(format)
                .Save(outStream);
            }
            return(outStream);
        }
Ejemplo n.º 25
0
        private static MemoryStream Tint(byte[] photoBytes, string color)
        {
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };

            using MemoryStream inStream = new MemoryStream(photoBytes);
            MemoryStream outStream = new MemoryStream();

            using (ImageFactory imageFactory = new ImageFactory())
            {
                imageFactory.Load(inStream)
                .Tint(ColorTranslator.FromHtml(color))
                .Format(format)
                .Save(outStream);
            }
            return(outStream);
        }
Ejemplo n.º 26
0
        private void LoadFile(OtherAsset f)
        {
            _status = "Loading...";

            byte[] data = f.Content;
            if (!PngFormat.IsPng(data))
            {
                _status = $"The provided file {f.Name} is not a PNG file.";
                return;
            }

            byte[] pixels = PngFormat.Decode(data, out PngFileHeader header);
            byte[] output = PngFormat.Encode(pixels, header.Width, header.Height);

            bool saved = Engine.AssetLoader.Save(output, "Player" + "/" + f.Name, false);

            _status = saved ? "Done!" : "Error when saving the file. Check logs.";
        }
Ejemplo n.º 27
0
        private static MemoryStream Blur(byte[] photoBytes, int size)
        {
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };

            using MemoryStream inStream = new MemoryStream(photoBytes);
            MemoryStream outStream = new MemoryStream();

            using (ImageFactory imageFactory = new ImageFactory())
            {
                imageFactory.Load(inStream)
                .GaussianBlur(size)
                .Format(format)
                .Save(outStream);
            }
            return(outStream);
        }
Ejemplo n.º 28
0
        public async Task Usertest()
        {
            Image img = DrawText(Context.User.Username + "#" + Context.User.DiscriminatorValue, new Font("Diavlo Light", 30.0f), System.Drawing.Color.FromArgb(0, 0, 0), System.Drawing.Color.FromArgb(0, 0, 0, 0));

            using WebClient myWebClient = new WebClient();
            string url = Commands.GetUserAvatarUrl(Context.User);

            if (Commands.GetUserAvatarUrl(Context.User) == null)
            {
                url = Context.User.GetDefaultAvatarUrl();
            }
            byte[] photoBytes            = myWebClient.DownloadData(url);
            ISupportedImageFormat format = new PngFormat {
                Quality = 70
            };
            Size size = new Size(200, 200);

            using MemoryStream inStream     = new MemoryStream(photoBytes);
            using MemoryStream avatarStream = new MemoryStream();
            using MemoryStream outStream    = new MemoryStream();
            using (ImageFactory imageFactory = new ImageFactory())
            {
                imageFactory.Load(inStream)
                .Resize(size)
                .Format(format)
                .Save(avatarStream);
            }
            avatarStream.Position = 0;
            Image imanidiot = Image.FromStream(avatarStream);

            Image imge = new Bitmap(800, 240);

            using (Graphics gr = Graphics.FromImage(imge))
            {
                gr.Clear(System.Drawing.Color.White);
                gr.DrawImage(imanidiot, new Point(13, 20));
                gr.DrawImage(img, new Point(229, 25));
            }
            imge.Save(outStream, System.Drawing.Imaging.ImageFormat.Png);

            outStream.Position = 0;
            await Context.Channel.SendFileAsync(outStream, "silverbotimage.png", "there");
        }
Ejemplo n.º 29
0
            public void Write(Stream file)
            {
                var encoder = new PngBitmapEncoder();

                encoder.Frames.Add(BitmapFrame.Create(m_bitmap));
                using (var png = new MemoryStream())
                    using (var cwp = new BinaryWriter(file, System.Text.Encoding.ASCII, true))
                    {
                        encoder.Save(png);
                        var header = new byte[0x11];
                        png.Position = 0x10;
                        png.Read(header, 0, header.Length);
                        cwp.Write(0x50445743u); // 'CWDP'
                        cwp.Write(header, 0, header.Length);
                        long idat;
                        using (var bin = new BinMemoryStream(png, ""))
                            idat = PngFormat.FindChunk(bin, "IDAT");
                        if (-1 == idat)
                        {
                            throw new InvalidFormatException("CWP conversion failed");
                        }
                        png.Position = idat;
                        png.Read(header, 0, 8);
                        int chunk_size = BigEndian.ToInt32(header, 0) + 4;
                        cwp.Write(header, 0, 4);
                        for (;;)
                        {
                            CopyChunk(png, file, chunk_size);
                            if (8 != png.Read(header, 0, 8))
                            {
                                throw new InvalidFormatException("CWP conversion failed");
                            }
                            if (Binary.AsciiEqual(header, 4, "IEND"))
                            {
                                cwp.Write((byte)0);
                                break;
                            }
                            chunk_size = BigEndian.ToInt32(header, 0) + 4;
                            cwp.Write(header, 0, 8);
                        }
                    }
            }
Ejemplo n.º 30
0
        public static void LoadCache()
        {
            string folderName = Path.Join("Assets", "CachedResults");

            if (!Directory.Exists(folderName))
            {
                return;
            }

            string[] files = Directory.GetFiles(folderName);

            foreach (string file in files)
            {
                byte[] fileData = File.ReadAllBytes(file);
                string fileName = Path.GetFileNameWithoutExtension(file);
                byte[] pixels   = PngFormat.Decode(fileData, out PngFileHeader header);
                ImageUtil.FlipImageY(pixels, (int)header.Size.Y);
                CachedResults.Add(fileName, pixels);
            }
        }
        public static void ResizedImage(Stream stream, int width, int height, ResizeMode resizeMode, ref string path)
        {
            ISupportedImageFormat format = new PngFormat();

            format.Quality = 100;
            path           = path + "." + format.DefaultExtension;
            Size size = new Size(width, height);

            using (ImageFactory imageFactory = new ImageFactory())
            {
                ResizeLayer resizeLayer = new ResizeLayer(size, resizeMode);
                imageFactory.Load(stream)
                .Resize(resizeLayer)
                .BackgroundColor(Color.White)
                .Format(format)
                .Save(path);
            }

            path = MyCustomUtility.RelativeFromAbsolutePath(path);
        }
            //ExEnd:SourcePngFilePath
            /// <summary>
            ///Gets XMP properties from Png file
            /// </summary> 
            public static void GetXMPProperties()
            {
                try
                {
                    //ExStart:GetXMPPropertiesPngImage 
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get XMP data
                    XmpProperties xmpProperties = pngFormat.GetXmpProperties();
                    if (xmpProperties != null)
                    {
                        // show XMP data
                        foreach (string key in xmpProperties.Keys)
                        {
                            XmpNodeView xmpNodeView = xmpProperties[key];
                            Console.WriteLine("[{0}] = {1}", xmpNodeView.Name, xmpNodeView.Value);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No XMP data found.");
                    }
                    //ExEnd:GetXMPPropertiesPngImage 
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates XMP values of Png file and creates output file
            /// </summary> 
            public static void UpdateXMPValues()
            {
                try
                {
                    //ExStart:UpdateXmpValuesPngImage
                    // initialize PngFormat
                    PngFormat PngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    const string dcFormat = "test format";
                    string[] dcContributors = { "test contributor" };
                    const string dcCoverage = "test coverage";
                    const string phCity = "NY";
                    const string phCountry = "USA";
                    const string xmpCreator = "GroupDocs.Metadata";

                    PngFormat.XmpValues.Schemes.DublinCore.Format = dcFormat;
                    PngFormat.XmpValues.Schemes.DublinCore.Contributors = dcContributors;
                    PngFormat.XmpValues.Schemes.DublinCore.Coverage = dcCoverage;
                    PngFormat.XmpValues.Schemes.Photoshop.City = phCity;
                    PngFormat.XmpValues.Schemes.Photoshop.Country = phCountry;
                    PngFormat.XmpValues.Schemes.XmpBasic.CreatorTool = xmpCreator;

                    // commit changes
                    PngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdateXmpValuesPngImage
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates XMP data of Png file and creates output file
            /// </summary> 
            public static void UpdateXMPData()
            {
                try
                {
                    //ExStart:UpdateXMPPropertiesPngImage 
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get xmp wrapper
                    XmpPacketWrapper xmpPacket = pngFormat.GetXmpData();

                    // create xmp wrapper if not exists
                    if (xmpPacket == null)
                    {
                        xmpPacket = new XmpPacketWrapper();
                    }

                    // check if DublinCore schema exists
                    if (!xmpPacket.ContainsPackage(Namespaces.DublinCore))
                    {
                        // if not - add DublinCore schema
                        xmpPacket.AddPackage(new DublinCorePackage());
                    }

                    // get DublinCore package
                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);

                    string authorName = "New author";
                    string description = "New description";
                    string subject = "New subject";
                    string publisher = "New publisher";
                    string title = "New title";
                    // set author
                    dublinCorePackage.SetAuthor(authorName);
                    // set description
                    dublinCorePackage.SetDescription(description);
                    // set subject
                    dublinCorePackage.SetSubject(subject);
                    // set publisher
                    dublinCorePackage.SetPublisher(publisher);
                    // set title
                    dublinCorePackage.SetTitle(title);
                    // update XMP package
                    pngFormat.SetXmpData(xmpPacket);

                    // commit changes
                    pngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdateXMPPropertiesPngImage 
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Removes XMP data of Png file and creates output file
            /// </summary> 
            public static void RemoveXMPData()
            {
                try
                {
                    //ExStart:RemoveXMPPropertiesPngImage 
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // remove XMP package
                    pngFormat.RemoveXmpData();

                    // commit changes
                    pngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:RemoveXMPPropertiesPngImage 
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates thumbnails in XMP data of Png file and creates output file
            /// </summary> 
            public static void UpdateThumbnailInXMPData()
            {
                try
                {
                    //ExStart:UpdateThumbnailXmpPropertiesPngImage

                    string path = Common.MapSourceFilePath(filePath);
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get image base64 string
                    string base64String;
                    using (Image image = Image.FromFile(path))
                    {
                        using (MemoryStream m = new MemoryStream())
                        {
                            image.Save(m, image.RawFormat);
                            byte[] imageBytes = m.ToArray();

                            // Convert byte[] to Base64 String
                            base64String = Convert.ToBase64String(imageBytes);
                        }
                    }

                    // create image thumbnail
                    Thumbnail thumbnail = new Thumbnail { ImageBase64 = base64String };

                    // initialize array and add thumbnail
                    Thumbnail[] thumbnails = new Thumbnail[1];
                    thumbnails[0] = thumbnail;

                    // update thumbnails property in XMP Basic schema
                    pngFormat.XmpValues.Schemes.XmpBasic.Thumbnails = thumbnails;

                    // commit changes
                    pngFormat.Save(Common.MapDestinationFilePath(filePath));

                    //ExEnd:UpdateThumbnailXmpPropertiesPngImage

                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates Basic Job XMP data of Png file and creates output file
            /// </summary> 
            public static void UpdateBasicJobXMPProperties()
            {
                try
                {
                    //ExStart:UpdateBasicJobTicketXmpPropertiesPngImage
                    // initialize PngFormat
                    PngFormat pngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get xmp data
                    var xmp = pngFormat.GetXmpData();

                    BasicJobTicketPackage package = null;

                    // looking for the BasicJob schema if xmp data is presented
                    if (xmp != null)
                    {
                        package = xmp.GetPackage(Namespaces.BasicJob) as BasicJobTicketPackage;
                    }
                    else
                    {
                        xmp = new XmpPacketWrapper();
                    }

                    if (package == null)
                    {
                        // create package if not exist
                        package = new BasicJobTicketPackage();

                        // and add it to xmp data
                        xmp.AddPackage(package);
                    }

                    // create array of jobs
                    Job[] jobs = new Job[1];
                    jobs[0] = new Job()
                    {
                        Id = "1",
                        Name = "test job"
                    };

                    // update schema
                    package.SetJobs(jobs);

                    // update xmp data
                    pngFormat.SetXmpData(xmp);

                    // commit changes
                    pngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdateBasicJobTicketXmpPropertiesPngImage

                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates CameraRaw XMP data of Png file and creates output file
            /// </summary> 
            public static void UpdateCameraRawXMPProperties()
            {
                try
                {
                    //ExStart:UpdateCameraRawXmpPropertiesPngImage
                    // initialize PngFormat
                    PngFormat PngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get access to CameraRaw schema
                    var package = PngFormat.XmpValues.Schemes.CameraRaw;

                    // update properties
                    package.AutoBrightness = true;
                    package.AutoContrast = true;
                    package.CropUnits = CropUnits.Pixels;

                    // update white balance
                    package.SetWhiteBalance(WhiteBalance.Auto);

                    // commit changes
                    PngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdateCameraRawXmpPropertiesPngImage
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }
            /// <summary>
            /// Updates PagedText XMP data of Png file and creates output file
            /// </summary> 
            public static void UpdatePagedTextXMPProperties()
            {
                try
                {
                    //ExStart:UpdatePagedTextXmpPropertiesPngImage
                    // initialize PngFormat
                    PngFormat PngFormat = new PngFormat(Common.MapSourceFilePath(filePath));

                    // get access to PagedText schema
                    var package = PngFormat.XmpValues.Schemes.PagedText;

                    // update MaxPageSize
                    package.MaxPageSize = new Dimensions(600, 800);

                    // update number of pages
                    package.NumberOfPages = 10;

                    // update plate names
                    package.PlateNames = new string[] { "1", "2", "3" };

                    // commit changes
                    PngFormat.Save(Common.MapDestinationFilePath(filePath));
                    //ExEnd:UpdatePagedTextXmpPropertiesPngImage
                    Console.WriteLine("File saved in destination folder.");
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }