예제 #1
0
        internal void SetDefine(MagickFormat format, string name, string value)
        {
            Throw.IfNullOrEmpty("name", name);
            Throw.IfNull("value", value);

            _NativeInstance.SetOption(ParseDefine(format, name), value);
        }
 /// <summary>
 /// Writes the images to the specified buffer writter. If the output image's file format does not
 /// allow multi-image files multiple files will be written.
 /// </summary>
 /// <param name="bufferWriter">The buffer writer to write the images to.</param>
 /// <param name="format">The format to use.</param>
 /// <exception cref="MagickException">Thrown when an error is raised by ImageMagick.</exception>
 public void Write(IBufferWriter <byte> bufferWriter, MagickFormat format)
 {
     using (_ = new TemporaryMagickFormat(this, format))
     {
         Write(bufferWriter);
     }
 }
예제 #3
0
        /// <summary>
        /// Generate compress result from base64 image.
        /// </summary>
        /// <param name="base64Image"></param>
        /// <returns></returns>
        public CompressedImageModel CompressFromBase64(string base64Image)
        {
            MagickFormat format = MagickFormat.Jpeg;
            IMagickImage image  = MagickImage.FromBase64(base64Image);

            MemoryStream compressedBuffer = new MemoryStream();
            MemoryStream thumbnailBuffer  = new MemoryStream();

            image.Write(compressedBuffer, format);

            image.Resize(ImageService.ThumbnailAspectSize, ImageService.ThumbnailAspectSize);
            image.Write(thumbnailBuffer, format);

            compressedBuffer.Seek(0, SeekOrigin.Begin);
            thumbnailBuffer.Seek(0, SeekOrigin.Begin);

            this.ImageOptimizer.LosslessCompress(compressedBuffer);
            this.ImageOptimizer.LosslessCompress(thumbnailBuffer);

            return(new CompressedImageModel(
                       compressedBuffer.GetBuffer(),
                       thumbnailBuffer.GetBuffer(),
                       ImageService.ImageFormat
                       ));
        }
예제 #4
0
        public static void SaveImageToFile(string filepath, Image image, MagickFormat format = MagickFormat.Png)
        {
            ImageUInt8RGB byteRgbImage = (ImageUInt8RGB)image.ToRGB().ToUInt8();
            uint          width        = byteRgbImage.Width;
            uint          height       = byteRgbImage.Height;

            byte[,] r = byteRgbImage.R.ToByteArray();
            byte[,] g = byteRgbImage.G.ToByteArray();
            byte[,] b = byteRgbImage.B.ToByteArray();
            byte[] data = new byte[width * height * 3];
            for (uint y = 0; y < height; y++)
            {
                for (uint x = 0; x < width; x++)
                {
                    data[3 * width * y + 3 * x]     = r[x, y];
                    data[3 * width * y + 3 * x + 1] = g[x, y];
                    data[3 * width * y + 3 * x + 2] = b[x, y];
                }
            }
            var readSettings = new MagickReadSettings
            {
                Width  = (int)width,
                Height = (int)height,
                Format = MagickFormat.Rgb
            };
            var savedImage = new MagickImage(data, readSettings);

            savedImage.Format = format;
            savedImage.Write(filepath);
        }
예제 #5
0
        public Stream ConvertPhoto(IFormFile file, MagickFormat format, ImageSize size = null)
        {
            byte[] fileBytes = null;
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                fileBytes = ms.ToArray();
            }

            var memStream = new MemoryStream();

            {
                using (MagickImage image = new MagickImage(fileBytes))
                {
                    image.Format = format;

                    if (size != null)
                    {
                        image.Resize(size.width, size.height);
                    }

                    image.Write(memStream);
                }
            }

            return(memStream);
        }
예제 #6
0
 private void SetFormat(MagickFormat format)
 {
     foreach (MagickImage image in _Images)
     {
         image.Format = format;
     }
 }
예제 #7
0
        /// <summary>
        /// Sets a format-specific option.
        /// </summary>
        /// <param name="format">The format to set the option for.</param>
        /// <param name="name">The name of the option.</param>
        /// <param name="value">The value of the option.</param>
        public void SetDefine(MagickFormat format, string name, string value)
        {
            Throw.IfNullOrEmpty(nameof(name), name);
            Throw.IfNull(nameof(value), value);

            SetOption(ParseDefine(format, name), value);
        }
예제 #8
0
        ///<summary>
        /// Sets a format-specific option.
        ///</summary>
        ///<param name="format">The format to set the option for.</param>
        ///<param name="name">The name of the option.</param>
        ///<param name="value">The value of the option.</param>
        public void SetDefine(MagickFormat format, string name, string value)
        {
            Throw.IfNullOrEmpty("name", name);
            Throw.IfNull("value", value);

            _Defines.Add(new MagickDefine(format, name, value));
        }
예제 #9
0
        private static StringValues MagickToContentType(MagickFormat fmt)
        {
            if (fmt == MagickFormat.Bmp)
            {
                return("image/bmp");
            }
            if (fmt == MagickFormat.Png)
            {
                return("image/png");
            }
            if (fmt == MagickFormat.WebP)
            {
                return("image/webp");
            }
            if (fmt == MagickFormat.Jpeg)
            {
                return("image/jpeg");
            }
            if (fmt == MagickFormat.Gif)
            {
                return("image/gif");
            }
            if (fmt == MagickFormat.Svg)
            {
                return("image/svg+xml");
            }

            throw new Exception("Unsuoported magick format: " + fmt);
        }
예제 #10
0
        private MagickReadSettings CreateMagickReadSettings(XmlElement element)
        {
            if (element == null)
            {
                return(null);
            }
            MagickReadSettings result = new MagickReadSettings();

            result.ColorSpace    = Variables.GetValue <Nullable <ColorSpace> >(element, "colorSpace");
            result.Defines       = CreateIReadDefines(element["defines"]);
            result.Density       = Variables.GetValue <Nullable <PointD> >(element, "density");
            result.Format        = Variables.GetValue <Nullable <MagickFormat> >(element, "format");
            result.FrameCount    = Variables.GetValue <Nullable <Int32> >(element, "frameCount");
            result.FrameIndex    = Variables.GetValue <Nullable <Int32> >(element, "frameIndex");
            result.Height        = Variables.GetValue <Nullable <Int32> >(element, "height");
            result.PixelStorage  = CreatePixelStorageSettings(element["pixelStorage"]);
            result.UseMonochrome = Variables.GetValue <Nullable <Boolean> >(element, "useMonochrome");
            result.Width         = Variables.GetValue <Nullable <Int32> >(element, "width");
            XmlElement setDefine = (XmlElement)element.SelectSingleNode("setDefine");

            if (setDefine != null)
            {
                MagickFormat format_ = XmlHelper.GetAttribute <MagickFormat>(setDefine, "format");
                String       name_   = XmlHelper.GetAttribute <String>(setDefine, "name");
                String       value_  = XmlHelper.GetAttribute <String>(setDefine, "value");
                result.SetDefine(format_, name_, value_);
            }
            return(result);
        }
예제 #11
0
 public void Write(Stream stream, MagickFormat format)
 {
     _mainBuffer.Seek(0, SeekOrigin.Begin);
     Cli(_mainBuffer, _readSettings, stream, new MagickReadSettings {
         Format = format
     });
 }
예제 #12
0
        public static async Task Convert(string dir, MagickFormat format, int quality, string ext = "", bool print = true, bool setProgress = true)
        {
            var files = IOUtils.GetFilesSorted(dir);

            if (print)
            {
                Logger.Log($"Converting {files.Length} files in {dir}");
            }
            int counter = 0;

            foreach (string file in files)
            {
                if (print)
                {
                    Logger.Log("Converting " + Path.GetFileName(file) + " to " + format.ToString().StripNumbers().ToUpper(), false, true);
                }
                MagickImage img = new MagickImage(file);
                img.Format  = format;
                img.Quality = quality;
                string outpath = file;
                if (!string.IsNullOrWhiteSpace(ext))
                {
                    outpath = Path.ChangeExtension(outpath, ext);
                }
                img.Write(outpath);
                counter++;
                if (setProgress)
                {
                    Program.mainForm.SetProgress((int)Math.Round(((float)counter / files.Length) * 100f));
                }
                await Task.Delay(1);
            }
        }
예제 #13
0
 /// <summary>
 /// Writes the image to the specified stream.
 /// </summary>
 /// <param name="stream">The stream to write the image data to.</param>
 /// <param name="format">The format to use.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 /// <exception cref="MagickException">Thrown when an error is raised by ImageMagick.</exception>
 public async Task WriteAsync(Stream stream, MagickFormat format, CancellationToken cancellationToken)
 {
     using (_ = new TemporaryMagickFormat(this, format))
     {
         await WriteAsync(stream, cancellationToken).ConfigureAwait(false);
     }
 }
예제 #14
0
        public void Export(string filter, MagickFormat format)
        {
            SaveFileDialog save = new SaveFileDialog
            {
                Filter = filter + "|All Files (*.*)|*.*"
            };

            if (save.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (format == MagickFormat.Png32 && currentFile.Format == TextureFormat.ARGB32 ||
                format == MagickFormat.Jpeg && currentFile.Format == TextureFormat.ARGB32 ||
                format == MagickFormat.Dds && (currentFile.Format == TextureFormat.DXT1 || currentFile.Format == TextureFormat.DXT5))
            {
                File.WriteAllBytes(save.FileName, currentFile.Data);
                return;
            }

            using (MagickImage image = new MagickImage(currentFile.Data))
                using (Stream stream = save.OpenFile())
                {
                    image.Format = format;

                    image.Write(stream);
                }
        }
예제 #15
0
        public void Save(string file, string ext = ".png", MagickFormat format = MagickFormat.Unknown)
        {
            if (ValidCurrent)
            {
                try
                {
                    var e = Path.GetExtension(file);
                    if (string.IsNullOrEmpty(e))
                    {
                        file = $"{file}{ext}";
                    }

                    FixDPI();

                    if (e.Equals(".png8", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Current.Write(Path.ChangeExtension(file, ".png"), MagickFormat.Png8);
                    }
                    else
                    {
                        Current.Write(file, format);
                    }
                }
                catch (Exception ex) { ex.ShowMessage(); }
            }
        }
예제 #16
0
        static public List <Stream> AsImagesToListOfStreams(string fileName, MagickFormat imageExtension)
        {
            List <Stream> pages = new List <Stream>();

            var settings = new MagickReadSettings();

            settings.Density = new Density(300, 300);

            using (var images = new MagickImageCollection())
            {
                images.Read(fileName, settings);

                int page = 1;
                foreach (var image in images)
                {
                    Stream memoryStream = new MemoryStream();
                    image.Format = imageExtension;
                    image.Write(memoryStream);
                    pages.Add(memoryStream);

                    page++;
                }
            }
            return(pages);
        }
예제 #17
0
 public static void SaveImage(MagickImage image, string destination, int quality = 95, ImageInformation exif = null,
                              MagickFormat format = MagickFormat.Jpeg)
 {
     using (var stream = File.Open(destination, FileMode.Create, FileAccess.ReadWrite)) {
         SaveImage(image, stream, quality, exif, format);
     }
 }
                private static bool ShouldReport(MagickFormat format)
                {
                    if (IsDisabledThroughPolicy(format))
                    {
                        return(false);
                    }

                    if (!OperatingSystem.IsWindows)
                    {
                        if (format == MagickFormat.Clipboard || format == MagickFormat.Emf || format == MagickFormat.Wmf)
                        {
                            return(false);
                        }
                    }

                    if (OperatingSystem.IsMacOS)
                    {
                        if (format == MagickFormat.Jxl)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }
예제 #19
0
        public static MagickFormat ParseMagickFormatFromExtension(FileInfo file)
        {
            MagickFormat format = default;
            if (file.Extension != null && file.Extension.Length > 1)
                format = Parse(file.Extension.Substring(1), MagickFormat.Unknown);

            return format;
        }
예제 #20
0
 private void TransformImage(Stream stream, MagickFormat format)
 {
     using (MagickImage image = new MagickImage(HttpContext.Server.MapPath("~/test.png")))
     {
         image.Format = format;
         image.Write(stream, format);
     }
 }
    /// <summary>
    /// Converts the file data from the specified format
    /// </summary>
    /// <param name="inputFormat">The format to convert from</param>
    /// <param name="outputFormat">The format to convert to</param>
    /// <param name="inputStream">The input file data stream to convert from</param>
    /// <param name="outputStream">The output stream for the converted data</param>
    public void ConvertFrom(FileExtension inputFormat, MagickFormat outputFormat, ArchiveFileStream inputStream, ArchiveFileStream outputStream)
    {
        // Get the image in specified format
        using MagickImage img = new(inputStream.Stream, GetMagickFormat(inputFormat.FileExtensions));

        // Write to stream as native format
        img.Write(outputStream.Stream, outputFormat);
    }
예제 #22
0
        /// <summary>
        /// Writes the image to the specified file.
        /// </summary>
        /// <param name="file">The file to write the image to.</param>
        /// <param name="format">The format to use.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <exception cref="MagickException">Thrown when an error is raised by ImageMagick.</exception>
        public Task WriteAsync(FileInfo file, MagickFormat format, CancellationToken cancellationToken)
        {
            Throw.IfNull(nameof(file), file);

            var bytes = ToByteArray(format);

            return(File.WriteAllBytesAsync(file.FullName, bytes, cancellationToken));
        }
예제 #23
0
 public DataSpan Recompress(DataSpan imageData, MagickFormat format = MagickFormat.Jpeg)
 {
     using (var img = new MagickImage(imageData.FullBufferRef))
     {
         img.Format = format;
         return(new DataSpan(img.ToByteArray()));
     }
 }
예제 #24
0
        private static void CheckFormat(MagickImage image)
        {
            MagickFormat format = image.FormatInfo.Module;

            if (format != MagickFormat.Png)
            {
                throw new MagickCorruptImageErrorException("Invalid image format: " + format.ToString());
            }
        }
예제 #25
0
        /// <summary>
        /// Returns the format information of the specified format.
        /// </summary>
        /// <param name="format">The image format.</param>
        /// <returns>The format information.</returns>
        public static MagickFormatInfo Create(MagickFormat format)
        {
            if (!_All.ContainsKey(format))
            {
                return(null);
            }

            return(_All[format]);
        }
예제 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MagickDefine"/> class.
        /// </summary>
        /// <param name="format">The format of the define.</param>
        /// <param name="name">The name of the define.</param>
        /// <param name="value">The value of the define.</param>
        public MagickDefine(MagickFormat format, string name, string value)
        {
            Throw.IfNullOrEmpty(nameof(name), name);
            Throw.IfNullOrEmpty(nameof(value), value);

            Format = format;
            Name   = name;
            Value  = value;
        }
예제 #27
0
 /// <summary>
 /// Save as image file
 /// </summary>
 /// <param name="srcFileName">Source filename to save</param>
 /// <param name="destFileName">Destination filename</param>
 /// <param name="format">New image format</param>
 /// <param name="quality">JPEG/MIFF/PNG compression level</param>
 public static async Task SaveAsync(string srcFileName, string destFileName, MagickFormat format = MagickFormat.Unknown, int quality = 100)
 {
     await Task.Run(() => {
         using (var imgM = new MagickImage(srcFileName)) {
             imgM.Quality = quality;
             imgM.Write(destFileName, format);
         }
     }).ConfigureAwait(false);
 }
예제 #28
0
        public static void CheckFormat(IMagickImage image, MagickFormat expectedFormat)
        {
            MagickFormat format = image.FormatInfo.Module;

            if (format != expectedFormat)
            {
                throw new MagickCorruptImageErrorException("Invalid image format: " + format.ToString());
            }
        }
예제 #29
0
        private static MagickFormat CheckFormat(MagickFormat format)
        {
            if (!AllowedFormats.Contains(format))
            {
                throw new ArgumentException("The specified format is not a video format.", nameof(format));
            }

            return(format);
        }
예제 #30
0
        public static void CheckFormat(IMagickImage <QuantumType> image, MagickFormat expectedFormat)
        {
            var format = image.FormatInfo?.ModuleFormat;

            if (format != expectedFormat)
            {
                throw new MagickCorruptImageErrorException("Invalid image format: " + format.ToString());
            }
        }
예제 #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MagickDefine"/> class.
 /// </summary>
 /// <param name="format">The format of the define.</param>
 /// <param name="name">The name of the define.</param>
 /// <param name="value">The value of the define.</param>
 public MagickDefine(MagickFormat format, string name, string value)
 {
   Format = format;
   Name = name;
   Value = value;
 }
예제 #32
0
 /// <summary>
 /// Returns the format information of the specified format.
 /// </summary>
 /// <param name="format">The image format.</param>
 /// <returns>The format information.</returns>
 public static MagickFormatInfo GetFormatInformation(MagickFormat format)
 {
   return MagickFormatInfo.Create(format);
 }
예제 #33
0
 /// <summary>
 /// Creates a define string for the specified format and name.
 /// </summary>
 /// <param name="format">The format to set the define for.</param>
 /// <param name="name">The name of the define.</param>
 /// <returns>A string for the specified format and name.</returns>
 protected static string ParseDefine(MagickFormat format, string name)
 {
   if (format == MagickFormat.Unknown)
     return name;
   else
     return EnumHelper.GetName(GetModule(format)) + ":" + name;
 }
예제 #34
0
 private static MagickFormat GetModule(MagickFormat format)
 {
   MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(format);
   return formatInfo.Module;
 }
예제 #35
0
    ///<summary>
    /// Sets a format-specific option.
    ///</summary>
    ///<param name="format">The format to set the option for.</param>
    ///<param name="name">The name of the option.</param>
    ///<param name="value">The value of the option.</param>
    public void SetDefine(MagickFormat format, string name, string value)
    {
      Throw.IfNullOrEmpty("name", name);
      Throw.IfNull("value", value);

      _Defines.Add(new MagickDefine(format, name, value));
    }
예제 #36
0
    /// <summary>
    /// Removes the define with the specified name.
    /// </summary>
    /// <param name="format">The format to set the define for.</param>
    /// <param name="name">The name of the define.</param>
    public void RemoveDefine(MagickFormat format, string name)
    {
      Throw.IfNullOrEmpty(nameof(name), name);

      string key = ParseDefine(format, name);
      if (_Options.ContainsKey(key))
        _Options.Remove(key);
    }
예제 #37
0
 public void SetDefine(MagickFormat format, string name, bool flag)
 {
   SetDefine(format, name, flag ? "true" : "false");
 }
예제 #38
0
    /// <summary>
    /// Sets a format-specific option.
    /// </summary>
    /// <param name="format">The format to set the option for.</param>
    /// <param name="name">The name of the option.</param>
    /// <param name="value">The value of the option.</param>
    public void SetDefine(MagickFormat format, string name, string value)
    {
      Throw.IfNullOrEmpty(nameof(name), name);
      Throw.IfNull(nameof(value), value);

      SetOption(ParseDefine(format, name), value);
    }
예제 #39
0
 ///<summary>
 /// Returns the format information of the specified format.
 ///</summary>
 ///<param name="format">The image format.</param>
 public static MagickFormatInfo GetFormatInformation(MagickFormat format)
 {
   return MagickFormatInfo.Create(Wrapper.MagickNET.GetFormatInformation(format));
 }
예제 #40
0
    /// <summary>
    /// Returns the value of a format-specific option.
    /// </summary>
    /// <param name="format">The format to get the option for.</param>
    /// <param name="name">The name of the option.</param>
    /// <returns>The value of a format-specific option.</returns>
    public string GetDefine(MagickFormat format, string name)
    {
      Throw.IfNullOrEmpty(nameof(name), name);

      return GetOption(ParseDefine(format, name));
    }
		public static MagickFormatInfo GetFormatInformation(MagickFormat format)
		{
			object result;
			try
			{
				result = Types.GraphicsMagickNET.CallMethod("GetFormatInformation", new Type[] {Types.MagickFormat}, format);
			}
			catch (Exception ex)
			{
				throw ExceptionHelper.Create(ex);
			}
			return (result == null ? null : new MagickFormatInfo(result));
		}