如何从资源中打开图片

本文关键字:资源 | 更新日期: 2023-09-27 18:19:08

我使用这段代码,但它不起作用。图片查看器默认不打开

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

如何从资源中打开图片

我想你误会了。

首先,Bitmap是一个封装图像信息的类,但是不是磁盘上的图像。如果你想让Windows照片查看器打开一张图片,你需要将图片存储到磁盘上的某个地方,这样照片查看器才能找到并打开你的图片。

第二,File.Open是在指定的路径上打开一个具有读写权限的FileStream的函数,而不是像你想要的那样,运行一个外部进程打开一个文件

总之,如果你想让你的程序在Windows照片查看器中打开一张图片,你需要

  1. 保存您的位图信息到一个位置;
  2. 使用Process.Start()命令在程序中运行Windows照片查看器

下面是一个简单的例子:

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);

还记得在使用后删除临时图片,如果这张照片不应该被保存。

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

var img = new Bitmap(Application_name.Properties.Resources.image_name);