Problems displaying an image in Silverlight - silverlight

I am trying to generate an image in silverlight but for some reason it is not showing.
Here is the code that I am using
Image fireBall = new Image();
Uri imageUri = new Uri("/Yambushi;Images/Projectiles/Fireball.png", UriKind.Relative);
fireBall.Source = new BitmapImage(imageUri);
cnvGame.Children.Add(fireBall);
fireBall.SetValue(Canvas.LeftProperty, Convert.ToDouble(100)); //(Doll left property)
fireBall.SetValue(Canvas.TopProperty, Convert.ToDouble(100));
fireBall.Height = 30;
fireBall.Width = 30;
Yambushi being the solution name and cnvGame the canvas I want to display the image in. The png file build action is set to content

Ok solved the problem...after I debugged the sourceUri of an image i've implemented through xaml and the source had to be as follows:
Uri imageUri = new Uri("/Images/Projectiles/Fireball.png", UriKind.Relative);
fireBall.Source = new BitmapImage(imageUri);

Related

WPF loading jpg image by code error - BitmapMetadata is not available on BitmapImage

Very frustrated with this.
I'm having an issue loading jpg images only via code. Same images are loaded correctly if I load them in XAML.
e.g:
<Image Source="Assets/Images/Backgrounds/ChangeSelectionImg.jpg" />
But this code doesn't load the same image, but works fine with PNG images:
var uriSource = new Uri(#"C:\Work\TestApp\Assets\Images\Backgrounds\ChangeSelectionImg.jpg", UriKind.Absolute);
var bmi = new BitmapImage();
bmi.BeginInit();
bmi.CacheOption = BitmapCacheOption.OnLoad;
bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bmi.UriSource = uriSource;
bmi.EndInit();
var image = new Image
{
Width = 187,
Height = 700,
StretchDirection = StretchDirection.DownOnly,
Stretch = Stretch.Fill,
Source = bmi
};
SpImage.Children.Add(image);
I haven't tried with Relative URI because the actual image I want to load is a folder external to the application. The image path will be specified in the database.
Even tried the BitmapCreateOptions.IgnoreColorProfile option as suggested here, but that didn't work either.
The code below works with PNG images but not jpg:
var imagePath = "some absolute path to an image";
var uriSource = new Uri(imagePath, UriKind.Absolute);
var image = new Image
{
Width = 187,
Height = 700,
StretchDirection = StretchDirection.DownOnly,
Stretch = Stretch.Fill,
Source = new BitmapImage(uriSource)
};
I'm at a loss of ideas now. Any help would be very much appreciated.
Since I couldn't figure out why this was happening and no one helping :(
Just in case someone else gets stuck in the same way, this is what I decided to do:
var bannerImg = new ImageBrush(new BitmapImage(uriSource))
{
Stretch = Stretch.Uniform
};
SpImage.Background = bannerImg;
I set the background image of the StackPanel to the image.
I'm still open to suggestions.
BitMapImage doesn't support BitMapMetaData, It throws System.NotSupported exception, using JpegBitmapDecoder will resolve this issue.

Delete image created by Interop Powerpoint in WPF Application

I wrote a WPF Application that opens a PowerPoint presentation and save the slides as images to be displayed in a PictureBox. The PictureBox is bounded to ImageBitmap property.
PowerPoint.Application app = new PowerPoint.Application();
PowerPoint.Presentations pres = app.Presentations;
p = pres.Open(FileName, ofalse, ofalse, otrue);
p.Slides[0].Export(ImagePath, "png", 640, 480);
ImageBitmap = new BitmapImage(new Uri(ImagePath));
When the application is closed, I would like to delete all the image files created, but instead I got an error: "“The process cannot access the file because it is being used by another process”.
I have determined (using ProcessExplorer) that the files were being used only by my application.
I read some suggestions that using the code below will allow the image file (located in ImagePath) to be deleted, but I think this will break MVVM since the viewModel now knows about the View.
Image im = GetCopyImage(#"D:\Temp\AAAA.jpg");
myPictureBox.Image = im;
File.Delete(#"D:\Temp\AAAA.jpg");
}
private Image GetCopyImage(string path)
{
using (Image im = Image.FromFile(path))
{
Bitmap bm = new Bitmap(im);
return bm;
}
}
You may set the BitmapCacheOption.OnLoad option during initialization of the BitmapImage. This lets WPF close the image file right after loading the image.
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(ImagePath);
bitmap.EndInit();
ImageBitmap = bitmap;

Load Image at runtime from resource in WPF

Im trying to load a image at runtime in WPF using the following code
_image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(#"pack://application:,,,/images/tagimages/placeholder.png", UriKind.Absolute);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
_image.Source = src;
_image.Stretch = Stretch.None;
In my project I have a folder called images and a sub folder of that folder called tagimages that contains the placeholder.png. When I run this code I get the following error
"Cannot locate resource 'images/tagimages/placeholder.png'"
What am I doing wrong?
It turns out that I should have used
Uri(#"pack://application:,,,/<MyProject>;component/images/tagimages/placeholder.png", UriKind.Absolute);
From procedural code you use: #"pack://application:,,,/putyourfilenamehere" for an embedded resource.
Or in other words
BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/Images/myimage.png"));

Relative Uri works for BitmapImage, but not for MediaPlayer?

This will be simple for you guys:
var uri = new Uri("pack://application:,,,/LiftExperiment;component/pics/outside/elevator.jpg");
imageBitmap = new BitmapImage();
imageBitmap.BeginInit();
imageBitmap.UriSource = uri;
imageBitmap.EndInit();
image.Source = imageBitmap;
=> Works perfectly on a .jpg with
Build Action: Content
Copy to Output Directory: Copy always
MediaPlayer mp = new MediaPlayer();
var uri = new Uri("pack://application:,,,/LiftExperiment;component/sounds/DialingTone.wav");
mp.Open(uri);
mp.Play();
=> Does not work on a .wav with the same build action and copy to output. I see the file in my /debug/ folder..
MediaPlayer mp = new MediaPlayer();
var uri = new Uri(#"E:\projects\LiftExp\_solution\LiftExperiment\bin\Debug\sounds\DialingTone.wav");
mp.Open(uri);
mp.Play();
=> Works perfectly..
So, how do I get the sound to work with a relative path? Why is it not working this way?
Let me know if you want more code or screenshots.
Thanks.
The pack://application URI syntax is for "embed" files, make sure the the media file is set to that, or use the pack://siteoforigin for "loose" files (copied to bin directory).
MSDN link

How to render an <image> in a background WPF process?

I'm taking Silverlight XAML and sending it to a web service that renders the XAML in a STA thread and generates a PNG image. All the XAML renders correctly except the <image> entries which 'appear' to load correctly when their Source property is set in WPF but the PNG does not show the referenced image - what am I doing wrong ?
The core of the code that I am using is as below. The value object is a DTO from Silverlight that contains the XAML in the string that ends up as the sXAML local property and the Image URI is in the value.ImageURL property.
var canvas = (FrameworkElement)XamlReader.Load(new XmlTextReader(new StringReader(sXAML)));
var obj = canvas.FindName("BGImage");
Image img = null;
if (obj != null)
{
img = obj as Image;
img.ImageFailed += img_ImageFailed;
img.Source = new BitmapImage(new Uri(value.ImageURL, UriKind.Absolute));
}
canvas.Arrange(new Rect(new Size(463d, 381d)));
canvas.UpdateLayout();
var mem = new MemoryStream();
var bmp = new RenderTargetBitmap(463, 381, 96d, 96d, PixelFormats.Pbgra32);
bmp.Render(canvas);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(mem);
FileStream fs = new FileStream("D:\\out.png", FileMode.Create);
mem.WriteTo(fs);
fs.Close();
NB: The img_ImageFailed event handler is never invoked indicating that the img Source assignment was successful in some way.
Things I would try:
1) In your WPF app, if you 'render' your dynamically loaded Canvas to display in a Window, does it all work (images included)?
2) Have you tried attaching a Loaded handler to the img object to see when the image is actually loaded?
3) Assuming #1 works - where are the images located (are they on the internet/local web server)? If you put a breakpoint in the code on
bmp.Render(canvas);
and wait a while before stepping on - does the image then appear in the rendered output?
I suspect the image is being 'downloaded' asynchronously and you are rendering the Canvas too early, before the Image object has resolved its source.
[UPDATE 29-Jan-09]
possible solution
I copied you code down exactly and gave it a try. When I used a 'local' image location (eg. "c:\images\splash.jpg") the image was rendered fine in the output jpeg. When I used a URL (eg. "http://localhost/images/splash.jpg") it did NOT appear (as you describe).
So I modified your code as follows (to try and FORCE the image to be downloaded - will only work for http: image references) --
if (obj != null)
{
img = obj as Image;
// new stuff
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = getCachedURLStream(new Uri(ImageURL));
bi.EndInit();
img.BeginInit();
img.Source = bi;
img.EndInit();
//img.ImageFailed += img_ImageFailed;
//img.Loaded += new RoutedEventHandler(img_Loaded);
//img.Source = new BitmapImage(new Uri(ImageURL, UriKind.Absolute));
}
public static Stream getCachedURLStream(Uri url)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
WebResponse response;
webrequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
response = webrequest.GetResponse();
Stream s = response.GetResponseStream();
BufferedStream bs = new BufferedStream(s, 8192);
return bs;
}
(the getCachedURLStream method is from synchronous image loading - it's kinda extraneous but I just wanted a quick chunk of code to test) and it seemed to then work (image visible in JPEG). Maybe that will work in your scenario?

Resources