Beispiel #1
0
        /// <summary>
        /// The position in the original string where the first character of the captured substring was found.
        /// </summary>
        /// <param name="queryString">
        /// The query string to search.
        /// </param>
        /// <returns>
        /// The zero-based starting position in the original string where the captured substring was found.
        /// </returns>
        public int MatchRegexIndex(string queryString)
        {
            int index = 0;

            // Set the sort order to max to allow filtering.
            this.SortOrder = int.MaxValue;

            foreach (Match match in this.RegexPattern.Matches(queryString))
            {
                if (match.Success)
                {
                    if (index == 0)
                    {
                        // Set the index on the first instance only.
                        this.SortOrder = match.Index;

                        ISupportedImageFormat format = this.ParseFormat(match.Value.Split('=')[1]);
                        if (format != null)
                        {
                            this.Processor.DynamicParameter = format;
                        }
                    }

                    index += 1;
                }
            }

            return(this.SortOrder);
        }
Beispiel #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);
        }
        /// <summary>
        /// Loads the image to process. Always call this method first.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="T:System.IO.Stream"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(Stream stream)
        {
            ISupportedImageFormat format = FormatUtilities.GetFormat(stream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            MemoryStream memoryStream = new MemoryStream();

            // Copy the stream. Disposal of the input stream is the responsibility
            // of the user.
            stream.CopyTo(memoryStream);

            // Set the position to 0 afterwards.
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            memoryStream.Position = 0;

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality   = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat;

            if (imageFormat != null)
            {
                imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image);
            }

            this.backupFormat       = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            // TODO. Some custom data doesn't seem to get copied by default methods.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            this.ShouldProcess = true;

            // Normalize the gamma component of the image.
            if (this.FixGamma)
            {
                this.Gamma(2.2F);
            }

            return(this);
        }
        private static void ConvertImageToWebP(string inputPath, string outputPath, ISupportedImageFormat outputImageFormat)
        {
            byte[] imageBytes;

            try
            {
                imageBytes = File.ReadAllBytes(inputPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            using (MemoryStream memoryStream = new MemoryStream(imageBytes))
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                {
                    try
                    {
                        imageFactory.Load(memoryStream).Format(outputImageFormat).Save(outputPath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        return;
                    }
                }
        }
Beispiel #5
0
 private static void ConvertWebPToImage(string path, ISupportedImageFormat format, string formatString)
 {
     byte[] b_image;
     try
     {
         b_image = File.ReadAllBytes(path);
     }
     catch (Exception e)
     {
         MessageBox.Show("读入图片时出现错误:\n" + e.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
         return;
     }
     using (MemoryStream inStream = new MemoryStream(b_image))
     {
         using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
         {
             string savePath = Path.GetDirectoryName(path) + @"/" + Path.GetFileNameWithoutExtension(path) + formatString;
             try
             {
                 WebPFormat webpFormat = new WebPFormat();
                 imageFactory.Load(webpFormat.Load(inStream)).Format(format).Save(savePath);
             }
             catch (Exception e)
             {
                 MessageBox.Show("转换时出现错误:\n" + e.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                 return;
             }
         }
     }
 }
Beispiel #6
0
        /// <summary>
        /// Parses the input string to return the correct <see cref="ISupportedImageFormat"/>.
        /// </summary>
        /// <param name="identifier">
        /// The identifier.
        /// </param>
        /// <returns>
        /// The <see cref="ISupportedImageFormat"/>.
        /// </returns>
        private ISupportedImageFormat ParseFormat(string identifier)
        {
            identifier = identifier.ToLowerInvariant();
            string finalIdentifier = identifier.Equals("png8") ? "png" : identifier;
            ISupportedImageFormat        newFormat = null;
            List <ISupportedImageFormat> formats   = ImageProcessorBootstrapper.Instance.SupportedImageFormats.ToList();
            ISupportedImageFormat        format    = formats.FirstOrDefault(f => f.FileExtensions.Any(e => e.Equals(finalIdentifier, StringComparison.InvariantCultureIgnoreCase)));

            if (format != null)
            {
                // Return a new instance as we want to use instance properties.
                newFormat = Activator.CreateInstance(format.GetType()) as ISupportedImageFormat;

                if (newFormat != null)
                {
                    // I wish this wasn't hard-coded but there's no way I can
                    // find to preserve the palette.
                    if (identifier.Equals("png8"))
                    {
                        newFormat.IsIndexed = true;
                    }
                    else if (identifier.Equals("png"))
                    {
                        newFormat.IsIndexed = false;
                    }
                }
            }

            return(newFormat);
        }
        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);
        }
        public byte[] GetImageByteArray(string fileName, ISupportedImageFormat imageFormat)
        {
            try
            {
                byte[] imgBytes;
                _imageFactory.Load(fileName);
                if (!Equals(_imageFactory.CurrentImageFormat, imageFormat))
                {
                    _imageFactory.Format(imageFormat);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    _imageFactory.Save(ms);
                    ms.Flush();
                    imgBytes = ms.ToArray();
                }

                return(imgBytes);
            }
            catch (Exception exception)
            {
                Log.Error(exception, $"GetImageByteArray Failed using filename: {fileName} and image format: {imageFormat}");
                return(null);
            }
        }
        public void AlphaIsModified()
        {
            foreach (ImageFactory imageFactory in this.ListInputImages())
            {
                Image original = (Image)imageFactory.Image.Clone();
                imageFactory.Alpha(50);

                ISupportedImageFormat format = imageFactory.CurrentImageFormat;

                // The Image class does not support alpha transparency in bitmaps.
                if (format.GetType() == typeof(BitmapFormat))
                {
                    AssertionHelpers.AssertImagesAreIdentical(
                        original,
                        imageFactory.Image,
                        "because the alpha operation should not have been applied on {0}",
                        imageFactory.ImagePath);
                }
                else
                {
                    AssertionHelpers.AssertImagesAreDifferent(
                        original,
                        imageFactory.Image,
                        "because the alpha operation should have been applied on {0}",
                        imageFactory.ImagePath);
                }
            }
        }
Beispiel #10
0
        private void ResizeImage(Stream sourceFileStream, string destinationFilePath, Size size, ResizeMode mode, Color backgroundColor, int rotationDegrees)
        {
            ISupportedImageFormat format = GetImageFormat(destinationFilePath, this.Quality);

            using (MemoryStream outStream = new MemoryStream())
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    // Load, resize, set the format and quality and save an image.
                    var image = imageFactory
                                .AutoRotate()
                                .Load(sourceFileStream)
                                .Rotate(rotationDegrees)
                                .Resize(new ResizeLayer(size, resizeMode: mode))
                                .Format(format)
                                .BackgroundColor(backgroundColor)
                                .Save(outStream);
                }

                // Do something with the stream.
                var path = Path.GetDirectoryName(destinationFilePath);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                FileStream file = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write);
                outStream.WriteTo(file);
                file.Close();
            }
        }
        /// <summary>
        /// Sets the output format of the current image to the matching <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="format">The <see cref="ISupportedImageFormat"/>. to set the image to.</param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Format(ISupportedImageFormat format)
        {
            if (this.ShouldProcess)
            {
                this.CurrentImageFormat = format;
            }

            return(this);
        }
        /// <summary>
        /// Performs the Format effect from the ImageProcessor library.
        /// </summary>
        /// <param name="image">The image with which to apply the effect.</param>
        /// <param name="format">The ISupportedImageFormat that the Image will be converted to upon saving.</param>
        /// <returns>A new image that will be saved with the corresponding ImageFormat.</returns>
        public Image Format(Image image, ISupportedImageFormat format)
        {
            using var factory = new ImageFactory();

            factory.Load(image);
            factory.Format(format);

            var result = factory.Image;

            return(new Bitmap(result));
        }
Beispiel #13
0
        /// <summary>
        /// Loads the image to process. Always call this method first.
        /// </summary>
        /// <param name="imagePath">The absolute path to the image to load.</param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(string imagePath)
        {
            FileInfo fileInfo = new FileInfo(imagePath);

            if (fileInfo.Exists)
            {
                this.ImagePath = imagePath;

                // Open a file stream to prevent the need for lock.
                using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                {
                    ISupportedImageFormat format = FormatUtilities.GetFormat(fileStream);

                    if (format == null)
                    {
                        throw new ImageFormatException("Input stream is not a supported format.");
                    }

                    MemoryStream memoryStream = new MemoryStream();

                    // Copy the stream.
                    fileStream.CopyTo(memoryStream);

                    // Set the position to 0 afterwards.
                    fileStream.Position = memoryStream.Position = 0;

                    // Set our image as the memory stream value.
                    this.Image = format.Load(memoryStream);

                    // Store the stream so we can dispose of it later.
                    this.InputStream = memoryStream;

                    // Set the other properties.
                    format.Quality          = DefaultQuality;
                    format.IsIndexed        = FormatUtilities.IsIndexed(this.Image);
                    this.backupFormat       = format;
                    this.CurrentImageFormat = format;

                    // Always load the data.
                    foreach (PropertyItem propertyItem in this.Image.PropertyItems)
                    {
                        this.ExifPropertyItems[propertyItem.Id] = propertyItem;
                    }

                    this.ShouldProcess = true;
                }
            }
            else
            {
                throw new FileNotFoundException(imagePath);
            }

            return(this);
        }
Beispiel #14
0
        /// <summary>
        /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            ISupportedImageFormat format = obj as ISupportedImageFormat;

            if (format == null)
            {
                return(false);
            }

            return(this.MimeType.Equals(format.MimeType) && this.IsIndexed.Equals(format.IsIndexed));
        }
Beispiel #15
0
        /// <summary>
        /// Loads the image to process. Always call this method first.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="T:System.IO.Stream"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(Stream stream)
        {
            MemoryStream memoryStream = new MemoryStream();

            // Copy the stream. Disposal of the input stream is the responsibility
            // of the user.
            stream.CopyTo(memoryStream);

            // Set the position to 0 afterwards.
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality   = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            this.backupFormat       = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            // TODO. Some custom data doesn't seem to get copied by default methods.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            this.backupExifPropertyItems = this.ExifPropertyItems;

            // Ensure the image is in the most efficient format.
            Image formatted = this.Image.Copy();

            this.Image.Dispose();
            this.Image = formatted;

            this.ShouldProcess = true;

            return(this);
        }
Beispiel #16
0
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            foreach (IDocument input in inputs)
            {
                FilePath relativePath = input.FilePath(Keys.RelativeFilePath);
                if (relativePath == null)
                {
                    continue;
                }
                FilePath destinationPath = context.FileSystem.GetOutputPath(relativePath);

                foreach (ImageInstruction instruction in _instructions)
                {
                    ISupportedImageFormat format = GetFormat(relativePath.Extension, instruction);
                    if (format == null)
                    {
                        continue;
                    }

                    string destinationFile = relativePath.FileNameWithoutExtension.FullPath;

                    if (instruction.IsFileNameCustomized)
                    {
                        if (!string.IsNullOrWhiteSpace(instruction.FileNamePrefix))
                        {
                            destinationFile = instruction.FileNamePrefix + destinationFile;
                        }

                        if (!string.IsNullOrWhiteSpace(instruction.FileNameSuffix))
                        {
                            destinationFile += instruction.FileNameSuffix + relativePath.Extension;
                        }
                    }
                    else
                    {
                        destinationFile += instruction.GetSuffix() + relativePath.Extension;
                    }

                    destinationPath = destinationPath.Directory.CombineFile(destinationFile);
                    Trace.Verbose($"{Keys.WritePath}: {destinationPath}");

                    Stream output = ProcessImage(input, format, instruction);

                    yield return(context.GetDocument(input, output, new MetadataItems
                    {
                        { Keys.WritePath, destinationPath },
                        { Keys.WriteExtension, relativePath.Extension }
                    }));
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            try
            {
                ISupportedImageFormat format = this.DynamicParameter;
                factory.Format(format);
            }
            catch (Exception ex)
            {
                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(factory.Image);
        }
Beispiel #18
0
        /// <summary>
        /// Get the correct mime-type for the given string input.
        /// </summary>
        /// <param name="path">
        /// The path to the cached image.
        /// </param>
        /// <returns>
        /// The <see cref="string"/> matching the correct mime-type.
        /// </returns>
        public static string GetMimeType(string path)
        {
            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false))
            {
                ISupportedImageFormat format = FormatUtilities.GetFormat(file);

                if (format != null)
                {
                    return(format.MimeType);
                }
            }

            return(string.Empty);
        }
        /// <summary>
        /// Loads the image to process from an array of bytes. Always call this method first.
        /// </summary>
        /// <param name="bytes">
        /// The <see cref="T:System.Byte"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(byte[] bytes)
        {
            MemoryStream memoryStream = new MemoryStream(bytes);

            ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality   = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat;

            if (imageFormat != null)
            {
                imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image);
            }

            this.backupFormat       = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            this.ShouldProcess = true;

            // Normalize the gamma component of the image.
            if (this.FixGamma)
            {
                this.Gamma(2.2F);
            }

            return(this);
        }
Beispiel #20
0
        private async void ConvertWebPToImage(string path, ISupportedImageFormat format, string formatString)
        {
            byte[] b_image;
            try
            {
                b_image = File.ReadAllBytes(path);
            }
            catch (Exception e)
            {
                await this.ShowMessageAsync("错误", "读入图片时发生错误: " + e.Message, MessageDialogStyle.Affirmative, generalDialogSetting);

                return;
            }
            using (MemoryStream inStream = new MemoryStream(b_image))
            {
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                {
                    string savePath = Path.GetDirectoryName(path) + @"/" + Path.GetFileNameWithoutExtension(path) + formatString;
                    if (File.Exists(savePath))
                    {
                        var existDialogRes = await this.ShowMessageAsync("文件已存在", "将要保存的文件: " + savePath + " 已存在,是否覆盖?", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings()
                        {
                            AffirmativeButtonText = "覆盖",
                            NegativeButtonText    = "取消",
                            DialogTitleFontSize   = 16
                        });

                        if (!(existDialogRes == MessageDialogResult.Affirmative))
                        {
                            return;
                        }
                    }
                    try
                    {
                        WebPFormat webpFormat = new WebPFormat();
                        imageFactory.Load(webpFormat.Load(inStream)).Format(format).Save(savePath);
                    }
                    catch (Exception e)
                    {
                        await this.ShowMessageAsync("错误", "转换时发生错误: " + e.Message, MessageDialogStyle.Affirmative, generalDialogSetting);

                        return;
                    }
                    await this.ShowMessageAsync("转换完成", "图片已转换完成。", MessageDialogStyle.Affirmative, generalDialogSetting);
                }
            }
        }
Beispiel #21
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);
        }
Beispiel #22
0
        /// <summary>
        /// The position in the original string where the first character of the captured substring was found.
        /// </summary>
        /// <param name="queryString">
        /// The query string to search.
        /// </param>
        /// <returns>
        /// The zero-based starting position in the original string where the captured substring was found.
        /// </returns>
        public int MatchRegexIndex(string queryString)
        {
            this.SortOrder = int.MaxValue;
            Match match = this.RegexPattern.Match(queryString);

            if (match.Success)
            {
                ISupportedImageFormat format = this.ParseFormat(match.Value.Split('=')[1]);
                if (format != null)
                {
                    this.SortOrder = match.Index;
                    this.Processor.DynamicParameter = format;
                }
            }

            return(this.SortOrder);
        }
Beispiel #23
0
 public void RescaleImage(string imageUrl, Size size, ISupportedImageFormat format, string fileName)
 {
     using (WebClient webClient = new WebClient())
     {
         using (Stream inStream = webClient.OpenRead(imageUrl))
         {
             using (ImageFactory imageFactory = new ImageFactory())
             {
                 string filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);
                 imageFactory.Load(inStream)
                 .Resize(size)
                 .Format(format)
                 .Save(filePath);
                 Console.WriteLine($"\n{ fileName} resized and saved in : { filePath}");
             }
         }
     }
 }
Beispiel #24
0
        /// <summary>
        /// Returns the content-type/mime-type for a given image type based on it's file extension
        /// </summary>
        /// <param name="extension">
        /// Can be prefixed with '.' or not (i.e. ".jpg"  or "jpg")
        /// </param>
        /// <returns>The <see cref="string"/></returns>
        internal string GetContentTypeForExtension(string extension)
        {
            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(extension));
            }

            extension = extension.TrimStart('.');

            ISupportedImageFormat found = ImageProcessorBootstrapper.Instance.SupportedImageFormats
                                          .FirstOrDefault(x => x.FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase));

            if (found != null)
            {
                return(found.MimeType);
            }

            // default
            return(new JpegFormat().MimeType);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="imageBytes"></param>
 /// <param name="newSize"></param>
 /// <param name="newFormat"></param>
 /// <returns></returns>
 /// <remarks></remarks>
 public static byte[] RescaleImage(byte[] imageBytes, Size newSize, ISupportedImageFormat newFormat)
 {
     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(preserveExifData: true))
             {
                 // Load, resize, set the format and quality and save an image.
                 imageFactory.Load(inStream)
                 .Resize(newSize)
                 .Format(newFormat)
                 .Save(outStream);
             }
             //  return the new byte array
             return(outStream.ToArray());
         }
     }
 }
Beispiel #26
0
        /// <summary>
        /// Loads the image to process from an array of bytes. Always call this method first.
        /// </summary>
        /// <param name="bytes">
        /// The <see cref="T:System.Byte"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(byte[] bytes)
        {
            MemoryStream memoryStream = new MemoryStream(bytes);

            ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality   = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            this.backupFormat       = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            // Ensure the image is in the most efficient format.
            Image formatted = this.Image.Copy();

            this.Image.Dispose();
            this.Image = formatted;

            this.ShouldProcess = true;

            return(this);
        }
Beispiel #27
0
        public MemoryStream ProcessImage(byte[] photoBytes, int width, int height, string fileFormat, int qualityPercentage)
        {
            Guard.WhenArgument(photoBytes, "photoBytes").IsNullOrEmpty().Throw();
            Guard.WhenArgument(fileFormat, "fileFormat").IsNullOrEmpty().Throw();

            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                MemoryStream outStream = new MemoryStream();
                using (this.imageFactory)
                {
                    fileFormat = fileFormat.ToLower();
                    ISupportedImageFormat format = null;
                    if (fileFormat == ".jpg" || fileFormat == ".jpeg")
                    {
                        format = new JpegFormat {
                            Quality = qualityPercentage
                        };
                    }
                    else if (fileFormat == ".png")
                    {
                        format = new PngFormat {
                            Quality = qualityPercentage
                        };
                    }
                    else
                    {
                        return(null);
                    }

                    Size size = new Size(width, height);

                    this.imageFactory.Load(inStream)
                    .Resize(size)
                    .Format(format)
                    .Save(outStream);

                    return(outStream);
                }
            }
        }
Beispiel #28
0
        private void ResizeImage(Stream sourceFileStream, string destinationFilePath, Size size, ResizeMode mode, Color?backgroundColor = null)
        {
            ISupportedImageFormat format = GetImageFormat(destinationFilePath, this.Quality);

            using (MemoryStream outStream = new MemoryStream())
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    // Load, resize, set the format and quality and save an image.
                    var image = imageFactory
                                .AutoRotate()
                                .Load(sourceFileStream);


                    image.Resize(new ResizeLayer(size, resizeMode: mode))
                    .Format(format);

                    //Any padded areas in the output for image formats that do not contain an alpha channel will display as black (the default encoder output). To change this color to another use this option
                    if (backgroundColor != null)
                    {
                        image.BackgroundColor(backgroundColor.Value);
                    }

                    image.Save(outStream);
                }
                // Do something with the stream.
                var path = Path.GetDirectoryName(destinationFilePath);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                FileStream file = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write);
                outStream.WriteTo(file);
                file.Close();
            }
        }
        /// <summary>
        /// Sets the output format of the current image to the matching <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="format">The <see cref="ISupportedImageFormat"/>. to set the image to.</param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Format(ISupportedImageFormat format)
        {
            if (this.ShouldProcess)
            {
                this.CurrentImageFormat = format;
            }

            return this;
        }
        /// <summary>
        /// Loads the image to process from an array of bytes. Always call this method first.
        /// </summary>
        /// <param name="bytes">
        /// The <see cref="T:System.Byte"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(byte[] bytes)
        {
            MemoryStream memoryStream = new MemoryStream(bytes);

            ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat;
            if (imageFormat != null)
            {
                imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image);
            }

            this.backupFormat = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            // Ensure the image is in the most efficient format.
            Image formatted = this.Image.Copy();
            this.Image.Dispose();
            this.Image = formatted;

            this.ShouldProcess = true;

            return this;
        }
        /// <summary>
        /// Loads the image to process. Always call this method first.
        /// </summary>
        /// <param name="imagePath">The absolute path to the image to load.</param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(string imagePath)
        {
            FileInfo fileInfo = new FileInfo(imagePath);
            if (fileInfo.Exists)
            {
                this.ImagePath = imagePath;

                // Open a file stream to prevent the need for lock.
                using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                {
                    ISupportedImageFormat format = FormatUtilities.GetFormat(fileStream);

                    if (format == null)
                    {
                        throw new ImageFormatException("Input stream is not a supported format.");
                    }

                    MemoryStream memoryStream = new MemoryStream();

                    // Copy the stream.
                    fileStream.CopyTo(memoryStream);

                    // Set the position to 0 afterwards.
                    memoryStream.Position = 0;

                    // Set our image as the memory stream value.
                    this.Image = format.Load(memoryStream);

                    // Store the stream so we can dispose of it later.
                    this.InputStream = memoryStream;

                    // Set the other properties.
                    format.Quality = DefaultQuality;
                    format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

                    IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat;
                    if (imageFormat != null)
                    {
                        imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image);
                    }

                    this.backupFormat = format;
                    this.CurrentImageFormat = format;

                    // Always load the data.
                    foreach (PropertyItem propertyItem in this.Image.PropertyItems)
                    {
                        this.ExifPropertyItems[propertyItem.Id] = propertyItem;
                    }

                    this.backupExifPropertyItems = this.ExifPropertyItems;

                    // Ensure the image is in the most efficient format.
                    Image formatted = this.Image.Copy();
                    this.Image.Dispose();
                    this.Image = formatted;

                    this.ShouldProcess = true;
                }
            }
            else
            {
                throw new FileNotFoundException(imagePath);
            }

            return this;
        }
        /// <summary>
        /// Loads the image to process. Always call this method first.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="T:System.IO.Stream"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(Stream stream)
        {
            ISupportedImageFormat format = FormatUtilities.GetFormat(stream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            MemoryStream memoryStream = new MemoryStream();

            // Copy the stream. Disposal of the input stream is the responsibility  
            // of the user.
            stream.CopyTo(memoryStream);

            // Set the position to 0 afterwards.
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            memoryStream.Position = 0;

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat;
            if (imageFormat != null)
            {
                imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image);
            }

            this.backupFormat = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            // TODO. Some custom data doesn't seem to get copied by default methods.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            this.backupExifPropertyItems = this.ExifPropertyItems;

            // Ensure the image is in the most efficient format.
            Image formatted = this.Image.Copy();
            this.Image.Dispose();
            this.Image = formatted;

            this.ShouldProcess = true;

            return this;
        }
Beispiel #33
0
        private Stream ProcessImage(IDocument input, ISupportedImageFormat format, ImageInstruction ins)
        {
            using (var imageFactory = new img.ImageFactory(preserveExifData: true))
            {
                // Load, resize, set the format and quality and save an image.
                img.ImageFactory fac;
                using (Stream stream = input.GetStream())
                {
                    fac = imageFactory.Load(stream).Format(format);
                }

                if (ins.IsNeedResize)
                {
                    if (ins.IsCropRequired)
                    {
                        var layer = new ResizeLayer(
                            size: ins.GetCropSize().Value,
                            anchorPosition: ins.GetAnchorPosition(),
                            resizeMode: ResizeMode.Crop
                            );

                        fac.Resize(layer);
                    }
                    else
                    {
                        fac.Resize(ins.GetCropSize().Value);
                    }
                }

                foreach (var f in ins.Filters)
                {
                    fac.Filter(ins.GetMatrixFilter(f));
                }

                if (ins.Brightness.HasValue)
                {
                    fac.Brightness(ins.Brightness.Value);
                }

                if (ins.Constraint.HasValue)
                {
                    fac.Constrain(ins.Constraint.Value);
                }

                if (ins.Opacity.HasValue)
                {
                    fac.Alpha(ins.Opacity.Value);
                }

                if (ins.Hue != null)
                {
                    fac.Hue(ins.Hue.Degrees, ins.Hue.Rotate);
                }

                if (ins.Tint != null)
                {
                    fac.Tint(ins.Tint.Value);
                }

                if (ins.Vignette != null)
                {
                    fac.Vignette(ins.Vignette.Value);
                }

                if (ins.Saturation.HasValue)
                {
                    fac.Saturation(ins.Saturation.Value);
                }

                if (ins.Contrast.HasValue)
                {
                    fac.Contrast(ins.Contrast.Value);
                }

                var outputStream = new MemoryStream();
                fac.Save(outputStream);
                outputStream.Seek(0, SeekOrigin.Begin);
                return outputStream;
            }
        }
Beispiel #34
0
        /// <summary>
        /// Convert a file to PictureContainer
        /// </summary>
        /// <param name="fileIn"></param>
        /// <param name="size"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        private static PictureContainer Convert(string fileIn, PresetSize size, ISupportedImageFormat format)
        {
            var filename = Path.GetFileNameWithoutExtension(fileIn);
            // Generate Url
            var id = Guid.NewGuid();
            var path = string.Format(@"/Temp/{0}/{1}_{2}x{3}.{4}", id, filename, size.Size.Width, size.Size.Height,
                format.DefaultExtension);
            using (var imageFactory = new ImageFactory(true))
            {
                try
                {
                    // Load, resize, set the format and save an image.
                    imageFactory.Load(fileIn)
                        .Resize(size.Size)
                        .Format(format);
                    imageFactory.Save(path);

                    if (!File.Exists(path)) throw new FileNotFoundException("File not found");
                    var pc = new PictureContainer
                    {
                        PresetSize = size,
                        FilePath = path
                    };
                    return pc;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return null;
                }
            }
        }
Beispiel #35
0
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            foreach (IDocument input in inputs)
            {
                var path = input.Get <string>(Keys.SourceFilePath);

                if (string.IsNullOrWhiteSpace(path))
                {
                    continue;
                }

                var    relativePath = Path.GetDirectoryName(PathHelper.GetRelativePath(context.InputFolder, path));
                string destination  = Path.Combine(context.OutputFolder, relativePath, Path.GetFileName(path));

                string destinationDirectory = Path.GetDirectoryName(destination);
                if (!Directory.Exists(destinationDirectory))
                {
                    Directory.CreateDirectory(destinationDirectory);
                }

                var extension = Path.GetExtension(path);


                foreach (var ins in _instructions)
                {
                    ISupportedImageFormat format = GetFormat(extension, ins);
                    if (format == null)
                    {
                        continue;
                    }

                    string destinationFile = Path.GetFileNameWithoutExtension(path);

                    if (ins.IsFileNameCustomized)
                    {
                        if (!string.IsNullOrWhiteSpace(ins.FileNamePrefix))
                        {
                            destinationFile = ins.FileNamePrefix + destinationFile;
                        }

                        if (!string.IsNullOrWhiteSpace(ins.FileNameSuffix))
                        {
                            destinationFile += ins.FileNameSuffix + extension;
                        }
                    }
                    else
                    {
                        destinationFile += ins.GetSuffix() + extension;
                    }

                    var destinationPath = Path.Combine(destinationDirectory, destinationFile);
                    context.Trace.Verbose($"{Keys.WritePath}: {destinationPath}");

                    var output = ProcessImage(input, format, ins);

                    var clone = input.Clone(output, new MetadataItems
                    {
                        { Keys.WritePath, destinationPath },
                        { Keys.WriteExtension, extension }
                    });

                    yield return(clone);
                }
            }
        }
Beispiel #36
0
        /// <summary>
        /// Loads the image to process from an array of bytes. Always call this method first.
        /// </summary>
        /// <param name="bytes">
        /// The <see cref="T:System.Byte"/> containing the image information.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Load(byte[] bytes)
        {
            MemoryStream memoryStream = new MemoryStream(bytes);

            ISupportedImageFormat format = FormatUtilities.GetFormat(memoryStream);

            if (format == null)
            {
                throw new ImageFormatException("Input stream is not a supported format.");
            }

            // Set our image as the memory stream value.
            this.Image = format.Load(memoryStream);

            // Save the bit depth
            this.CurrentBitDepth = Image.GetPixelFormatSize(this.Image.PixelFormat);

            // Store the stream so we can dispose of it later.
            this.InputStream = memoryStream;

            // Set the other properties.
            format.Quality = DefaultQuality;
            format.IsIndexed = FormatUtilities.IsIndexed(this.Image);

            this.backupFormat = format;
            this.CurrentImageFormat = format;

            // Always load the data.
            foreach (int id in this.Image.PropertyIdList)
            {
                this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id);
            }

            IAnimatedImageFormat imageFormat = this.CurrentImageFormat as IAnimatedImageFormat;
            if (imageFormat != null)
            {
                imageFormat.AnimationProcessMode = this.AnimationProcessMode;
            }

            // Ensure the image is in the most efficient format.
            Image formatted = this.Image.Copy(this.AnimationProcessMode);

            // Clear property items.
            if (!this.PreserveExifData)
            {
                this.ClearExif(formatted);
            }

            this.Image.Dispose();
            this.Image = formatted;

            this.ShouldProcess = true;

            return this;
        }
Beispiel #37
0
        private Stream ProcessImage(IDocument input, ISupportedImageFormat format, ImageInstruction ins)
        {
            using (var imageFactory = new img.ImageFactory(preserveExifData: true))
            {
                // Load, resize, set the format and quality and save an image.
                img.ImageFactory fac;
                using (Stream stream = input.GetStream())
                {
                    fac = imageFactory.Load(stream).Format(format);
                }

                if (ins.IsNeedResize)
                {
                    if (ins.IsCropRequired)
                    {
                        var layer = new ResizeLayer(
                            size: ins.GetCropSize().Value,
                            anchorPosition: ins.GetAnchorPosition(),
                            resizeMode: ResizeMode.Crop
                            );

                        fac.Resize(layer);
                    }
                    else
                    {
                        fac.Resize(ins.GetCropSize().Value);
                    }
                }

                foreach (var f in ins.Filters)
                {
                    fac.Filter(ins.GetMatrixFilter(f));
                }

                if (ins.Brightness.HasValue)
                {
                    fac.Brightness(ins.Brightness.Value);
                }

                if (ins.Constraint.HasValue)
                {
                    fac.Constrain(ins.Constraint.Value);
                }

                if (ins.Opacity.HasValue)
                {
                    fac.Alpha(ins.Opacity.Value);
                }

                if (ins.Hue != null)
                {
                    fac.Hue(ins.Hue.Degrees, ins.Hue.Rotate);
                }

                if (ins.Tint != null)
                {
                    fac.Tint(ins.Tint.Value);
                }

                if (ins.Vignette != null)
                {
                    fac.Vignette(ins.Vignette.Value);
                }

                if (ins.Saturation.HasValue)
                {
                    fac.Saturation(ins.Saturation.Value);
                }

                if (ins.Contrast.HasValue)
                {
                    fac.Contrast(ins.Contrast.Value);
                }

                var outputStream = new MemoryStream();
                fac.Save(outputStream);
                outputStream.Seek(0, SeekOrigin.Begin);
                return(outputStream);
            }
        }
Beispiel #38
0
        /// <summary>
        /// Sets the output format of the current image to the matching <see cref="T:System.Drawing.Imaging.ImageFormat"/>.
        /// </summary>
        /// <param name="format">The <see cref="ISupportedImageFormat"/>. to set the image to.</param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Format(ISupportedImageFormat format)
        {
            if (this.ShouldProcess)
            {
                this.CurrentImageFormat = format;

                // Apply any fomatting quirks.
                this.CurrentImageFormat.ApplyProcessor(factory => factory.Image, this);
            }

            return this;
        }