Пример #1
0
        public void TestCompressToWebP()
        {
            WebPFormat webP    = new WebPFormat();
            var        srcPath = @"C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg";

            //using (System.IO.FileStream fs = new System.IO.FileStream(,
            //    System.IO.FileMode.Open, System.IO.FileAccess.Read))
            //{
            Image img = Image.FromFile(srcPath);

            //var image = webP.Load(fs);

            for (int i = 10; i <= 100; i += 10)
            {
                webP.Quality = i;
                webP.Save(@"C:\Users\Public\Pictures\Sample Pictures\Compress-" + i + ".webp", img, 4);
            }

            for (int i = 90; i <= 99; i += 1)
            {
                webP.Quality = i;
                webP.Save(@"C:\Users\Public\Pictures\Sample Pictures\90-99\Compress-" + i + ".webp", img, 4);
            }
            //}
        }
Пример #2
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;
             }
         }
     }
 }
Пример #3
0
        public static void ToWebP(Image inputImage, string outputImage, Size?size = null)
        {
            if (inputImage == null)
            {
                return;
            }

            size = size ?? new Size(inputImage.Width, inputImage.Height);

            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new WebPFormat();

            using (FileStream outStream = new FileStream(outputImage, FileMode.Create))
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(true))
                {
                    var resizeLayer = new ResizeLayer((Size)size, ResizeMode.Stretch);

                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(inputImage)
                    .Format(format)
                    .Resize(resizeLayer)
                    .Save(outStream);
                }
                // Do something with the stream.
            }
        }
Пример #4
0
        internal static void ConvertToWebP(string inputPath, string outputPath, int imageQualityPercentage)
        {
            ISupportedImageFormat webpFormat = new WebPFormat {
                Quality = imageQualityPercentage
            };

            ConvertImageToWebP(inputPath, outputPath, webpFormat);
        }
Пример #5
0
        private void ConvertToWebP(string path)
        {
            ISupportedImageFormat webpFormat = new WebPFormat {
                Quality = 100
            };

            ConvertImageToWebP(path, webpFormat);
        }
        /// <inheritdoc />
        public override async Task InvokeAsync(ILoadingContext <ImageSource> context, LoadingPipeDelegate <ImageSource> next, CancellationToken cancellationToken = default)
        {
            if (context.Current is Stream stream)
            {
                if (!stream.CanSeek)
                {
                    var memoryStream = new MemoryStream();
                    await stream.CopyToAsync(memoryStream);

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    stream = memoryStream;
                }

                var isWebP = IsWebP(stream);

                var tcs = new TaskCompletionSource <ImageSource>();
                await Task.Run(() =>
                {
                    Image webPImage = null;
                    if (isWebP)
                    {
                        var webPFormat = new WebPFormat();
                        webPImage      = webPFormat.Load(stream);
                    }

                    if (webPImage != null)
                    {
                        var webPMemoryStream = new MemoryStream();
                        webPImage.Save(webPMemoryStream, ImageFormat.Png);
                        stream = webPMemoryStream;
                    }

                    stream.Seek(0, SeekOrigin.Begin);

                    try
                    {
                        var bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = stream;
                        bitmap.EndInit();
                        bitmap.Freeze();
                        context.UIContext.Send(state =>
                        {
                            context.AttachSource(bitmap);
                        }, null);
                        tcs.SetResult(bitmap);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                }, cancellationToken);

                context.Current = await tcs.Task;
            }

            await next(context, cancellationToken);
        }
Пример #7
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);
                }
            }
        }
Пример #8
0
        public void ExtractArchive()
        {
            var archive = ArchiveFactory.Open(filepath);

            temp_dir = GetTemporaryDirectory();
            foreach (var entry in archive.Entries)
            {
                if (!entry.IsDirectory)
                {
                    string ek = entry.Key.ToLower();

                    if (entry.Key.ToLower().StartsWith("zz"))
                    {
                        continue;
                    }

                    file_base = Path.GetFileNameWithoutExtension(entry.Key);
                    MemoryStream memStream = new MemoryStream();
                    entry.WriteTo(memStream);
                    //Page temp_page = new Page(memStream, entry.Key);
                    //orig_pages.Add(temp_page);
                    ISupportedImageFormat format = new WebPFormat {
                        Quality = 80
                    };
                    ImageFactory image = new ImageProcessor.ImageFactory();
                    try
                    {
                        image.Load(memStream.ToArray())
                        .Format(format)
                        .Save(converted);
                    }
                    catch {
                        continue;
                    }
                    string filename = Path.Combine(temp_dir, file_base + ".webp");
                    using (System.IO.FileStream output = new System.IO.FileStream(filename, FileMode.Create)) {
                        converted.CopyTo(output);
                        memStream.Dispose();
                        output.Close();
                    }
                }
            }
            CompressArchive();
        }
Пример #9
0
        public void GenerateWebP()
        {
            var st = new StackFrame(1);

            Console.WriteLine($"{st.GetMethod().DeclaringType.FullName}.{st.GetMethod().Name}");
            Console.WriteLine();

            var encoder     = new WebPFormat();
            var fileName    = "Testing.jpg";
            var outFileName = "Testing.webp";

            File.Delete(outFileName);

            using (Stream BitmapStream = File.Open(fileName, FileMode.Open))
            {
                Image img = Image.FromStream(BitmapStream);
                encoder.Save(new FileStream(outFileName, FileMode.Create), img, 1);
            }
        }
Пример #10
0
        public static void ToWebP(string inputFile, string outputFile)
        {
            byte[] photoBytes = File.ReadAllBytes(inputFile);
            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new WebPFormat();

            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (FileStream outStream = new FileStream(outputFile, FileMode.Create))
                {
                    // 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)
                        .Format(format)
                        .Save(outStream);
                    }
                    // Do something with the stream.
                }
            }
        }
Пример #11
0
 public void Process(GetMediaStreamPipelineArgs args)
 {
     Sitecore.Diagnostics.Log.Debug("::WEBP:: enabled:" + (args.Options.CustomOptions.ContainsKey("webp") || args.Options.CustomOptions["webp"] == "1").ToString(), this);
     Assert.ArgumentNotNull(args, "args");
     if (!ShouldSkip(args))
     {
         Sitecore.Diagnostics.Log.Debug("::WEBP:: converting " + args.MediaData.MediaItem.InnerItem.Paths.Path, this);
         ISupportedImageFormat format = new WebPFormat()
         {
             Quality = Sitecore.Configuration.Settings.GetIntSetting("Media.Resizing.Quality", 70)
         };
         MemoryStream outstream = new MemoryStream();
         using (Stream stream = args.MediaData.MediaItem.GetMediaStream())
         {
             using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
             {
                 imageFactory.Load(stream).Format(format).Save(outstream);
                 args.OutputStream = new MediaStream(outstream, "webp", args.MediaData.MediaItem);
                 args.OutputStream.Headers.Headers["Content-Type"] = "image/webp";
             }
         }
     }
 }
Пример #12
0
        public static Bitmap loadBitmap(string path, string extension, int sizeX = -1, int sizeY = -1)
        {
            Bitmap bitmap;

            if (extension == ".webp")
            {
                WebPFormat webpDecoder = new WebPFormat();
                bitmap = (Bitmap)webpDecoder.Load(File.Open(path, FileMode.Open));
            }

            else
            {
                if (sizeX == -1 || sizeY == -1)
                {
                    bitmap = new Bitmap(Image.FromFile(path), new Size(Settings.Accuracy, Settings.Accuracy));
                }
                else
                {
                    bitmap = new Bitmap(Image.FromFile(path), new Size(sizeX, sizeY));
                }
            }

            return(bitmap);
        }
Пример #13
0
        [HttpPost("upload")] //Postback

        public async Task <IActionResult> Post(IFormFile file)
        {
            //--------< Upload_ImageFile() >--------

            //< check >

            if (file == null || file.Length == 0)
            {
                return(Content("file not selected"));
            }

            //</ check >



            //< get Path >

            string imagesPath   = Path.Combine(_appEnvironment.WebRootPath, "images");
            string webPFileName = Path.GetFileNameWithoutExtension(Uri.EscapeDataString(file.FileName)) + ".webp";
            string pngFileName  = Path.GetFileNameWithoutExtension(Uri.EscapeDataString(file.FileName)) + ".png";
            string jpgFileName  = Path.GetFileNameWithoutExtension(Uri.EscapeDataString(file.FileName)) + ".jpg";

            string webPImagePath = Path.Combine(imagesPath, webPFileName);
            string pngImagePath  = Path.Combine(imagesPath, pngFileName);
            string jpgImagePath  = Path.Combine(imagesPath, jpgFileName);


            //</ get Path >



            //< Copy File to Target >
            ISupportedImageFormat jepgformat = new JpegFormat();
            ISupportedImageFormat weformat   = new WebPFormat {
                Quality = 30
            };

            /*
             *
             * using (FileStream webPFileStream = new FileStream(webPImagePath, FileMode.Create))
             * {
             *  using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false, fixGamma: false))
             *  {
             *
             *      imageFactory.Load(file.OpenReadStream())
             *                  .AutoRotate()
             *                  .Format(weformat)
             *                  .Save(webPFileStream);
             *
             *
             *  }
             * }
             */

            using (FileStream jpgFileStream = new FileStream(jpgImagePath, FileMode.Create))
            {
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false, fixGamma: false))
                {
                    imageFactory.Load(file.OpenReadStream())
                    .AutoRotate()
                    .Format(jepgformat)
                    .Save(jpgFileStream);
                }
            }

            //</ Copy File to Target >



            //< output >



            return(Ok(jpgFileName));
        }
Пример #14
0
        private void ThreadedFileMove(object o)
        {
            if (o.GetType() != typeof(string[]))
            {
                return;
            }
            string[] fromTo = o as string[];
            if (fromTo.Length != 2)
            {
                return;
            }

            lock (FileMoveLock)
            {
                try
                {
                    if (File.Exists(fromTo[0]) && !File.Exists(fromTo[1]))
                    {
                        if (fromTo[0].EndsWith(".jfif"))
                        {
                            var jfif       = Image.FromFile(fromTo[0]);
                            var targetPath = fromTo[1].Substring(0, fromTo[1].LastIndexOf('.')) + ".jpeg";
                            jfif.Save(targetPath, ImageFormat.Jpeg);
                            jfif.Dispose();
                            File.Delete(fromTo[0]);
                        }
                        else if (fromTo[0].EndsWith(".webp"))
                        {
                            lock (PictureConversionLock)
                            {
                                var stream = new FileStream(fromTo[0], FileMode.Open);
                                try
                                {
                                    var webp       = new WebPFormat().Load(stream);
                                    var targetPath = fromTo[1].Substring(0, fromTo[1].LastIndexOf('.')) + ".jpeg";
                                    webp.Save(targetPath, ImageFormat.Jpeg);
                                    webp.Dispose();
                                    stream.Dispose();
                                    File.Delete(fromTo[0]);
                                }
                                catch
                                {
                                    stream.Dispose();
                                    File.Move(fromTo[0], fromTo[1]);
                                }
                            }
                        }
                        else if (fromTo[0].EndsWith(".jpg_large"))
                        {
                            File.Move(fromTo[0], fromTo[1].Split('_').Reverse().Skip(1).Reverse().Combine("_"));
                        }
                        else if (fromTo[0].EndsWith(".crdownload") || fromTo[0].EndsWith(".opdownload"))
                        {
                            return;
                        }
                        else
                        {
                            File.Move(fromTo[0], fromTo[1]);
                        }

                        // Display toast
                        new Process()
                        {
                            StartInfo = new ProcessStartInfo("toast.exe", $"-h \"Downloaded File\" -m \"{Path.GetFileNameWithoutExtension(fromTo[1])}\" " +
                                                             $"-f \"To {fromTo[1]}\" -n \"DownloadFolderSorter\"")
                            {
                                UseShellExecute = false, CreateNoWindow = true
                            }
                        }.Start();
                    }
                }
                catch { }
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            if (args.Length >= 3)
            {
                string pngPath      = args[0];
                string assetsFolder = args[1];
                string stickerPack  = args[2];

                // Are the argument file and folder valid?
                if (!File.Exists(pngPath) || !Directory.Exists(assetsFolder))
                {
                    Console.WriteLine("[ ! ] Invalid argument");
                    return;
                }

                // Acquire file name without extension and the folder where the converted sticker should be stored
                string baseName = Path.GetFileName(pngPath);
                baseName = baseName.Substring(0, baseName.LastIndexOf('.'));
                string webpFolder = Path.Combine(assetsFolder, stickerPack);

                Console.WriteLine("[ * ] Generating sticker from: {0}", pngPath);

                // Is a PNG?
                if (!pngPath.EndsWith(".png"))
                {
                    Console.WriteLine("[ ! ] File is not a PNG");
                    return;
                }

                // Is a 512x512 image?
                using (var image = System.Drawing.Image.FromFile(pngPath))
                {
                    if (image.Width != 512 || image.Height != 512)
                    {
                        Console.WriteLine("[ ! ] Invalid sticker size, should be 512x512");
                        return;
                    }
                }

                string tmpPath = Path.Combine(webpFolder, baseName + ".tmp");

                // Optimize PNG image
                var compressor = new PNGCompressor();
                compressor.CompressImageLossy(pngPath, tmpPath);

                // Convert to WebP
                var newName = baseName + ".webp";
                using (var imageFactory = new ImageFactory(preserveExifData: false))
                {
                    ISupportedImageFormat webp = new WebPFormat {
                        Quality = 75
                    };
                    imageFactory.Load(tmpPath);
                    imageFactory.Format(webp);
                    imageFactory.Save(Path.Combine(webpFolder, newName));
                }

                Console.WriteLine("[ * ] Saved WebP to: {0}", webpFolder);

                // Delete compressed temporary file
                if (File.Exists(tmpPath))
                {
                    File.Delete(tmpPath);
                }

                // Add to JSON
                JObject stickerJson = JObject.Parse(File.ReadAllText(Path.Combine(assetsFolder, "contents.json")));
                foreach (var pack in stickerJson["sticker_packs"])
                {
                    if (pack["identifier"].ToString() == stickerPack)
                    {
                        JObject sticker = new JObject();
                        sticker["image_file"] = newName;
                        sticker["emojis"]     = new JArray();

                        JArray stickers = (JArray)pack["stickers"];
                        stickers.Add(sticker);
                    }
                }
                File.WriteAllText(Path.Combine(assetsFolder, "contents.json"), stickerJson.ToString());
            }
            else
            {
                Console.WriteLine(".\\ZapArtist.exe <png image> <asset folder> <sticker pack>");
            }
        }
            //ExEnd:SourceWebPFilePath

            /// <summary>
            /// Reads metadata from WebP file
            /// </summary> 
            public static void GetMetadataProperties()
            {
                try
                {
                    //ExStart:GetMetadatPropertiesInWebP

                    // initialize WebPFormat class
                    WebPFormat webPFormat = new WebPFormat(Common.MapSourceFilePath(webPFilePath));

                    // get width
                    int width = webPFormat.Width;

                    // get height
                    int height = webPFormat.Height;

                    //display height and width in console
                    Console.Write("Width: {0}, Height: {1}", width, height);
                    //ExEnd:GetMetadatPropertiesInWebP
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp.Message);
                }
            }