In my app user can set profile pic from device memory i.e tablet memory or desktop local drive and upload it to server.
I used file picker so that user can select one picture and set it as profile picture, but the problem is the picture is not sticking to Image element.
My code:
private async void filePicker()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
String filePath = file.Path;
System.Diagnostics.Debug.WriteLine(filePath);
Uri uri = new Uri(filePath, UriKind.Relative);
profilePicture.Source = new BitmapImage(uri);
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
if (!unsnapped)
{
//NotifyUser("Cannot unsnap the sample.", NotifyType.StatusMessage);
}
return unsnapped;
}
the file path that I'm getting is this one
filePath=C:\Users\Prateek\Pictures\IMG_0137.JPG
I don't know what went wrong.
I am not sure if this will solve the problem, this is what I did to set my image source.
Using a bitmap image as the source to your image
BitmapImage bitmapimage = new BitmapImage();
StorageFile file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmapimage.SetSourceAsync(stream);
profilePicture.Source = bitmapImage;
I have used this code ...
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.textBlock.Text =
"File Path: " + file.Path + Environment.NewLine +
"File Name: " + file.Name;
try
{
var stream = await file.OpenReadAsync();
var imageSource = new BitmapImage();
await imageSource.SetSourceAsync(stream);
this.image.Source = imageSource;
}
catch (Exception ex)
{
this.textBlock.Text = ex.ToString();
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}
Related
I have a UWP Desktop application that has text and audio files associated, for example when the user selects the Class1.txt file, the application automatically tries to open the Class1.mp3 file.
Even with broadFileSystemAccess configured, the operation always returns an access denied error.
Any help is most welcome. Thanks.
private async void nviOpen_Tapped(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".txt");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
using (var txtStream = await file.OpenStreamForReadAsync())
{
var encoding = FileEncoding.DetectFileEncoding(txtStream);
txtStream.Seek(0, SeekOrigin.Begin);
var stmReader = new StreamReader(txtStream, encoding);
var txtContent = await stmReader.ReadToEndAsync();
tbxOriginalText.Text = txtContent;
}
//Open associated audio file
var audioFile = await StorageFile.GetFileFromPathAsync(file.Path + #"\" + file.DisplayName + ".mp3");
if (audioFile != null)
{
MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromStorageFile(audioFile));
}
}
catch (Exception ex)
{
MessageDialog msgDlg = new MessageDialog(ex.Message);
await msgDlg.ShowAsync();
}
}
}
Please take a look at the file system privacy setting and make sure that you've allowed your app for accessing your file system.
Like this:
I develop an uwp app in c# / xaml.
In my app I use this code for select an image in picture folder and put the image on the background of a grid:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
ImageBrush ib = new ImageBrush();
ib.ImageSource = image;
image.SetSource(stream);
set.Background = new ImageBrush { ImageSource = image, Stretch = Stretch.UniformToFill };
}
else
{
//
}
and what I want to do is: save the image location in application setting for later re-use
And I don't know how to do...
Don't save path to the file in UWP - the app also needs privileges, not only file location. You will likely get UnauthorizedAccessException when you get file directly from path - for example C:\Images\image.jpg.
There are two lists in UWP to remeber StorageItems, along with privileges: FutureAccessList and MostRecentlyUsedList.
When you add an item to such list, you obtain a token and this is what you should remember in your LocalSettings (for example). Then you can reuse such token to access the file/folder. Sample:
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// to save the token for further access
ApplicationData.Current.LocalSettings.Values["MyToken"] = StorageApplicationPermissions.FutureAccessList.Add(file);
// rest of the code
}
// to get the file later:
StorageFile theFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync((string)ApplicationData.Current.LocalSettings.Values["MyToken"]);
You can use the Windows.Storage.ApplicationDataContainer in following way:
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["some key"] = "your value"; // Store value in settings
var valueFromSettings = localSettings.Values["some key"]; // Getting value from settings
That way you can store and retrieve the file path, to get the path:
var filePath = file.Path;
and to get a StorageFile from a path:
var file = await StorageFile.GetFileFromPathAsync(filePath);
I have to save a content from Image tag to a file. I used a lot of Uncle Google but he doesn't know :(
private void QRbutton_Click(object sender, RoutedEventArgs e)
{
IBarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Height = 1200,
Width = 1200
}
};
String message = "";
if (String.IsNullOrEmpty(QRtxt.Text))
{
message = "You send empty message. ";
}
else
{
//Saving Input to string
message = QRtxt.Text;
StckPnlProfile_Layout.Visibility = Visibility.Collapsed;
QRsendbtn.Visibility = Visibility.Visible;
}
var result = writer.Write(message);
var wb = result.ToBitmap() as WriteableBitmap;
System.Diagnostics.Debug.WriteLine("BEFORE[Saving image to file]");
QRimage.Source = wb;
}
And there is XAML code of Image:
<Image x:Name="QRimage" Height="300"/>
I think your only option can be using RenderTargetBitmap class , it captures an image from any UIElement inherited class type like Image.
https://msdn.microsoft.com/library/windows/apps/xaml/windows.ui.xaml.media.imaging.rendertargetbitmap.aspx
HesamM, thank you for your response. Actually I did it in this way:
private async void saveImage(object sender, RoutedEventArgs e)
{
Debug.WriteLine("********** Function STARTED: Save QR code as image to jpg **********");
try
{
System.Diagnostics.Debug.WriteLine("Searching for assets folder.");
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder localFolder = await package.GetFolderAsync("Assets");
StorageFile file = await localFolder.CreateFileAsync("savedimage.jpg", CreationCollisionOption.ReplaceExisting);
var renderTargetBitmap = new RenderTargetBitmap();
System.Diagnostics.Debug.WriteLine("Rendering an image.");
await renderTargetBitmap.RenderAsync(QRimage);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
System.Diagnostics.Debug.WriteLine("Save QR code to jpg.");
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
bytes);
await encoder.FlushAsync();
}
MessageDialog SuccessMsg = new MessageDialog("Code QR saved.");
await SuccessMsg.ShowAsync();
}
catch (Exception ex)
{
//MessageDialog ErrMsg = new MessageDialog("Error Ocuured!");
System.Diagnostics.Debug.WriteLine("ERROR ZAPISU PLIKU: " + ex);
}
Debug.WriteLine("********** Function STOPPED: Save QR code as image to jpg **********");
}
I need to copy an image from my windows universal app, I was able to pick an image from my gallery but i don't how to copy it in another folder.
Although I was able to display the image in my UWP interface, so I think that I succeed to get it as a stream.
Any help would be appreciated, I'm lost here ... here is the code I used:
public MainPage()
{
this.InitializeComponent();
// Scenario4WriteableBitmap = new WriteableBitmap((int)Scenario4ImageContainer.Width, (int)Scenario4ImageContainer.Height);
Scenario2DecodePixelHeight.Text = "100";
Scenario2DecodePixelWidth.Text = "100";
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
int decodePixelHeight=150;
int decodePixelWidth=150;
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelHeight.Text, out decodePixelHeight))
{
Scenario2DecodePixelHeight.Text = "100";
decodePixelHeight = 100;
}
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelWidth.Text, out decodePixelWidth))
{
Scenario2DecodePixelWidth.Text = "100";
decodePixelWidth = 100;
}
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = decodePixelHeight;
bitmapImage.DecodePixelWidth = decodePixelWidth;
await bitmapImage.SetSourceAsync(fileStream);
Scenario2Image.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
String url = "http://localhost/mydatabase/add.php";
var values = new List<KeyValuePair<String, String>>
{
new KeyValuePair<string, string>("UserName",UserName.Text),
new KeyValuePair<string, string>("UserImage",UserImage.Text),
};
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(url, new FormUrlEncodedContent(values));
/*client.DefaultRequestHeaders.Add("content_type", "binary/octet_stream");
responseImage = client.PostAsync("", FileChooser.FileName);*/
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode.ToString());
var dialog = new MessageDialog("added succesfully ");
await dialog.ShowAsync();
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception exc)
{
// .. and understanding the error here
Debug.WriteLine(exc.ToString());
}
}
`
you can use CopyAsync of StorageFile to copy the file you get from FileOpenPicker to a specific folder.
In my windows app, i am trying to load an image from local machine to server but facing an exception of System.Runtime.InteropServices.COMException on the statement StorageFile file = await open.PickSingleFileAsync();. Here is the method:
FileOpenPicker open = new FileOpenPicker();
StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = 600; //match the target Image.Width, not shown
await bitmapImage.SetSourceAsync(fileStream);
big_image.Source = bitmapImage;
}
}
How to fix it ??? I am using VS '13. Big_image is the image defined in xaml and i am trying to set its source.
i got the solution by adding some new stuff:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
big_image.Source = bitmapImage;
}
}
microsoft.phone.tasks.photochoosertask is used to pick images.