为什么IrfanView说我的jpg文件是一个png文件?

时间:2015-03-19 14:12:03

标签: c# image png jpeg irfanview

我的实用程序应该调整.jpg或.png文件的大小。

它似乎在一个位置正常工作(在工作中,我没有安装IrfanView)。但是在家里,当我打开一个* .jpg然后保存它(调整大小)时,我看到了:

enter image description here

但是,在任何一种情况下图像仍然可以正常显示(无论我在对话框中选择“是”还是“否”。

IOW,我可以加载并保存jpgs和png,然后保存,并显示正常。但IrfanView声称他们搞砸了。

实际上,我不确定图像是如何保存的;我假设它只是根据扩展名以“幕后”的正确格式保存它。无论如何,因为这是一个相当简单的实用程序,我将只显示所有代码:

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace FileResizingUtil
{
    public partial class FormFileResizer : Form
    {
        private Image _imgToResize;
        String _originalFilename = String.Empty;

        public FormFileResizer()
        {
            InitializeComponent();
        }

        private void buttonChooseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog
            {
                InitialDirectory = "c:\\",
                Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png", FilterIndex = 2, RestoreDirectory = true
            };


            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _originalFilename = ofd.FileName;
                    _imgToResize = Image.FromFile(_originalFilename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
            // If made it to here, it must be good
            String preamble = labelImgSelected.Text;
            labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
            textBoxOrigHeight.Text = _imgToResize.Height.ToString();
            textBoxOrigWidth.Text = _imgToResize.Width.ToString();
            buttonApplyPercentageChange.Enabled = true;
            //buttonResizeImage.Enabled = true;
        }

        private void buttonResizeImage_Click(object sender, EventArgs e)
        {
            // Really large images take awhile, so show an hourglass
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
                // Two different ways of getting the int val
                Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);

                String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
                String fileNameExtension = Path.GetExtension(_originalFilename);
                String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
                // If used a different extension (jpg where the original was png, or vice versa) would the Save be intelligent enough to actually save in the other format?
                resizedImg.Save(newFilename);

                MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
                Recycle();
            }
            finally
            {

                Cursor.Current = Cursors.Default;
            }
        }

        private void Recycle()
        {
            buttonResizeImage.Enabled = false;
            buttonApplyPercentageChange.Enabled = false;
            labelImgSelected.Text = "Image selected: ";
            textBoxOrigHeight.Text = String.Empty;
            textBoxOrigWidth.Text = String.Empty;
            // Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
        }

        private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
        {
            int origHeight = _imgToResize.Height;
            int origWidth = _imgToResize.Width;

            // Two ways to convert the val
            double heightFactor = (double)numericUpDownHeight.Value / 100.0;
            double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
            if (heightFactor < 0 || widthFactor < 0)
            {
                // show an error - no negative values allowed- using updown, so that should not be possible
            }
            var newHeight = Convert.ToInt32(origHeight * heightFactor);
            var newWidth = Convert.ToInt32(origWidth * widthFactor);
            textBoxNewHeight.Text = newHeight.ToString();
            textBoxNewWidth.Text = newWidth.ToString();
            buttonResizeImage.Enabled = true;
        }

        private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
        {
            EnableResizeButtonIfValidDimensionsEntered();
        }

        private void EnableResizeButtonIfValidDimensionsEntered()
        {
            if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
            String candidateHeight = textBoxNewHeight.Text;
            String candidateWidth = textBoxNewWidth.Text;
            int validHeight;
            int validWidth;
            buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
                                        (int.TryParse(candidateWidth, out validWidth));
        }

        private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
        {
            if (checkBoxRetainRatio.Checked)
            {
                numericUpDownWidth.Value = numericUpDownHeight.Value;
            }
        }

        private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
        {
            if (checkBoxRetainRatio.Checked)
            {
                numericUpDownHeight.Value = numericUpDownWidth.Value;
            }
        }

    }
}

..和GUI(就在点击“调整大小图像”按钮之前:

enter image description here

更新

基于Eugene Sh.'ls评论,我将Save方法更改为以下块:

bool success = true;
. . .
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
    resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null && 
         fileNameExtension.ToLower().Contains("png"))
{
    resizedImg.Save(newFilename, ImageFormat.Png);
}
else
{
    success = false;
}

if (success)
{
    MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
}
else
{
    MessageBox.Show("Something went awry. The file was not saved");
}

更新2

所以这是我的新代码,实现建议,并支持几种新的文件类型:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace FileResizingUtil
{
    public partial class FormFileResizer : Form
    {
        private Image _imgToResize;
        String _originalFilename = String.Empty;

        public FormFileResizer()
        {
            InitializeComponent();
        }

        private void buttonChooseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog
            {
                InitialDirectory = "c:\\",
                Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png| BMP files (*.bmp)|*.bmp| TIFF files (*.tiff)|*.png| ICO files (*.ico)|*.ico| EMF files (*.emf)|*.emf| WMF files (*.wmf)|*.wmf",
                    FilterIndex = 1, RestoreDirectory = true
            };


            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _originalFilename = ofd.FileName;
                    _imgToResize = Image.FromFile(_originalFilename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
            if (String.IsNullOrWhiteSpace(_originalFilename)) return;
            // If made it to here, it must be good
            String preamble = labelImgSelected.Text;
            labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
            textBoxOrigHeight.Text = _imgToResize.Height.ToString();
            textBoxOrigWidth.Text = _imgToResize.Width.ToString();
            buttonApplyPercentageChange.Enabled = true;
        }

        private void buttonResizeImage_Click(object sender, EventArgs e)
        {
            bool success = true;
            // Really large images take awhile, so show an hourglass
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                // Two different ways of getting the int val
                var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
                Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);

                String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
                String fileNameExtension = Path.GetExtension(_originalFilename);
                String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
                if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Jpeg);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("png"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Png);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("bmp"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Bmp);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("ico"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Icon);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("tiff"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Tiff);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("emf"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Emf);
                }
                else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("wmf"))
                {
                    resizedImg.Save(newFilename, ImageFormat.Wmf);
                }
                else
                {
                    success = false;
                }

                MessageBox.Show(success
                    ? String.Format("Done! File saved as {0}", newFilename)
                    : "Something went awry. The file was not saved");
                Recycle();
            }
            finally
            {

                Cursor.Current = Cursors.Default;
            }
        }

        private void Recycle()
        {
            buttonResizeImage.Enabled = false;
            buttonApplyPercentageChange.Enabled = false;
            labelImgSelected.Text = "Image selected: ";
            textBoxOrigHeight.Text = String.Empty;
            textBoxOrigWidth.Text = String.Empty;
            // Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
        }

        private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
        {
            int origHeight = _imgToResize.Height;
            int origWidth = _imgToResize.Width;

            // Two ways to convert the val
            double heightFactor = (double)numericUpDownHeight.Value / 100.0;
            double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
            if (heightFactor < 0 || widthFactor < 0)
            {
                // show an error - no negative values allowed- using updown, so that should not be possible
            }
            var newHeight = Convert.ToInt32(origHeight * heightFactor);
            var newWidth = Convert.ToInt32(origWidth * widthFactor);
            textBoxNewHeight.Text = newHeight.ToString();
            textBoxNewWidth.Text = newWidth.ToString();
            buttonResizeImage.Enabled = true;
        }

        private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
        {
            EnableResizeButtonIfValidDimensionsEntered();
        }

        private void EnableResizeButtonIfValidDimensionsEntered()
        {
            if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
            String candidateHeight = textBoxNewHeight.Text;
            String candidateWidth = textBoxNewWidth.Text;
            int validHeight;
            int validWidth;
            buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
                                        (int.TryParse(candidateWidth, out validWidth));
        }

        private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
        {
            if (checkBoxRetainRatio.Checked)
            {
                numericUpDownWidth.Value = numericUpDownHeight.Value;
            }
        }

        private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
        {
            if (checkBoxRetainRatio.Checked)
            {
                numericUpDownHeight.Value = numericUpDownWidth.Value;
            }
        }

    }
}

3 个答案:

答案 0 :(得分:2)

来自Image.Save documentation

  

如果图像的文件格式不存在编码器,则为Portable   使用网络图形(PNG)编码器。使用Save方法时   将图形图像另存为Windows图元文件格式(WMF)或增强版   元文件格式(EMF)文件,生成的文件保存为Portable   网络图形(PNG)文件。出现此问题的原因是GDI +   .NET Framework的组件没有可用的编码器   用于将文件保存为.wmf或.emf文件。

如果您想以不同的格式保存,请使用重载的Save方法,将格式作为第二个参数:

Save(String, ImageFormat)

答案 1 :(得分:1)

大多数图片查看器不使用文件的扩展名来确定文件的类型,而是使用所谓的“幻数”(http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files)。它们基本上检查文件的前X个字节,这些字节通常是特定图像格式所独有的。

我的猜测是,您正在使用的库将文件保存为PNG默认值(编辑:请参阅Eugenes答案),而不考虑您放置的扩展名。 IrfanView注意到,幻数和扩展名不匹配,但仍然通过默认显示幻数来显示图像。

答案 2 :(得分:1)

转到控制台并打印出文件。如果是PNG文件,您将看到PNG显示并停止。

如果是JPEG,你将获得大量垃圾,但应该在顶部看到EXIF或JFIF。一开始是FF D8

因为JPEG和PNG具有不同的签名,所以应用程序可以告诉它们除了它们的内容并邀请适当的解码器。

图像应用程序通常根据流的内容识别图像类型,而不是扩展名。