c#如果文件格式为.jpg,如何在picturebox中显示图像

时间:2016-12-23 20:49:04

标签: c# winforms syntax-error picturebox openfiledialog

我有一个问题。我想将图像文件或rar / zip加载到我的WPF。当我点击我的WPF上的按钮打开文件对话框时,我遇到了一些错误。

这是我打开文件对话框的代码。

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        op.Title = "Select a File";
        op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                    "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                    "Portable Network Graphic (*.png)|*.png"+
                    "Zip Files|*.zip;*.rar";

        if (op.ShowDialog() == DialogResult.OK)
        {
                pictureBox1.Image = System.Drawing.Image.FromFile(op.FileName);
                _path = op.FileName;
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

我的问题是如果文件格式为.jpg / .png,如何显示图像,如果文件格式为.rar / .zip,则显示rar图标或任何图标。

3 个答案:

答案 0 :(得分:1)

您似乎正在尝试获取文件图标。为此,请使用ExtractAssociatedIcon,如下所示:

var icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
pictureBox1.Image = icon.ToBitmap();

答案 1 :(得分:0)

如果我不明白,您的问题的解决方案就像下面的代码一样;

首先,当用户选择 zip rar 文件时,您应该选择要在图片框中显示的常规图片。然后将所选图片( ex:rar.jpg )放在app的** bin \ debug **文件夹下。

然后,使用以下代码;

        try
        {

            op.Title = "Select a File";
            op.Filter = "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff|"
   + "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
   + "Zip Files|*.zip;*.rar";

            if (op.ShowDialog() == DialogResult.OK)
            {
                string x = op.FileName.ToString();
                char[] ayrac = { '.' };
                string[] kelimeler = x.Split(ayrac);
                string y = kelimeler[1].ToString();

                if (y != "zip" && y != "rar")
                {
                    pictureBox1.Image = System.Drawing.Image.FromFile(op.FileName);
                    _path = op.FileName;
                    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                }
                else
                {
                    //How to get picture: The best way is to put the subfolder under the app's bin\debug\,thus you can simply coding:
                    pictureBox1.Image = Image.FromFile(@"rar.jpg", true);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

我希望代码可以解决你的问题。

答案 2 :(得分:0)

也许你想要的只是一个检查文件结尾的简单if语句,如下所示:

using System.IO;

if (Path.GetExtension(op.FileName).EndsWith("rar")
    || Path.GetExtension(op.FileName).EndsWith("zip"))
{
    // File has rar or zip extension
    // Load default image from resources
} 
else
{
    // Load provided image
}

如果您想使其不区分大小写,您甚至可以将StringComparison.InvariantCultureIgnoreCase添加到EndsWith - 来电。