Get Image source from Image after uploading - c#

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());

Related

Loaded pictureBox.ImageLocation is null

I'm trying to do something when I click image displayed inside pictureBox1.
pictureBox is loaded with this code:
string imgpath = #"img\256.png";
pictureBox48.Image = Image.FromFile(imgpath);
Then control is released to me so I can see that the picture loaded correctly.
Then i click the picture:
public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}
This doesn't work. When I debug the code I see that variable1 stay null, that is pictureBox48.ImageLocation is null. Why is that? Shouldn't it be the path to the image that is assigned there?
You can't get the image path when you set the image using the Image property because you are assigning an Image object which can come from different sources.
Set the image using ImageLocation.
string imgpath = #"img\256.png";
pictureBox48.ImageLocation = imgpath;
When you click in the PictureBox you can get the path using the same property:
public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}
When dealing with Image or PictureBox I would recommend to not use something like Location or Path of the image. Assume that when the image is loaded user removes it from the hard drive and you're left with the code full of errors.
That's why you should rely on Image itself as it contains every information about the image like pixel format, width, height and raw pixel data.
I would recommend you to just copy the image, not the path to the file.
This piece of code should give you a hint:
pixtureBox48.Image = Image.FromFile(imgPath);
// above code assumes that the image is still on hard drive and is accessible,
// now let's assume user deletes that file. You have the data but not on the physical location.
Image copyImage = (Image)pictureBox48.Image.Clone();
Form3 fo = new Form(copyImage); // change .ctor definition to Form(Image copy)
fo.ShowDialog();

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) { }
}

Xaml Image.Source is not updating in C#

I have some trouble with updating the source of an Image in Xaml. Im making a Windows Store App, and Im trying to set the source in my C# code. Basically, what my small program is doing is to let the user select a JPG file, and then copy this over to AppData folder. In my App, I want the picture the user have uploaded to show. Everything is working except the part where I show the image, this image does not want to change even if I provide a new source.
C# Code:
public sealed partial class MainPage : Page
{
FileOpenPicker pickerSelect;
FileSavePicker pickerSave;
StorageFolder folder;
StorageFile pic;
public MainPage()
{
this.InitializeComponent();
InitializePickers();
InitializeProfilePicture();
}
private async void InitializeProfilePicture()
{
folder = Windows.Storage.ApplicationData.Current.LocalFolder;
pic = await folder.GetFileAsync("profile.jpg");
BitmapImage uri = new BitmapImage(new Uri(pic.Path, UriKind.Absolute));
ProfilePic.Source = uri;
}
private void InitializePickers()
{
pickerSelect = new FileOpenPicker();
pickerSave = new FileSavePicker();
pickerSelect.FileTypeFilter.Add(".jpg");
}
private async void Upload_Click(object sender, RoutedEventArgs e)
{
StorageFile pictureSelect = await pickerSelect.PickSingleFileAsync();
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
await pictureSelect.CopyAsync(folder, "profile.jpg", NameCollisionOption.ReplaceExisting);
InitializeProfilePicture();
}
}
In the method "InitializeProfilePicture" I create a new BitmapImage and I set ProfilePic to this. This code is just working once, if I run the InitializeProfilePicture in the start as I do now, and the user selects a new picture and uploads to the AppData folder, the image does not change (even though the picture is indeed uploaded). If I remove the method from the start and just keep it in the Button_Click method, the new uploaded picture will be the one showing. But uploading a new picture after ProfilePic have set it's source, it will not change.
Image in Xaml is just like this
Image Width="480" Height="640" x:Name="ProfilePic" Grid.Row="1" Grid.RowSpan="2"
.. And there is also a button here to run Upload_Click method, but thats it.
Any idea why this is happening?? Should it not be updated??
You could load a BitmapImage directly from file like this:
var imageFile = await picker.PickSingleFileAsync();
var bitmap = new BitmapImage();
using (var stream = await imageFile.OpenReadAsync())
{
await bitmap.SetSourceAsync(stream);
}
ProfilePic.Source = bitmap;

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;
}

Adding a picture from a resource to a picture box

I got this issue with displaying a image that i allready have added as a resource. I am guessing i am missing something vital but i cant find what it is. I am hoping that someone has a better idea of what i am doing wrong atm.
I have added an .bmp image into the solutiontree and changed the build action properties of that image to Embedded resource but i cant figure out how to call that image from the pipe?
as the user clicks a button the image should be sent to the imagebox, the code i have written so far looks like this:
this is ofs only the button_click code:
private void button1_Click(object sender, EventArgs e)
{
//Show image in the picturebox of selected cake
Image image = Image.FromFile(fruitcake.jpg);
pictbox.Image = image;
pictbox.Height = 163;
pictbox.Width = 223;
choice = 1;
lblCookiesPerGram.Text = string.Empty;
}
Anyone has an idea of what i am doing wrong or can i do this in another war? mind thou its 4 buttons the user clicks and there is a image for each one ;)
//Regards
If you go to your Solution - Properties window and select the Resources tab and add the image through this manager, then the images can be directly referenced like this:
Image image = Properties.Resources.fruitcake;
To retrieve an image from a resource, you can do something like:
using (Stream imgStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(
"MyNamespace.resources.fruitcake.jpg"))
{
var image = new Bitmap(imgStream);
pictBox.Image = image;
pictBox.Height = image.Height;
pictBox.Width = image.Width;
}

Categories