コード例 #1
0
ファイル: Navigation.cs プロジェクト: aihuyisheng/PicView
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async void Pic(int index)
        {
#if DEBUG
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            // Declare variable to be used to set image source
            BitmapSource bitmapSource;

            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                if (bitmapSource == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }

            /// Retrieve from preloader if available
            /// if not, it will be null
            bitmapSource = Preloader.Get(Pics[index]);

            // Initate loading behavior, if needed
            if (bitmapSource == null)
            {
                // Set loading from translation service
                SetLoadingString();

                // Show a thumbnail while loading
                var thumb = GetThumb(index, true);
                if (thumb != null && Properties.Settings.Default.PicGallery != 2)
                {
                    // Don't allow image size to stretch the whole screen
                    if (xWidth == 0)
                    {
                        ConfigureWindows.GetMainWindow.MainImage.Width  = ConfigureWindows.GetMainWindow.MinWidth;
                        ConfigureWindows.GetMainWindow.MainImage.Height = ConfigureWindows.GetMainWindow.MinHeight;
                    }
                    else
                    {
                        ConfigureWindows.GetMainWindow.MainImage.Width  = xWidth;
                        ConfigureWindows.GetMainWindow.MainImage.Height = xHeight;
                    }

                    ConfigureWindows.GetMainWindow.MainImage.Source = thumb;
                }

                // Dissallow changing image while loading
                CanNavigate = false;

                // Get it!
                await Preloader.Add(Pics[index]).ConfigureAwait(true);

                // Retry
                bitmapSource = Preloader.Get(Pics[index]);

                if (bitmapSource == null)
                {
                    // If pic is still null, image can't be rendered
                    bitmapSource = ImageDecoder.ImageErrorMessage();
                }
            }

            // Need to put UI change in dispatcher to fix slideshow bug
            await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (Action)(() =>
            {
                // Scroll to top if scroll enabled
                if (IsScrollEnabled)
                {
                    ConfigureWindows.GetMainWindow.Scroller.ScrollToTop();
                }

                // Reset transforms if needed
                if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
                {
                    UILogic.TransformImage.Rotation.Flipped = false;
                    UILogic.TransformImage.Rotation.Rotateint = 0;
                    GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                    ConfigureWindows.GetMainWindow.MainImage.LayoutTransform = null;
                }

                ConfigureWindows.GetMainWindow.MainImage.Source = bitmapSource;
                FitImage(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
                SetTitleString(bitmapSource.PixelWidth, bitmapSource.PixelHeight, index);
            }));

            // Update values
            CanNavigate  = true;
            FolderIndex  = index;
            FreshStartup = false;

            if (ConfigureWindows.GetImageInfoWindow != null)
            {
                if (ConfigureWindows.GetImageInfoWindow.IsVisible)
                {
                    ConfigureWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            RecentFiles.Add(Pics[index]);

#if DEBUG
            stopWatch.Stop();
            var s = $"Pic(); executed in {stopWatch.Elapsed.TotalMilliseconds} milliseconds";
            Trace.WriteLine(s);
#endif
        }
コード例 #2
0
 public Bitmap GetImage()
 {
     return(ImageDecoder.DecodeImage(_file));
 }
コード例 #3
0
        public async Task ExecuteSelectFile(FileModel model)
        {
            if (model == null)
            {
                return;
            }

            if (State is DockState.AutoHidden or DockState.Hidden)
            {
                return;
            }

            if (_settingsManager.ShowFilePreview)
            {
                PE_SelectedItem = model;
            }
            else
            {
                return;
            }

            PE_MeshPreviewVisible = false;
            IsAudioPreviewVisible = false;
            IsImagePreviewVisible = false;
            IsVideoPreviewVisible = false;

            // check additional changes
            if (model.IsDirectory)
            {
                return;
            }

            if (PE_SelectedItem == null)
            {
                return;
            }
            // string.Equals(model.GetExtension(), ERedExtension.bk2.ToString(), StringComparison.OrdinalIgnoreCase) ||
            if (!(string.Equals(model.GetExtension(), ERedExtension.mesh.ToString(), StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(model.GetExtension(), ERedExtension.wem.ToString(), StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(model.GetExtension(), ERedExtension.xbm.ToString(), StringComparison.OrdinalIgnoreCase) ||
                  Enum.TryParse <EConvertableOutput>(PE_SelectedItem.GetExtension(), out _) ||
                  Enum.TryParse <EUncookExtension>(PE_SelectedItem.GetExtension(), out _)
                  )
                )
            {
                return;
            }

            if (PE_SelectedItem != null)
            {
                if (PE_SelectedItem.GetExtension().Length > 0)
                {
                    //if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.bk2.ToString(),
                    //   System.StringComparison.OrdinalIgnoreCase))
                    //{
                    //    IsVideoPreviewVisible = true;
                    //    SetExeCommand?.Invoke("test.exe | test2.bk2 /J /I2 /P");
                    //}


                    if (Enum.IsDefined(typeof(EConvertableOutput), PE_SelectedItem.GetExtension()))
                    {
                        PE_MeshPreviewVisible = true;

                        LoadModel(PE_SelectedItem.FullName);
                    }



                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.mesh.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        PE_MeshPreviewVisible = true;
                        using (var meshStream = new FileStream(PE_SelectedItem.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            meshStream.Seek(0, SeekOrigin.Begin);
                            string outPath = Path.Combine(ISettingsManager.GetManagerCacheDir(), "Temp_OBJ", Path.GetFileName(PE_SelectedItem.FullName));
                            outPath = Path.ChangeExtension(outPath, ".glb");
                            if (_meshTools.ExportMeshPreviewer(meshStream, new FileInfo(outPath)))
                            {
                                LoadModel(outPath);
                            }
                            meshStream.Dispose();
                            meshStream.Close();
                        }
                    }

                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.wem.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        IsAudioPreviewVisible = true;

                        AddAudioItem(PE_SelectedItem.FullName);
                    }

                    // textures
                    if (Enum.TryParse <EUncookExtension>(PE_SelectedItem.GetExtension(),
                                                         out _))
                    {
                        IsImagePreviewVisible = true;

                        var q = await ImageDecoder.RenderToBitmapSource(PE_SelectedItem.FullName);

                        if (q != null)
                        {
                            var g = BitmapFrame.Create(q);
                            LoadImage(g);
                        }
                    }

                    // xbm
                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.xbm.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        IsImagePreviewVisible = true;

                        // convert xbm to dds stream
                        await using var ddsstream  = new MemoryStream();
                        await using var filestream = new FileStream(PE_SelectedItem.FullName,
                                                                    FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.SequentialScan);
                        _modTools.ConvertXbmToDdsStream(filestream, ddsstream, out _);

                        // try loading it in pfim
                        try
                        {
                            var qa = await ImageDecoder.RenderToBitmapSourceDds(ddsstream);

                            if (qa != null)
                            {
                                LoadImage(qa);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            DecideForMeshPreview();
        }
コード例 #4
0
ファイル: MainForm.cs プロジェクト: timgaunt/resizer
        private void OnSaveClick(object sender, EventArgs e)
        {
            if (m_fileStructure.Nodes.Count == 0)
            {
                return;
            }

            PsdFile psdFileSrc = (PsdFile)m_fileStructure.Nodes[0].Tag;


            PsdFile psdFile = new PsdFile();

            //-----------------------------------------------------------------------

            psdFile.Rows    = psdFileSrc.Rows;
            psdFile.Columns = psdFileSrc.Columns;

            // we have an Alpha channel which will be saved,
            // we have to add this to our image resources
            psdFile.Channels = 3;// 4;

            // for now we oly save the images as RGB
            psdFile.ColorMode = PsdFile.ColorModes.RGB;

            psdFile.Depth = 8;

            //-----------------------------------------------------------------------
            // no color mode Data

            //-----------------------------------------------------------------------

            psdFile.ImageResources.Clear();
            psdFile.ImageResources.AddRange(psdFileSrc.ImageResources.ToArray());

            //-----------------------------------------------------------------------

            int size = psdFile.Rows * psdFile.Columns;

            psdFile.ImageData = new byte[psdFile.Channels][];
            for (int i = 0; i < psdFile.Channels; i++)
            {
                psdFile.ImageData[i] = new byte[size];
            }

            Bitmap bmp = ImageDecoder.DecodeImage(psdFileSrc);

            for (int y = 0; y < psdFile.Rows; y++)
            {
                int rowIndex = y * psdFile.Columns;

                for (int x = 0; x < psdFile.Columns; x++)
                {
                    int pos = rowIndex + x;

                    Color pixelColor = bmp.GetPixel(x, y);

                    psdFile.ImageData[0][pos] = pixelColor.R;
                    psdFile.ImageData[1][pos] = pixelColor.G;
                    psdFile.ImageData[2][pos] = pixelColor.B;
                    //psdFile.ImageData[3][pos] = pixelColor.A;
                }
            }

            //-----------------------------------------------------------------------

            psdFile.ImageCompression = ImageCompression.Rle;

            psdFile.Save(Path.Combine(Path.GetDirectoryName(m_fileName.Text), Path.GetFileNameWithoutExtension(m_fileName.Text) + "-saved.psd"));
        }
コード例 #5
0
        private void run()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog             = new Microsoft.Win32.OpenFileDialog();
            fileDialog.DefaultExt  = "jpg";
            fileDialog.Filter      = "이미지(*.jpg; *.jpeg; *.gif; *.bmp; *.png; *.psd)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.psd";
            fileDialog.Multiselect = true;
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            Debug.WriteLine("test");
            Nullable <bool> result      = fileDialog.ShowDialog();
            var             folderesult = folderBrowserDialog.ShowDialog();

            if (result == true && folderesult == System.Windows.Forms.DialogResult.OK)
            {
                string[] tokens = Regex.Split(fileDialog.SafeFileName, @"(\.jpg|jpeg|gif|bmp|png|psd)", RegexOptions.IgnoreCase);

                if (tokens[1].ToLower().Equals("psd"))
                {
                    PsdFile psd = new PsdFile().Load(fileDialog.FileName);

                    using (var imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        Bitmap bitmap;

                        foreach (Layer layer in psd.Layers)
                        {
                            bitmap = ImageDecoder.DecodeImage(layer);
                            if (bitmap != null)
                            {
                                imageFactory.Load(bitmap).Save(string.Format(@"{0}\{1}.jpg", folderBrowserDialog.SelectedPath, layer.Name));
                                //Encoding eucKr = Encoding.GetEncoding("euc-kr");
                                //EncodingInfo[] encods = Encoding.GetEncodings();
                                //Encoding destEnc = Encoding.UTF8;
                                //using (StreamWriter file = new StreamWriter(string.Format(@"{0}\info.txt", folderBrowserDialog.SelectedPath)))
                                //{
                                //    foreach (EncodingInfo ec in encods)
                                //    {
                                //        Encoding enc = ec.GetEncoding();
                                //        byte[] sourceBytes = enc.GetBytes(layer.Name);
                                //        byte[] endBytes = Encoding.Convert(eucKr, destEnc, sourceBytes);
                                //        string info = string.Format("{0}({1}) : {2}", enc.EncodingName, enc.BodyName, destEnc.GetString(endBytes));
                                //        file.WriteLine(info);
                                //    }
                                //}

                                //byte[] byteString1 = Encoding.Default.GetBytes("테스트");
                                //byte[] byteString3 = Encoding.Default.GetBytes("layer 1");
                                //byte[] byteString2 = Encoding.Default.GetBytes(layer.Name);
                                //string layerName1 = Encoding.UTF8.GetString(byteString2);
                                //string layerName2 = Encoding.Default.GetString(byteString2);
                                //imageFactory.Load(bitmap).Save(string.Format(@"{0}\{1}.jpg", folderBrowserDialog.SelectedPath, layerName));
                            }
                        }
                    }
                }
                else
                {
                    Debug.WriteLine("No");
                }
            }
        }
コード例 #6
0
 public async Task CS_W_ImageDecoder_LoadFromPath()
 {
     var sample = await ImageDecoder.LoadFromPathAsync("ms-appx:///Car.jpg", MediaSample2DFormat.Nv12);
 }
コード例 #7
0
        /// <summary>
        /// NOT thread safe!
        /// </summary>
        /// <param name="style"></param>
        internal static async void SetWallpaper(WallpaperStyle style)
        {
            if (UILogic.ConfigureWindows.GetMainWindow.MainImage.Effect != null || Clipboard.ContainsImage())
            {
                try
                {
                    var SaveImage = ImageDecoder.GetRenderedMagickImage();
                    if (SaveImage == null)
                    {
                        return;
                    }

                    UILogic.Tooltip.ShowTooltipMessage(Application.Current.Resources["Applying"]);

                    await Task.Run(() =>
                    {
                        // Create temp directory
                        var tempPath   = Path.GetTempPath();
                        var randomName = Path.GetRandomFileName();

                        // Write temp file to it
                        using var filestream = new FileStream(tempPath + randomName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.SequentialScan);
                        SaveImage.Write(filestream);
                        SaveImage.Dispose();
                        filestream.Close();

                        // Use it
                        SetDesktopWallpaper(tempPath + randomName, style);

                        // Clean up
                        File.Delete(tempPath + randomName);
                        using var timer = new Timer(2000);
                        timer.Elapsed  += (s, x) => Directory.Delete(tempPath);
                    }).ConfigureAwait(false);

                    SaveImage.Dispose(); // Make visual studio happy
                }
                catch { }
            }
            else if (Pics.Count > 0)
            {
                if (FolderIndex < Pics.Count)
                {
                    await Task.Run(() =>
                    {
                        SetDesktopWallpaper(Pics[FolderIndex], style);
                    }).ConfigureAwait(false);
                }
            }
            else
            {
                string wallpaper = FileFunctions.GetURL(UILogic.ConfigureWindows.GetMainWindow.TitleText.Text);

                if (Uri.IsWellFormedUriString(wallpaper, UriKind.Absolute)) // Check if from web
                {
                    await Task.Run(() =>
                    {
                        // Create temp directory
                        var tempPath   = Path.GetTempPath();
                        var randomName = Path.GetRandomFileName();

                        // Download to it
                        using var webClient = new System.Net.WebClient();
                        Directory.CreateDirectory(tempPath);
                        webClient.DownloadFile(wallpaper, tempPath + randomName);

                        // Use it
                        SetDesktopWallpaper(tempPath + randomName, style);

                        // Clean up
                        File.Delete(tempPath + randomName);
                        using var timer = new Timer(2000);
                        timer.Elapsed  += (s, x) => Directory.Delete(tempPath);
                    }).ConfigureAwait(false);

                    return;
                }
                // TODO add Base64 support
            }
        }
コード例 #8
0
        private static Shared <Image> Adapter(Shared <EncodedImage> encodedImage, Envelope env)
        {
            Shared <Image> sharedImage = null;

            if ((encodedImage != null) && (encodedImage.Resource != null))
            {
                sharedImage = ImagePool.GetOrCreate(encodedImage.Resource.Width, encodedImage.Resource.Height, ImageDecoder.GetPixelFormat(encodedImage.Resource));
                ImageDecoder.DecodeTo(encodedImage.Resource, sharedImage.Resource);
            }

            return(sharedImage);
        }
コード例 #9
0
 /// <summary>
 /// Load bitmap from file.
 /// </summary>
 ///
 /// <param name="fileName">File name to load bitmap from.</param>
 ///
 /// <returns>Returns loaded bitmap.</returns>
 ///
 /// <remarks><para>The method is provided as an alternative of <see cref="System.Drawing.Image.FromFile(string)"/>
 /// method to solve the issues of locked file. The standard .NET's method locks the source file until
 /// image's object is disposed, so the file can not be deleted or overwritten. This method workarounds the issue and
 /// does not lock the source file.</para>
 /// </remarks>
 ///
 /// <example>
 /// <code source="Unit Tests\Accord.Tests.Imaging\Formats\PNMCodecTest.cs" region="doc_load" />
 /// </example>
 ///
 public static System.Drawing.Bitmap FromFile(string fileName)
 {
     return(ImageDecoder.DecodeFromFile(fileName));
 }
コード例 #10
0
 /// <summary>
 /// Sets the image decoder.
 /// </summary>
 public Builder SetImageDecoder(ImageDecoder imageDecoder)
 {
     ImageDecoder = imageDecoder;
     return(this);
 }
コード例 #11
0
ファイル: Preloader.cs プロジェクト: radtek/PicView
 /// <summary>
 /// Add file to prelader
 /// </summary>
 /// <param name="file">file path</param>
 internal static Task Add(string file) => Task.Run(() =>
 {
     Sources.TryAdd(file, ImageDecoder.RenderToBitmapSource(file));
 });
コード例 #12
0
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async void Pic(int index)
        {
#if DEBUG
            var stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            // Declare variable to be used to set image source
            BitmapSource bitmapSource;

            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                if (bitmapSource == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }
            else if (File.Exists(Pics[index])) // Checking if file exists fixes rare crashes
            {
                /// Use the Load() function load image from memory if available
                /// if not, it will be null
                bitmapSource = Preloader.Load(Pics[index]);
            }
            else
            {
                /// Try to reload from backup if file does not exist
                /// TODO needs testing
                Reload(true);
                return;
            }

            // Initate loading behavior, if needed
            if (bitmapSource == null)
            {
                // Set loading from translation service
                SetLoadingString();

                // Show a thumbnail while loading
                var thumb = GetThumb(index, true);
                if (thumb != null && Properties.Settings.Default.PicGallery != 2)
                {
                    // Don't allow image size to stretch the whole screen
                    if (xWidth == 0)
                    {
                        var size = ImageDecoder.ImageSize(Pics[index]);
                        if (size.HasValue)
                        {
                            FitImage(size.Value.Width, size.Value.Height);
                        }
                        else
                        {
                            LoadWindows.GetMainWindow.MainImage.Width  = LoadWindows.GetMainWindow.MinWidth;
                            LoadWindows.GetMainWindow.MainImage.Height = LoadWindows.GetMainWindow.MinHeight;
                        }
                    }
                    else
                    {
                        LoadWindows.GetMainWindow.MainImage.Width  = xWidth;
                        LoadWindows.GetMainWindow.MainImage.Height = xHeight;
                    }

                    LoadWindows.GetMainWindow.MainImage.Source = thumb;
                }

                // Dissallow changing image while loading
                CanNavigate = false;

                // Get it!
                await Preloader.Add(Pics[index]).ConfigureAwait(true);

                // Retry
                bitmapSource = Preloader.Load(Pics[index]);

                if (bitmapSource == null)
                {
                    // Attempt to fix it
                    bitmapSource = await PicErrorFix(index).ConfigureAwait(true);

                    // If pic is still null, image can't be rendered
                    if (bitmapSource == null)
                    {
                        // Clean up
                        Pics.RemoveAt(index);
                        Preloader.Remove(index);

                        // Sync with gallery, if needed
                        if (GetPicGallery != null)
                        {
                            if (GetPicGallery.grid.Children.Count > index)
                            {
                                GetPicGallery.grid.Children.RemoveAt(index);
                            }
                        }

                        // Check if images still exists
                        if (Pics.Count == 0)
                        {
                            Unload();
                            return;
                        }

                        /// Retry
                        /// TODO needs testing
                        CanNavigate = true;
                        Pic();
                        return;
                    }
                }
            }

            // Reset transforms if needed
            if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
            {
                UILogic.TransformImage.Rotation.Flipped             = false;
                UILogic.TransformImage.Rotation.Rotateint           = 0;
                GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                LoadWindows.GetMainWindow.MainImage.LayoutTransform = null;
            }

            // Show the image! :)
            LoadWindows.GetMainWindow.MainImage.Source = bitmapSource;
            FitImage(bitmapSource.PixelWidth, bitmapSource.PixelHeight);
            SetTitleString(bitmapSource.PixelWidth, bitmapSource.PixelHeight, index);

            // Scroll to top if scroll enabled
            if (IsScrollEnabled)
            {
                LoadWindows.GetMainWindow.Scroller.ScrollToTop();
            }

            // Update values
            CanNavigate  = true;
            FolderIndex  = index;
            FreshStartup = false;

            if (LoadWindows.GetImageInfoWindow != null)
            {
                if (LoadWindows.GetImageInfoWindow.IsVisible)
                {
                    LoadWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            RecentFiles.Add(Pics[index]);

#if DEBUG
            stopWatch.Stop();
            var s = $"Pic(); executed in {stopWatch.Elapsed.TotalMilliseconds} milliseconds";
            Trace.WriteLine(s);
#endif
        }
コード例 #13
0
 private static HttpResponseMessage DecodedDataAsZipFileResponse(string fileName, ImageDecoder image, IList <Directory> directories, IList <File> files)
 {
     return(new HttpResponseMessage(HttpStatusCode.OK)
     {
         Content = new PushStreamContent(async(outputStream, content, context) =>
         {
             ZipOutputStream zipStream = new ZipOutputStream(outputStream);
             try
             {
                 await image.DecodeAsync(directories, files,
                                         new FileDataOutputHandler(
                                             (directory) =>
                 {
                     if (!directory.IsRootDirectory)
                     {
                         zipStream.PutNextEntry(directory.Path);
                     }
                 },
                                             async(directory, file, stream) =>
                 {
                     zipStream.PutNextEntry(Path.Combine(directory.Path, file.Name));
                     await stream.CopyToAsync(zipStream);
                 }));
             }
             finally
             {
                 image.ImageStream.Close();
                 zipStream.Close();
             }
         })
         {
             Headers =
             {
                 ContentType        = new MediaTypeHeaderValue("application/octet-stream"),
                 ContentDisposition = new ContentDispositionHeaderValue("attachment")
                 {
                     FileName       = fileName
                 }
             }
         }
     });
 }
コード例 #14
0
 private static void AddDecoderFormat(ImageDecoder decoder, string description, string filter)
 {
     DecoderImageFormats.Add(new ImageFormatInformation(decoder, description, filter));
 }
コード例 #15
0
        public async Task ExtractFiles(
            string fileInputLocation,
            string password,
            string targetDirectory)
        {
            try
            {
                using (var input = new FileStream(fileInputLocation, FileMode.Open, FileAccess.Read))
                {
                    ConsoleLogger.LogMessage("Creating decoder instance...");
                    var decoder = await ImageDecoder.LoadAsync
                                  (
                        imageStream : input,
                        decodingConfiguration : new DecodingConfiguration
                        (
                            password: password,
                            tempStorageProvider: new MemoryStorageProvider(),
                            bufferSize: 81920
                        ));

                    ConsoleLogger.LogMessage("Creating decoder output handler...");
                    Output.FileDataOutputHandler handler = new Output.FileDataOutputHandler(
                        (directory, file, stream) =>
                    {
                        if (stream != null)
                        {
                            try
                            {
                                string fullName = Path.Combine(targetDirectory, file.Name);
                                if (File.Exists(fullName))
                                {
                                    File.Delete(fullName);
                                }
                                ConsoleLogger.LogMessage($"'{file.Name}' has been extracted to {fullName}");
                                using (FileStream saveStream = new FileStream(fullName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    stream.CopyTo(saveStream);
                                }
                            }
                            catch
                            {
                                ConsoleLogger.ShowErrorMessage($"Failed to process '{file.Name}' from the image container");
                            }
                        }
                        return(Task.CompletedTask);
                    }
                        );
                    ConsoleLogger.LogMessage("Start decoding image, extracting payload...");
                    await decoder.DecodeAsync(outputHandler : handler);
                }
            }

            catch (InvalidPasswordException)
            {
                ConsoleLogger.ShowErrorMessage("Invalid password");
            }
            catch (Exception ex)
            {
                ConsoleLogger.ShowErrorMessage(ex.Message);
            }
        }
コード例 #16
0
ファイル: Form1.cs プロジェクト: q4445552001/color
 private void Form1_Load(object sender, EventArgs e)
 {
     imgLoad           = ImageDecoder.DecodeFromFile(@"Nut0.png");
     pictureBox1.Image = imgLoad;
 }
コード例 #17
0
ファイル: Navigation.cs プロジェクト: ZevFung/PicView
        /// <summary>
        /// Loads image at specified index
        /// </summary>
        /// <param name="index">The index of file to load from Pics</param>
        internal static async void Pic(int index)
        {
            Preloader.PreloadValue preloadValue;
            // Error checking to fix rare cases of crashing
            if (Pics.Count < index)
            {
                preloadValue = await PicErrorFix(index).ConfigureAwait(true);

                if (preloadValue == null)
                {
                    /// Try to recover
                    /// TODO needs testing
                    Reload(true);
                    return;
                }
            }

            FolderIndex  = index;
            preloadValue = Preloader.Get(Pics[index]);

            // Initate loading behavior, if needed
            if (preloadValue == null || preloadValue.isLoading)
            {
                // Dissallow changing image while loading
                CanNavigate = false;

                if (!GalleryFunctions.IsOpen)
                {
                    await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                    {
                        // Set loading from translation service
                        SetLoadingString();
                    }));

                    // Show a thumbnail while loading
                    var thumb = GetThumb(index);
                    if (thumb != null && Properties.Settings.Default.PicGallery != 2)
                    {
                        await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                        {
                            // Don't allow image size to stretch the whole screen
                            if (xWidth == 0)
                            {
                                ConfigureWindows.GetMainWindow.MainImage.Width = ConfigureWindows.GetMainWindow.MinWidth;
                                ConfigureWindows.GetMainWindow.MainImage.Height = ConfigureWindows.GetMainWindow.MinHeight;
                            }
                            else
                            {
                                ConfigureWindows.GetMainWindow.MainImage.Width = xWidth;
                                ConfigureWindows.GetMainWindow.MainImage.Height = xHeight;
                            }

                            ConfigureWindows.GetMainWindow.MainImage.Source = thumb;
                        }));
                    }
                }

                // Get it, if not loading
                if (!Preloader.Contains(Pics[index]))
                {
                    await Preloader.Add(Pics[index]).ConfigureAwait(true);
                }
                else // Wait until loading finnished
                {
                    if (preloadValue == null)
                    {
                        await Preloader.Add(Pics[index]).ConfigureAwait(true);

                        preloadValue = Preloader.Get(Pics[index]);
                    }
                    while (preloadValue.isLoading)
                    {
                        await Task.Delay(5).ConfigureAwait(true);
                    }
                }

                // Retry
                preloadValue = Preloader.Get(Pics[index]);

                if (preloadValue == null)
                {
                    await Preloader.Add(Pics[index]).ConfigureAwait(true);

                    preloadValue = Preloader.Get(Pics[index]);
                }

                if (preloadValue.bitmapSource == null)
                {
                    // If pic is still null, image can't be rendered
                    preloadValue.bitmapSource = ImageDecoder.ImageErrorMessage();
                }
            }

            // Need to put UI change in dispatcher to fix slideshow bug
            await ConfigureWindows.GetMainWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (Action)(() =>
            {
                // Scroll to top if scroll enabled
                if (IsScrollEnabled)
                {
                    ConfigureWindows.GetMainWindow.Scroller.ScrollToTop();
                }

                // Reset transforms if needed
                if (UILogic.TransformImage.Rotation.Flipped || UILogic.TransformImage.Rotation.Rotateint != 0)
                {
                    UILogic.TransformImage.Rotation.Flipped = false;
                    UILogic.TransformImage.Rotation.Rotateint = 0;
                    GetImageSettingsMenu.FlipButton.TheButton.IsChecked = false;

                    ConfigureWindows.GetMainWindow.MainImage.LayoutTransform = null;
                }

                ConfigureWindows.GetMainWindow.MainImage.Source = preloadValue.bitmapSource;
                FitImage(preloadValue.bitmapSource.PixelWidth, preloadValue.bitmapSource.PixelHeight);
                SetTitleString(preloadValue.bitmapSource.PixelWidth, preloadValue.bitmapSource.PixelHeight, index);
            }));

            // Update values
            CanNavigate  = true;
            FreshStartup = false;

            if (ConfigureWindows.GetImageInfoWindow != null)
            {
                if (ConfigureWindows.GetImageInfoWindow.IsVisible)
                {
                    ConfigureWindows.GetImageInfoWindow.UpdateValues();
                }
            }

            if (Pics.Count > 1)
            {
                Taskbar.Progress(index, Pics.Count);

                // Preload images \\
                await Preloader.PreLoad(index).ConfigureAwait(false);
            }

            // Add recent files, except when browing archive
            if (string.IsNullOrWhiteSpace(TempZipFile))
            {
                RecentFiles.Add(Pics[index]);
            }
        }
コード例 #18
0
        public TPLImage(ref EndianBinaryReader reader)
        {
            base.setType(ImagePlatform.Wii);

            mHeight        = reader.ReadUInt16();
            mWidth         = reader.ReadUInt16();
            mFormat        = (ImageDecoder.ImageFormat_Wii)reader.ReadUInt32();
            mImageDataAddr = reader.ReadUInt32();
            mWrapS         = reader.ReadUInt32();
            mWrapT         = reader.ReadUInt32();
            mMinFilter     = reader.ReadUInt32();
            mMagFilter     = reader.ReadUInt32();
            mLODBias       = reader.ReadF32();
            mEdgeLODEnable = reader.ReadByte();
            mMinLOD        = reader.ReadByte();
            mMaxLOD        = reader.ReadByte();
            mUnpacked      = reader.ReadByte();

            reader.Seek(mImageDataAddr);

            mOutImg = null;
            bool unsupported = false;

            Console.WriteLine("Format: " + mFormat);

            if (mWidth % 4 != 0)
            {
                mWidth += (ushort)(4 - (mWidth % 4));
            }

            if (mHeight % 4 != 0)
            {
                mHeight += (ushort)(4 - (mHeight % 4));
            }

            switch (mFormat)
            {
            case ImageDecoder.ImageFormat_Wii.I4:
                mOutImg = ImageDecoder.DecodeI4(ref reader, mHeight, mWidth);
                break;

            case ImageDecoder.ImageFormat_Wii.I8:
                mOutImg = ImageDecoder.DecodeI8(ref reader, mHeight, mWidth);
                break;

            case ImageDecoder.ImageFormat_Wii.IA4:
                mOutImg = ImageDecoder.DecodeIA4(ref reader, mHeight, mWidth);
                break;

            case ImageDecoder.ImageFormat_Wii.IA8:
                mOutImg = ImageDecoder.DecodeIA8(ref reader, mHeight, mWidth);
                break;

            case ImageDecoder.ImageFormat_Wii.RGB565:
                mOutImg = ImageDecoder.DecodeRGB565(ref reader, mHeight, mWidth);
                break;

            case ImageDecoder.ImageFormat_Wii.RGB5A3:
                mOutImg = ImageDecoder.DecodeRGB5A3(ref reader, mHeight, mWidth);
                break;

            default:
                Console.WriteLine("Format " + mFormat + " not supported...");
                unsupported = true;
                break;
            }

            if (unsupported)
            {
                return;
            }
        }
コード例 #19
0
        public async Task ExecuteSelectFile(FileModel model)
        {
            if (model == null)
            {
                return;
            }

            if (State is DockState.AutoHidden or DockState.Hidden)
            {
                return;
            }

            if (canShowPrev)
            {
                PE_SelectedItem = model;
            }
            else
            {
                return;
            }
            PE_MeshPreviewVisible = false;
            IsAudioPreviewVisible = false;
            IsImagePreviewVisible = false;
            IsVideoPreviewVisible = false;

            // check additional changes
            if (model.IsDirectory)
            {
                return;
            }

            if (PE_SelectedItem == null)
            {
                return;
            }
            // string.Equals(model.GetExtension(), ERedExtension.bk2.ToString(), StringComparison.OrdinalIgnoreCase) ||
            if (!(string.Equals(model.GetExtension(), ERedExtension.mesh.ToString(), StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(model.GetExtension(), ERedExtension.wem.ToString(), StringComparison.OrdinalIgnoreCase) ||

                  string.Equals(model.GetExtension(), ERedExtension.xbm.ToString(), StringComparison.OrdinalIgnoreCase) ||
                  Enum.TryParse <EUncookExtension>(PE_SelectedItem.GetExtension(), out _)
                  )
                )
            {
                return;
            }

            if (PE_SelectedItem != null)
            {
                if (PE_SelectedItem.GetExtension().Length > 0)
                {
                    //if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.bk2.ToString(),
                    //   System.StringComparison.OrdinalIgnoreCase))
                    //{
                    //    IsVideoPreviewVisible = true;
                    //    SetExeCommand?.Invoke("test.exe | test2.bk2 /J /I2 /P");
                    //}

                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.mesh.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        PE_MeshPreviewVisible = true;

                        var q = _meshTools.ExportMeshWithoutRigPreviewer(PE_SelectedItem.FullName, Path.Combine(ISettingsManager.GetManagerCacheDir(), "Temp_OBJ"));
                        if (q.Length > 0)
                        {
                            LoadModel(q);
                        }
                    }

                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.wem.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        IsAudioPreviewVisible = true;

                        AddAudioItem(PE_SelectedItem.FullName);
                    }

                    // textures
                    if (Enum.TryParse <EUncookExtension>(PE_SelectedItem.GetExtension(),
                                                         out _))
                    {
                        IsImagePreviewVisible = true;

                        var q = await ImageDecoder.RenderToBitmapSource(PE_SelectedItem.FullName);

                        if (q != null)
                        {
                            var g = BitmapFrame.Create(q);
                            LoadImage(g);
                        }
                    }

                    // xbm
                    if (string.Equals(PE_SelectedItem.GetExtension(), ERedExtension.xbm.ToString(),
                                      System.StringComparison.OrdinalIgnoreCase))
                    {
                        IsImagePreviewVisible = true;
                        var man = ServiceLocator.Default.ResolveType <ModTools>();

                        // convert xbm to dds stream
                        await using var ddsstream  = new MemoryStream();
                        await using var filestream = new FileStream(PE_SelectedItem.FullName,
                                                                    FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.SequentialScan);
                        man.UncookXbm(filestream, ddsstream, out _);

                        // try loading it in pfim
                        try
                        {
                            var qa = await ImageDecoder.RenderToBitmapSourceDds(ddsstream);

                            if (qa != null)
                            {
                                LoadImage(qa);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            DecideForMeshPreview();
        }