WPF - How to get the URI Source of an Image? - c#

I want to get the URI Source of an image that has been created in XAML. The source of the image is a BitmapFrame. I know you can use BitmapImage.UriSource for BitmapImages, but what about BitmapFrames?
To get the BitmapFrame I use:
private void imgs_Loaded(object sender, MouseEventArgs e)
{
Image img = (Image)sender;
BitmapFrame frame = (BitmapFrame)img.Source;
//How to get frame's UriSource?
}

Related

Get Image source from Image after uploading

I am currently following walk through on how to upload an image from a phone's photo gallery link here to allow users to upload an image to my application which they can set as their profile picture. I am able to get an image from the phone's gallery however when I try and save, I cannot retrieve the image source from the xaml.
Below is the xaml for the image and the button that the user clicks on to upload an image.
<Button Text="Pick a Profile Image"
Clicked="OnPictureButton_Clicked"
Grid.Column="0"></Button>
<Image Source="{Binding Employee.ProfilePicture}"
Grid.Column="1"
x:Name="profilePicture"
Grid.RowSpan="2"
WidthRequest="200"></Image>
Here is the corresponding c# code:
private async void OnPictureButton_Clicked(object sender, EventArgs e)
{
(sender as Button).IsEnabled = false;
// _stream is a private global variable
// Allow the user to view images on the phone
_stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamASync();
// If they select an image, set it as the source for profilePicture
if (_stream != null)
{
profilePicture.Source = ImageSource.FromStream(() => _stream);
}
(sender as Button).IsEnabled = true;
}
private async void Clicked_EmployeeSaved(object sender, EventArgs e)
{
var data = (EmployeeFull)BindingContext;
var uploadedPicture = profilePicture.Source; // Should be uploaded image
// Testing how to get the source for the image (Can disregard for question)
Bitmap bitmap = BitmapFactory.DecodeStream(_stream);
MemoryStream ms = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
byte[] byteArray;
byteArray = ms.ToArray();
}
Now, I know that once the user selects an image from the gallery on their device, the stream closes and so I will be unable to access it later on in the code, like I have tried in the second function shown.
However, I am unable to retrieve the name of the image that I have selected to upload. On the screen, the user is able to see this image as I have set the selected image as the source for the profilePicture tag but when I try and get that source when the user clicks 'save', it shows an ImageSource` object, not a string which I expected.
Is there another way I can get the uploaded image's name?
If you are sure the ImageSource is a stream, you can use a cast ImageSource to StreamImageSource, and then get the stream from that.
Example:
var imageStreamSource = (StreamImageSource)profilePicture.Source;
Stream actualStream = await imageStreamSource.Stream(new CancellationToken());

How to get dragover image from webView to Bitmap (UWP C#)

I want to drag&drop image on website to Canvas on Xaml.
But it is not acceptable, because dragged data is not image data but html data.
So I try to get dragover thumbnail image.
But I don't know how to access dragover thumbnail image.
How can I access dragover thumbnail image. I want to know those code. C#.
--Xaml--
<WebView x:Name="WebView" Source="https://google.com" ScriptNotify="Notify" NavigationCompleted="Completed" ></WebView>
<Canvas x:Name="Board" AllowDrop="True" DragOver="dragOver" Drop="drop" Background="White"></Canvas>
--C#--
private void dragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
e.DragUIOverride.IsContentVisible = true; // I want to get this content data. To bitmap.
}
You can use the following code to get the BitmapImage from DragEventArgs
if (e.DataView.Contains(StandardDataFormats.Bitmap))
{
try
{
var a = await e.DataView.GetBitmapAsync();
var c = await a.OpenReadAsync();
BitmapImage b = new BitmapImage();
b.SetSource(c);
MyCanvasImage.Source = b;
}
catch (Exception) { }
}

Save Bitmap image

I'm trying to modify an example of a machine vision library ( Common Vision Blox ). The example gets an image from the camera, converts it to bitmap format and shows to the user through a PictureBox.
What I want it is to save the data to a file, but I get a BMP all in black. I tried some variants but the result is the same.
If I save the image from the PictureBox, using PictureBox.SaveImage the result is the same if I
The code is this :
private Bitmap _bm;
private bool _bRequiresCopy;
private void cvImg_ImageUpdated(object sender, EventArgs e)
{
// create a bitmap out of the image
_bm = CvbImageToBitmap(cvImg.Image, out _bRequiresCopy);
// and display it in the picture box
//if (_bm != null) // Only this two lines in the original code
// pictureBox.Image = _bm;
if (_bm != null)
{
pictureBox.Image = _bm;
// Tests to save
_bm.Save("c:\\test.bmp"); // This don't work
// The following don't work, but if add a button to the form and just place in the click
// event of the button it stores the image correctly
pictureBox.Image.Save("c:\\test2.bmp");
Bitmap TestBMP = new Bitmap(_bm);
TestBMP.Save("c:\\test3.bmp"); // This don't work
}
// setup grab checkbox
chkGrab.Enabled = cvImg.IsGrabber;
chkGrab.Checked = false;
}

Update an image source when pressing a button

I have a problem with Uri and my image file.
I tested a lot of things on how to make it work but without success.
(I have image A on start. I click on image and image A change to B.)
Please can anyone expain me this problem?
I know here is lot questions about this but i still dont understand it.
Thx in advance
XAML:
<Image x:Name="obr_0_1" Grid.ColumnSpan="1"
Grid.Column="0" Grid.Row="0"
Tapped="obr_0_1_Tapped" Loaded="obr_0_1_Loaded"/>`
C#:
private void obr_0_1_Tapped(object sender, TappedRoutedEventArgs e)
{
zmenObrazek();
}
private void zmenObrazek()
{
obr_0_1.Source = new BitmapImage(new Uri("/Content/Obrazky/half-life.png", UriKind.Relative));
}
When I set the source this way, I get:
An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not > handled in user code
How do I set the image source from code ?
What about implementing the following static class:
using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
// I don't know your namespace but put it in the same namespace as your code above
// (or reference this namespace in your code above)
namespace MyNamespace
{
public static class Helper
{
public static Image CreateImage(string fileName, int desiredPixelWidth)
{
Image myImage = new Image();
//set image source
myImage.Source = CreateSource(fileName);
myImage.Width = desiredPixelWidth;
return myImage;
}
public static BitmapImage CreateSource(string fileName)
{
var file = new FileInfo(fileName);
System.Drawing.Image im = System.Drawing.Image.FromFile(file.FullName);
int actualPixelWidth = im.Width;
Uri fileUri = new Uri(file.FullName);
// Create source
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = fileUri;
// To save significant application memory, set the DecodePixelWidth or
// DecodePixelHeight of the BitmapImage value of the image source to the desired
// height or width of the rendered image. If you don't do this, the application will
// cache the image as though it were rendered as its normal size rather then just
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = actualPixelWidth;
myBitmapImage.EndInit();
return myBitmapImage;
}
}
}
Then in your source code you do the following
private void zmenObrazek()
{
// do you need the first forward slash?
// (I assume "Content" is a folder in the bin directory)
obr_0_1.Source = Helper.CreateSource("Content/Obrazky/half-life.png");
}
Is the image above (half-life.png) found in the bin folder under Content/Obrazky?
If not you may also want to change the image property, Copy to Output Directory, to "Copy always" (when you add an image to project folder the default for this property is "Do not copy").

Resource image can be referenced in Xaml but not in code, why?

Excuse the novice question, but I am just learning WPF.
I have an image that I've set the build action to be "Resource"
If I set it as the Window Icon in the XAML it works just fine.
like this:
Window ... Icon="Images/MyIco.png"
But, if I try to set it as the source for an Image, I get an exception the resource is not found:
Uri uri = new Uri("pack://application:,,,/Images/MyIco.png"); // This does not work
img.Source = BitmapFrame.Create(uri);
What am I doing wrong in the code above?
Make sure your path is correct, if true, u can try this code to load your image
//tmp is your path
BitmapImage img = new BitmapImage(new Uri(tmp, UriKind.Relative));
img.CreateOptions = BitmapCreateOptions.None;
img.ImageOpened += img_ImageOpened;
void img_ImageOpened(object sender, RoutedEventArgs e)
{
WriteableBitmap wbm = new WriteableBitmap((BitmapImage)sender);
}
Ex: my path is "/Assets/sizes/background/bg_02.png"

Categories