예제 #1
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);
            }
        }
예제 #2
0
        /// <inheritdoc/>
        protected override string GetFileName(HttpContext context)
        {
            MagickFormat format        = ImageData.FormatInfo.Format;
            string       cacheFileName = GetCacheFileName("Optimized", format.ToString(), format);

            if (!CanUseCache(cacheFileName))
            {
                CreateOptimizedFile(cacheFileName);
            }

            return(cacheFileName);
        }
예제 #3
0
        static public void AsImagesToFiles(string fileName, MagickFormat imageExtension)
        {
            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)
                {
                    image.Format = imageExtension;
                    image.Write($"{fileName}.Page{page.ToString()}.{imageExtension.ToString().ToLower()}");
                    page++;
                }
            }
        }
예제 #4
0
        private static void CheckFormat(MagickImage image)
        {
            MagickFormat format = image.FormatInfo.Module;

            if (format != MagickFormat.Png)
            {
                throw new MagickCorruptImageErrorException("Invalid image format: " + format.ToString());
            }
        }
예제 #5
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());
            }
        }
예제 #6
0
 public static string MagickFormatToImageType(MagickFormat format)
 => _magickFormatMap.TryGetValue(format, out var imageType) ? imageType : format.ToString();
예제 #7
0
 public void Write()
 {
     image.Write("lossyimage." + defaultFormat.ToString().ToLower());
 }
        public async Task <Boolean> Run(
            String pathToFile,
            CreatePdfImageTaskParams createPdfImageTaskParams,
            Func <int, Stream, Task <Boolean> > pageWriter)
        {
            String tempFileName = null;

            if (Passwords.Count > 0)
            {
                tempFileName =
                    Path.Combine(Path.GetDirectoryName(pathToFile),
                                 Path.GetFileNameWithoutExtension(pathToFile) + "_decrypted.pdf");
                if (Decryptor.DecryptFile(pathToFile, tempFileName, Passwords))
                {
                    pathToFile = tempFileName;
                }
            }
            using (var sourceStream = File.OpenRead(pathToFile))
            {
                var settings = new MagickReadSettings
                {
                    Density = new PointD(createPdfImageTaskParams.Dpi, createPdfImageTaskParams.Dpi)
                };
                settings.FrameIndex = 0; // First page
                settings.FrameCount = 1; // Number of pages
                MagickFormat imageFormat = TranslateFormat(createPdfImageTaskParams.Format);

                Logger.DebugFormat("Image format is {0}", imageFormat.ToString());
                using (var images = new MagickImageCollection())
                {
                    bool done = false;
                    if (!_firstDone)
                    {
                        lock (LockForInitializationIssue)
                        {
                            if (!_firstDone)
                            {
                                images.Read(sourceStream, settings);
                                done = true;
                            }
                        }
                    }

                    if (!done)
                    {
                        images.Read(sourceStream, settings);
                    }

                    var lastImage =
                        Math.Min(createPdfImageTaskParams.FromPage - 1 + createPdfImageTaskParams.Pages, images.Count) -
                        1;
                    for (int page = createPdfImageTaskParams.FromPage - 1; page <= lastImage; page++)
                    {
                        var image = images[page];
                        image.Format = imageFormat;

                        using (var ms = new MemoryStream())
                        {
                            image.Write(ms);
                            ms.Seek(0L, SeekOrigin.Begin);
                            await pageWriter(page + 1, ms).ConfigureAwait(false);
                        }
                    }
                }
            }
            if (!String.IsNullOrEmpty(tempFileName) && File.Exists(tempFileName))
            {
                File.Delete(tempFileName);
            }
            return(true);
        }
예제 #9
0
        public static void ImageMagickConvert(Stream src, Stream dst,
                                              MagickFormat srcFormat, int srcWidth, int srcHeight, int srcDepth,
                                              MagickFormat dstFormat, int dstWidth = -1, int dstHeight = -1)
        {
            if (Environment.OSVersion.Platform == PlatformID.Unix ||
                Environment.OSVersion.Platform == PlatformID.MacOSX)
            {
                try
                {
                    var args = "";
                    if (dstWidth != -1 && dstHeight != -1 && (dstWidth != srcWidth || dstHeight != srcHeight))
                    {
                        args += $"-resize {dstWidth}x{dstHeight}! ";
                    }

                    if (srcFormat == MagickFormat.Bgra || srcFormat == MagickFormat.Bgr || srcFormat == MagickFormat.Rgba)
                    {
                        args += $"-size {srcWidth}x{srcHeight} -depth {srcDepth} ";
                    }

                    var processStart = new ProcessStartInfo
                    {
                        FileName               = "convert",
                        Arguments              = $"{args}{srcFormat.ToString().ToLower()}:- {dstFormat.ToString().ToLower()}:-",
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        CreateNoWindow         = true,
                        UseShellExecute        = false
                    };

                    var process = Process.Start(processStart);

                    src.CopyTo(process.StandardInput.BaseStream);
                    process.StandardInput.Close();

                    while (!process.HasExited || !process.StandardOutput.EndOfStream)
                    {
                        process.StandardOutput.BaseStream.CopyTo(dst);
                        process.WaitForExit(1);
                    }
                }
                catch
                {
                    // TODO, handle gracefully
                }
            }
            else
            {
                var readSettings = new MagickReadSettings
                {
                    Format = srcFormat
                };

                if (srcFormat == MagickFormat.Bgra || srcFormat == MagickFormat.Rgba || srcFormat == MagickFormat.Bgr)
                {
                    readSettings.PixelStorage = new PixelStorageSettings
                    {
                        Mapping     = srcFormat.ToString().ToUpper(),
                        StorageType = srcDepth == 8 ? StorageType.Char : StorageType.Short
                    };

                    readSettings.Width  = srcWidth;
                    readSettings.Height = srcHeight;
                }

                using (var image = new MagickImage(src, readSettings))
                {
                    if (dstWidth != -1 && dstHeight != -1)
                    {
                        image.Resize(new MagickGeometry(dstWidth, dstHeight)
                        {
                            IgnoreAspectRatio = true
                        });
                    }

                    image.Write(dst, dstFormat);
                }
            }
        }
        private void Save(IMagickImage image, string device, string uploadPath, string identifier, MagickFormat format, int?size = null)
        {
            image.Format = format;

            if (size != null)
            {
                image.Resize(new MagickGeometry()
                {
                    Width             = size.Value,
                    IgnoreAspectRatio = false
                });
            }

            string path = Path.Combine(uploadPath, String.Format("{0}-{1}.{2}", identifier, device, format.ToString()));

            image.Write(path);

            if (format == MagickFormat.Jpg)
            {
                Compress(path);
            }
        }
예제 #11
0
 public static string ImageExt(this MagickFormat format)
 {
     return($".{format.ToString().ToLower()}");
 }