I am trying to retrieve an image from the phone library and set it as the page background using the following code
private void selectImageFromMediaLib()
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
private void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
backgroundUri = new Uri(e.OriginalFileName, UriKind.Absolute);
var bitmap = new BitmapImage(backgroundUri);
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = bitmap;
this.LayoutRoot.Background = imageBrush;
}
}
However, the page background turns black so the photo was not retrieved/created correctly. What is the correct path for the URI to the device library? Isn't using UriKind.Absolute enough?
You can't use the PhotoResult.OriginalFileName property to read the file, instead use the
PhotoResult.ChosenPhoto stream and assign it to the bitmap.ImageSource property in your code.
try this. It works for me
PhotoChooserTask selectphoto;
private void selectImageFromMediaLib()
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
private void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
MemoryStream ms = new MemoryStream(imageBytes);
bitmapImage.SetSource(ms);
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = bitmapImage;
this.LayoutRoot.Background = imageBrush;
}
}
Related
I coded an application that has a webcam which can SCAN QR codes:
VideoCaptureDevice LocalWebCam;
public FilterInfoCollection LoaclWebCamsCollection;
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
BitmapImage bi;
using (var bitmap = (Bitmap)eventArgs.Frame.Clone())
{
bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
bi.StreamSource = ms;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
}
bi.Freeze();
Dispatcher.BeginInvoke(new ThreadStart(delegate { frameHolder.Source = bi; }));
}
catch
{
//some error
}
and
void Window2_Loaded(object sender, RoutedEventArgs e)
{
LoaclWebCamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
LocalWebCam = new VideoCaptureDevice(LoaclWebCamsCollection[0].MonikerString);
LocalWebCam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
LocalWebCam.Start();
timer.Start(); // QR CODE SCANNER
}
It works all fine but when I let the application run for some longer time the webam freezes. Does someone have an idea why?
I have a custom UserControl with an Image control in it. I'm trying to fetch an image from web[network server] and show it in my control, refreshing the source using a dispatcher timer. Here is the code:
void StartSourceRefresh()
{
if (timeinterval < 1) timeinterval = 1;
tmrRefresh.Tick += new EventHandler(dispatcherTimer_Tick);
tmrRefresh.Interval = new TimeSpan(0, 0, timeinterval); //in hour-minute-second
tmrRefresh.Start();
}
public void ChangeImageSource(string newSource)
{
//newSource = "http://192.168.1.3/abc/imagetobeshown.png"
WebImg.Source = null;
if (newSource.Trim() == "")
WebImg.Source = new BitmapImage(new Uri(#imagePlaceholder, UriKind.Absolute));
else
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(#newSource, UriKind.Absolute);
image.EndInit();
WebImg.Source = image;
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
ChangeImageSource(txtImgSrc.Text.Trim());
}
the problem is the image wont change. Its showing the same one which was fetched at the first time. Timer is running fine. But the image just won't change. What am i doing wrong here?
Edit: Network Source gets refreshed after certain interval, so have to fetch the same source
You are apparently reloading from the same image URL, which is cached by default.
Disable caching by setting BitmapCreateOptions.IgnoreImageCache:
var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(newSource);
image.EndInit();
My objective is as follows: I want to drag drop a file to my WPF window and it should create a button with the icon image at run time.
Currently my code simply creates a button without any image in it. Im new to WPF so please go easy on me!
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(AttachedProperties), new UIPropertyMetadata(null));
public static void SetImageSource(DependencyObject d, ImageSource source)
{
d.SetValue(ImageSourceProperty, source);
}
private Bitmap GetIconImageFromFile(String filename)
{
Bitmap bmp = System.Drawing.Icon.ExtractAssociatedIcon(filename).ToBitmap();
bmp.Save("test.bmp");
return bmp;
}
private BitmapImage GetBitmapImageFromBitmap(Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
memory.Seek(0, SeekOrigin.Begin);
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
return bitmapImage;
}
private void Window_Drop(object sender, System.Windows.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
{
String[] fileNames = (String[])e.Data.GetData(DataFormats.FileDrop);
foreach (String fileName in fileNames)
{
MessageBox.Show("WindowDrop " + fileName);
Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
//newButton.Template = (ControlTemplate)TryFindResource("btemp2");
Bitmap bmp = GetIconImageFromFile(fileName);
BitmapSource src = GetBitmapImageFromBitmap(bmp);
AttachedProperties.SetImageSource(newButton,src);
stack.Children.Add(newButton);
}
}
}
I have modified your code as follows , I create Image instance and set it as button content. Please try this.
foreach (String fileName in fileNames)
{
MessageBox.Show("WindowDrop " + fileName);
Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
//Craete the Image isntance and set the image to be dispalyed
Image ButtonPicture = new Image();
ButtonPicture.BaseUri = fileName;
//Set it to the button content
newButton.Content = ButtonPicture;
AttachedProperties.SetImageSource(newButton,src);
stack.Children.Add(newButton);
}
Ik in windows forms I could add images in resources and then change the images as users click on an event handler not sure whats changed in Xaml but I cant figure it out.
private void guessClick(object sender, RoutedEventArgs e)
{
wrongGuesses++;
hangmanPicture.Image = hangmanImage[wrongGuesses];
}
if I just put hangmanPicture = hangmanImage[wrongGuesses];
I get can not convert. I don't understand why its trying to convert anything.
if your hangmanImage array is an array of ImageSource or BitmapImage, you can use it like this:
private void guessClick(object sender, RoutedEventArgs e)
{
wrongGuesses++;
hangmanPicture.Source = hangmanImage[wrongGuesses];
}
Otherwise, you have to convert anything in hangmanImage into ImageSource or BitmapImage.
If it's Bitmap you can use below converter before that code:
public static BitmapImage ConvertToBitmapImageFromBitmap(Bitmap bitmap)
{
using(var memory = new MemoryStream())
{
BitmapImage bitmapImage;
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
So, then it will be like this:
hangmanPicture.Source = ConvertToBitmapImageFromBitmap(hangmanImage[wrongGuesses]);
Hi I am developing a lockscreen app where I am using listbox of images.After selecting a image when i am clicking a button to set lockscreen,It should updated.But it bot updating .Here is my code
private async void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
MediaLibrary mediaLibrary = new MediaLibrary();
//ImageSource im = image1.Source;
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(mediaLibrary.Pictures[imageList.SelectedIndex].GetImage());
String tempJPEG = "MyWallpaper1.jpg";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 90);
fileStream.Close();
}
LockScreenChange(tempJPEG);
}
private async void LockScreenChange(string filePathOfTheImage)
{
if (!LockScreenManager.IsProvidedByCurrentApplication)
{
await LockScreenManager.RequestAccessAsync();
}
if (LockScreenManager.IsProvidedByCurrentApplication)
{
var schema = "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
LockScreen.SetImageUri(uri);
var currentImage = LockScreen.GetImageUri();
MessageBox.Show("Success", "LockScreen changed", MessageBoxButton.OK);
}
else
{
MessageBox.Show("Background cant be changed. Please check your permissions to this application.");
}
}
Actually when first time the app is launched and when I am clicking set button,the current selected image is set as lockscreen,after that when i am selecting another image,it is showing lockscreen changed ,success.No error and no exception.I dont know where is the problem.
Please help........
It got solved by changing temporary file name to original file name i.e. string tempJpeg