将PictureBox的图像从我的资源更改为图像?

问题描述 投票:22回答:6

如何从我的资源中将PictureBox图像设置为图像?

(我尝试了这个没有成功:pictuerbox.Image = "img_location";

c# winforms image resources picturebox
6个回答
63
投票

如果使用visual studio UI加载资源,那么您应该能够这样做:

picturebox.Image = project.Properties.Resources.imgfromresource

11
投票

Ken有正确的解决方案,但您不想添加picturebox.Image.Load()成员方法。

如果使用Load执行此操作并且未设置ImageLocation,则它将失败并显示“必须设置映像位置”异常。如果你使用picturebox.Refresh()成员方法,它没有例外。

完成的代码如下:

public void showAnimatedPictureBox(PictureBox thePicture)
{
            thePicture.Image = Properties.Resources.hamster;
            thePicture.Refresh();
            thePicture.Visible = true;
}

它被调用为:showAnimatedPictureBox(myPictureBox);

我的XAML看起来像:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="myApp.MainWindow"
        Title="myApp" Height="679.079" Width="986">

        <StackPanel Width="136" Height="Auto" Background="WhiteSmoke" x:Name="statusPanel">
            <wfi:WindowsFormsHost>
                <winForms:PictureBox x:Name="myPictureBox">
                </winForms:PictureBox>
            </wfi:WindowsFormsHost>
            <Label x:Name="myLabel" Content="myLabel" Margin="10,3,10,5" FontSize="20" FontWeight="Bold" Visibility="Hidden"/>
        </StackPanel>
</Window>

我意识到这是一个旧帖子,但是直接从资源加载图像在微软的网站上是非常不清楚的,这是我得到的(部分)解决方案。希望它可以帮到某人!


6
投票

好的...首先,您需要在项目中导入图像

1)在“表单设计”中选择图片框

2)打开PictureBox任务(它是指向图片框边缘的小箭头)

3)点击“选择图片...”

4)选择第二个选项“Project resource file:”(此选项将创建一个名为“Resources”的文件夹,您可以使用Properties.Resources访问该文件夹)

5)单击导入并从计算机中选择图像(现在,将在步骤4中创建的Resources文件夹中发送与图像同名的图像副本)

6)点击确定

现在图像在您的项目中,您可以将它与属性命令一起使用。当您想要从图片框更改图片时,只需输入以下代码:

pictureBox1.Image = Properties.Resources.myimage;

注意:myimage代表图像的名称...在资源之后键入点后,在您的选项中它将是您导入的图像文件


3
投票

您可以使用ResourceManager加载图像。

请参阅以下链接:http://www.java2s.com/Code/CSharp/Development-Class/Saveandloadimagefromresourcefile.htm


2
投票

尝试以下方法:

 myPictureBox.Image = global::mynamespace.Properties.Resources.photo1;

并使用项目命名空间替换命名空间


0
投票

您必须将资源文件的完整路径指定为应用程序资源中的图像名称,请参阅下面的示例。

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    PictureBox1.Image = My.Resources.Chrysanthemum
End Sub

在MyResources指定资源名称后分配给Image属性的路径中。

但是,在您从应用程序的资源部分导入任何内容之前,从映像文件存在,或者它可以创建您自己的。

再见

© www.soinside.com 2019 - 2024. All rights reserved.