Esempio n. 1
0
        /// <summary>
        /// Save an image.
        /// </summary>
        private void Save()
        {
            System.Windows.Forms.SaveFileDialog dlgSave = new System.Windows.Forms.SaveFileDialog();
            dlgSave.Filter = ImageCodecInfo.GetImageDecoders().Aggregate("Blp texture|*.blp", (str, codec) =>
                                                                         str += "|" + codec.FormatDescription + "|" + codec.FilenameExtension.ToLower());
            dlgSave.ShowDialog();

            if (dlgSave.FileName != "")
            {
                FileInfo info             = new FileInfo(dlgSave.FileName);
                Thread   conversionWorker = null;

                if (info.Extension.ToUpper() == ".BLP")
                {
                    // Save as Blp
                    if (settings.Format == SaveSettings.SaveFormat.Dxt1)
                    {
                        conversionWorker = new Thread(delegate() {
                            blp.Save(info.FullName, LibSquish.DxtFormat.Dxt1, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                            this.Dispatcher.Invoke((Action) delegate() { ToggleWorking(false); });
                        });
                    }
                    else if (settings.Format == SaveSettings.SaveFormat.Dxt3)
                    {
                        conversionWorker = new Thread(delegate() {
                            blp.Save(info.FullName, LibSquish.DxtFormat.Dxt3, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                            this.Dispatcher.Invoke((Action) delegate() { ToggleWorking(false); });
                        });
                    }
                    else if (settings.Format == SaveSettings.SaveFormat.Dxt5)
                    {
                        conversionWorker = new Thread(delegate() {
                            blp.Save(info.FullName, LibSquish.DxtFormat.Dxt5, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                            this.Dispatcher.Invoke((Action) delegate() { ToggleWorking(false); });
                        });
                    }
                    else if (settings.Format == SaveSettings.SaveFormat.Raw1)
                    {
                        conversionWorker = new Thread(delegate() {
                            blp.Save(info.FullName, Blp2.RawFormat.Raw1, settings.ResizeMethod, settings.Mipmaps, settings.Raw1Quality, settings.Dither);
                            this.Dispatcher.Invoke((Action) delegate() { ToggleWorking(false); });
                        });
                    }
                    else if (settings.Format == SaveSettings.SaveFormat.Raw3)
                    {
                        conversionWorker = new Thread(delegate() {
                            blp.Save(info.FullName, Blp2.RawFormat.Raw3, settings.ResizeMethod, settings.Mipmaps);
                            this.Dispatcher.Invoke((Action) delegate() { ToggleWorking(false); });
                        });
                    }
                    else if (settings.Format == SaveSettings.SaveFormat.Jpeg)
                    {
                        throw new NotImplementedException();
                    }

                    // Start conversion thread
                    conversionWorker.Priority = ThreadPriority.Highest;
                    conversionWorker.Start();
                    if (conversionWorker.ThreadState == ThreadState.Running)
                    {
                        ToggleWorking(true);
                    }
                }
                else
                {
                    // Save as regular image
                    ImageFormat imgFormat;
                    try {
                        // Choose the ImageFormats whose Guids equal the FormatID of the corresponding ImageCodecInfos
                        imgFormat = typeof(ImageFormat).GetProperties().First(
                            format => format.PropertyType.Equals(typeof(ImageFormat)) && ((ImageFormat)format.GetValue(null, null)).Guid == ImageCodecInfo.GetImageEncoders().First(
                                decoder => decoder.FilenameExtension.ToLower().Contains(info.Extension.ToLower())
                                ).FormatID
                            ).GetValue(null, null) as ImageFormat;
                    } catch (InvalidOperationException) {
                        // Fall back to bmp on error
                        imgFormat = ImageFormat.Bmp;
                    }
                    blp.Save(info.FullName, imgFormat);
                }
            }
        }
Esempio n. 2
0
        private void btnConvert_Click(object sender, RoutedEventArgs e)
        {
            if (cmbIn.SelectedValue.ToString() == cmbOut.SelectedValue.ToString())
            {
                System.Windows.Forms.MessageBox.Show("Input and output types must be different!", "Check your parameters", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }

            if (String.IsNullOrEmpty(txtFolderIn.Text) || String.IsNullOrEmpty(txtFolderOut.Text))
            {
                System.Windows.Forms.MessageBox.Show("Please specify a input and output directory!", "Check your parameters", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }

            // Cancel conversion
            if (locked)
            {
                if (conversionWorker.ThreadState == ThreadState.Running)
                {
                    System.Diagnostics.Debug.WriteLine("abort...");
                    conversionWorker.Suspend();
                    ToggleUI();
                    return;
                }
            }

            lstStatus.Items.Clear();
            listItem            = new System.Windows.Controls.ListBoxItem();
            listItem.Content    = "Generating file list -- " + DateTime.Now;
            listItem.Foreground = (System.Windows.Media.SolidColorBrush)App.Current.Resources["TextColor2"];
            lstStatus.Items.Add(listItem);
            progress.Value = 0;
            ToggleUI();

            string folderIn  = txtFolderIn.Text;
            string folderOut = txtFolderOut.Text;
            bool   subfolder = (chkSubfolders.IsChecked == true) ? true : false;
            string cmbInTxt  = cmbIn.SelectedValue.ToString();
            string cmbOutTxt = cmbOut.SelectedValue.ToString();

            if (File.Exists(folderOut + @"\conversion.log"))
            {
                File.Delete(folderOut + @"\conversion.log");
            }

            conversionWorker = new Thread(delegate() {
                DirectoryInfo di = new DirectoryInfo(folderIn);
                IEnumerable <FileInfo> filesUnfiltered = new DirectoryInfo(folderIn).EnumerateFiles("*", (subfolder) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

                // Filter complete file listfiles
                if (cmbInTxt == "BLP")
                {
                    filesFiltered.AddRange(filesUnfiltered.Where(file => file.Extension.ToUpper() == ".BLP"));
                }
                else
                {
                    ImageCodecInfo.GetImageDecoders().First(codec => codec.FormatDescription == cmbInTxt).FilenameExtension.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(
                        ext => filesFiltered.AddRange(filesUnfiltered.Where(file => file.Extension.ToUpper() == ext.Replace("*", "").ToUpper()))
                        );
                }

                // Collect unfiltered file list
                filesUnfiltered = null;
                GC.Collect();

                if (cmbOutTxt == "BLP")
                {
                    outputExt = ".BLP";
                }
                else
                {
                    outputExt = ImageCodecInfo.GetImageEncoders().First(
                        codec => codec.FormatDescription.ToUpper() == cmbOutTxt
                        ).FilenameExtension.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("*", "");

                    imgFormat = typeof(ImageFormat).GetProperties().First(
                        format => format.PropertyType.Equals(typeof(ImageFormat)) && ((ImageFormat)format.GetValue(null, null)).Guid == ImageCodecInfo.GetImageEncoders().First(
                            decoder => decoder.FilenameExtension.ToUpper().Contains(outputExt.ToUpper())
                            ).FormatID
                        ).GetValue(null, null) as ImageFormat;
                }

                for (int i = 0; i < filesFiltered.Count; i++)
                {
                    string dirName = filesFiltered[i].FullName.Replace(di.FullName, "").Replace(filesFiltered[i].Name, "");

                    // Add status list item
                    this.Dispatcher.Invoke((Action) delegate() {
                        // Add listbox item
                        listItem         = new System.Windows.Controls.ListBoxItem();
                        listItem.Content = filesFiltered[i].Name;
                        lstStatus.Items.Add(listItem);

                        // Limit list box item count to 50
                        if (lstStatus.Items.Count > 50)
                        {
                            lstStatus.Items.RemoveAt(lstStatus.Items.Count - 51);
                        }
                        lstStatus.ScrollIntoView(listItem);

                        // Update progress bar
                        progress.Value = (float)(i + 1) / filesFiltered.Count() * 100;
                    });

                    try {
                        // Create subdirectory
                        if (!Directory.Exists(folderOut + dirName))
                        {
                            Directory.CreateDirectory(folderOut + dirName);
                        }

                        using (Blp2 blp = Blp2.FromFile(filesFiltered[i].FullName)) {
                            if (cmbOutTxt == "BLP")
                            {
                                if (settings.Format == SaveSettings.SaveFormat.Dxt1)
                                {
                                    blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, LibSquish.DxtFormat.Dxt1, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                                }
                                else if (settings.Format == SaveSettings.SaveFormat.Dxt3)
                                {
                                    blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, LibSquish.DxtFormat.Dxt3, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                                }
                                else if (settings.Format == SaveSettings.SaveFormat.Dxt5)
                                {
                                    blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, LibSquish.DxtFormat.Dxt5, settings.ResizeMethod, settings.Mipmaps, settings.DxtQuality);
                                }
                                else if (settings.Format == SaveSettings.SaveFormat.Raw1)
                                {
                                    blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, Blp2.RawFormat.Raw1, settings.ResizeMethod, settings.Mipmaps, settings.Raw1Quality, settings.Dither);
                                }
                                else if (settings.Format == SaveSettings.SaveFormat.Raw3)
                                {
                                    blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, Blp2.RawFormat.Raw3, settings.ResizeMethod, settings.Mipmaps);
                                }
                            }
                            else
                            {
                                blp.Save(folderOut + dirName + filesFiltered[i].Name.Substring(0, filesFiltered[i].Name.LastIndexOf('.')) + outputExt, imgFormat);
                            }
                        }
                    } catch (Exception exc) {
                        try {
                            using (FileStream fs = new FileStream(folderOut + @"\conversion.log", FileMode.Append, FileAccess.Write, FileShare.Write)) {
                                StreamWriter sw = new StreamWriter(fs);
                                sw.WriteLine("err @" + filesFiltered[i].Name + ": " + exc.Message);
                                sw.Flush();
                                sw.Close();
                            }
                        } catch (Exception) { }
                    }
                }

                this.Dispatcher.Invoke((Action) delegate() {
                    listItem            = new System.Windows.Controls.ListBoxItem();
                    listItem.Content    = "Conversion completed -- " + DateTime.Now;
                    listItem.Foreground = (System.Windows.Media.SolidColorBrush)App.Current.Resources["TextColor2"];
                    lstStatus.Items.Add(listItem);
                    lstStatus.ScrollIntoView(listItem);
                    ToggleUI();
                });
            });

            // Start conversion thread
            conversionWorker.Priority = ThreadPriority.Normal;
            conversionWorker.Start();
        }