如何从资源中打开图片?

时间:2014-08-23 10:44:47

标签: c# bitmap

我使用此代码但它不起作用。默认照片查看器无法打开图片

public static void OpenPicture(object source,EventArgs e)
{
    Bitmap bitmap1 = AD.Properties.Resources.dust2;
    File.Open(bitmap1, FileMode.Open);
}

2 个答案:

答案 0 :(得分:1)

我认为你有一些误解。

首先,Bitmap是一个封装图像信息的类,但不是磁盘上的图像。如果您希望Windows照片查看器打开图片,您需要将该图像存储在磁盘上的某个位置,因此照片查看器可以找到并打开您的图片。

其次,File.Open是您open a FileStream on the specified path with read/write access的功能,但不是运行外部流程来打开文件,就像您想要实现的那样。

总之,如果您希望程序在Windows Photo Viewer中打开图片,则需要

  1. 将位图信息保存到某个位置;
  2. 使用Process.Start()命令在程序中运行Windows Photo Viewer。
  3. 这是一个简单的例子:

    var bitmap = new Bitmap(AD.Properties.Resources.YourImage);
    bitmap.Save("YourImageLocation");
    Process.Start("YourIamgeLocation");
    

    有关选择保存位置的一些注意事项是:永远不要选择系统驱动器以避免因缺少写入权限而导致的意外故障。典型的选择是ApplicationData下的子文件夹。以下是选择适当文件夹的演示:

    // here you could replace "YourApplicationName" with any name you want, but
    // name it after your application is a better convension
    var destPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourApplicationName");
    var picPath = Path.Combine(destPath, "pic.jpg");
    
    if (!Directory.Exists(destPath))
    {
        Directory.CreateDirectory(destPath);
    }
    
    var bitmap = new Bitmap(Properties.Resources.dust2);
    bitmap.Save(picPath);
    Process.Start(picPath);
    

    还要记得在使用后删除临时图片,如果这张图片不应保存的话。

答案 1 :(得分:-2)

将该图像添加到应用程序的资源文件夹中。 然后你可以使用:

var img = new Bitmap(Application_name.Properties.Resources.image_name);
相关问题