如何以编程方式设置图像源

时间:2011-06-28 08:05:38

标签: c# image silverlight code-behind

当Image的Source属性设置如下时,图片来自/Images/down.png

我如何以编程方式执行相同的操作?

<Image x:Name="myImg" Source="/MyProject;component/Images/down.png" />

以下操作不起作用,因为Image.Source属性不是字符串类型。

myImg.Source = "/MyProject;component/Images/down.png"; 

6 个答案:

答案 0 :(得分:64)

试试这个:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));

答案 1 :(得分:10)

myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute)); 

不要忘记将Build Action设置为“Content”,将Copy复制到输出目录为“Always”。

答案 2 :(得分:3)

尝试分配图像:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

答案 3 :(得分:2)

$sql = "SELECT * FROM articles";


$res = mysql_query($sql);

//$i = 1; // [image#]
//$c = 0; // Array object #

echo "<br/><br/>";

while($row = mysql_fetch_assoc($res)){
    $title = $row['title']; // Grabs the title
    $articles = $row['articleContent']; // Grabs the article
    $images = unserialize(base64_decode($row['image']));
    //  $imageSplit[$i] = $images[$c]; // [image1] = array[0]

    foreach ($images as $index => $img_url) {
        $i = $index + 1;
        $articles = str_replace("[image$i]","<img src='images/$img_url' width='300px' height='auto'/>","$articles");
    }


    echo "Title: $title<br/>
    Content: $articles<br/>
    <br/>
    <hr/>";

    // All variables, including $c and $i are both echoing out correctly, however $i is only being applied correctly once every loop

    //$c++;
    //$i++; 
}

LOGO是指您的图片

希望能帮到任何人。 :)

答案 4 :(得分:-1)

使用asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"
           ImageAlign="left"
           ImageUrl="images/image1.jpg"/>

和代码隐藏以更改图片网址

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 

答案 5 :(得分:-1)

试试这个

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);