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.
Related
I'm trying to get this mini app to save the photo taken by the camera but I get this error.System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
I followed the Microsoft Tutorial but cant get it to work.
private async void btnTakePhoto_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);
//StorageFile photo = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/mypic.jpg"));
StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo == null)
{
// User cancelled photo capture
return;
}
StorageFolder destinationFolder =
await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder",
CreationCollisionOption.OpenIfExists);
await photo.CopyAsync(destinationFolder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
await photo.DeleteAsync();
IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap,
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied);
SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);
imageControl.Source = bitmapSource;
}
From the above mentioned code snippet remove the line that I have written below.
await photo.DeleteAsync();
After removing the line it works fine.
I have a list of Bitmap images. I need to save them to local folder.
This doesn't work on windows 10 Universal application.
var serializer = new DataContractSerializer(typeof(List<BitmapImage>));
using (var stream = await ApplicationData.Current.LocalCacheFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting)) {
serializer.WriteObject(stream, collection);
}
WriteObject method throws the following error
Exception thrown: 'System.Runtime.Serialization.InvalidDataContractException' in System.Private.DataContractSerialization.dll
BitmapImage is not serializable. Convert that to a byte array and write that to disk instead:
public static byte[] ConvertToBytes(BitmapImage bitmapImage)
{
using (var ms = new MemoryStream())
{
var btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
btmMap.SaveJpeg(ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
return ms.ToArray();
}
}
var serializer = new DataContractSerializer(typeof(byte[]));
using (var stream = await ApplicationData.Current.LocalCacheFolder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting)) {
serializer.WriteObject(stream, ConvertToBytes(collection));
}
You cannot extract the bitmap from a BitmapImage. There is no way to save a BitmapImage to file directly. The only way is to remember the original source and save that out. For more details about save BitmapImage to file please reference this thread.
If you know the original source, for example, you read the BitmapImage from the file picked by a FileOpenPicker, then you can read the image file to a WriteableBitmap then you can extract the PixelBuffer, encode it with a BitmapEncoder, and then save the resulting stream to a StorageFile as Rob said. Sample code as follows:
private async void btncreate_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openpicker = new FileOpenPicker();
openpicker.FileTypeFilter.Add(".jpg");
openpicker.FileTypeFilter.Add(".png");
StorageFile originalimage = await openpicker.PickSingleFileAsync();
WriteableBitmap writeableimage1;
using (IRandomAccessStream stream = await originalimage.OpenAsync(FileAccessMode.Read))
{
SoftwareBitmap softwareBitmap;
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
writeableimage1 = new WriteableBitmap(softwareBitmap.PixelWidth, softwareBitmap.PixelHeight);
writeableimage1.SetSource(stream);
}
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile newimage = await folder.CreateFileAsync(originalimage.Name, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream ras = await newimage.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ras);
var stream = writeableimage1.PixelBuffer.AsStream();
byte[] buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, buffer.Length);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)writeableimage1.PixelWidth, (uint)writeableimage1.PixelHeight, 96.0, 96.0, buffer);
await encoder.FlushAsync();
}
}
For list of images, you may need save them one by one.
How to set a picked image as background of a grid dynamically, save it in app local storage and retrieve it each time app is launched?
BitmapImage BgBitmap = new BitmapImage();
Image BgImg = new Image();
private async void bgbtn_Click(object sender, RoutedEventArgs e)
{
var fop = new FileOpenPicker();
fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fop.FileTypeFilter.Add(".jpg");
fop.FileTypeFilter.Add(".png");
fop.CommitButtonText = "OK";
fop.ViewMode = PickerViewMode.Thumbnail;
StorageFile file = await fop.PickSingleFileAsync();
IRandomAccessStream stream= await file.OpenAsync(FileAccessMode.ReadWrite);
await file.CopyAsync(ApplicationData.Current.LocalFolder, "BackgroundImg", NameCollisionOption.ReplaceExisting);
await BgBitmap.SetSourceAsync(stream);
BgImg.Source = BgBitmap;
}
Now, how to set this BgImg as "mainGrid" Grid Background?
and it will be nice if i can save the picked file in app storage and set tht file as background.
var imageBrush = new ImageBrush();
imageBrush.ImageSource = BgBitmap;
this.mainGrid.BackGround = imageBrush;
this should work for you
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.";
}
I am working on an application for working with photos for Windows 8 Metro on C#. And now I'm faced with a strange problem.
First, I select the file over PickSingleFileAsync, then trying to get a thumbnail via GetThumbnailAsync:
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)
{
BitmapImage bitmapImage = new BitmapImage ();
var thumb = await file.GetThumbnailAsync (ThumbnailMode.PicturesView, 150, ThumbnailOptions.UseCurrentScale);
if (thumb! = null) bitmapImage.SetSource (thumb);
}
This code is executed for files on my HDD or for any MTP-devices (tested camera and Android Tablet), but not for the iPhone. This part
var thumb = await file.GetThumbnailAsync (ThumbnailMode.PicturesView, 150, ThumbnailOptions.UseCurrentScale);
Performed for about 30 seconds, and returns null.
This code
BitmapImage bitmapImage = new BitmapImage ();
var stream = await file.OpenAsync (FileAccessMode.Read);
if (stream! = null) bitmapImage.SetSource (stream);
However, this is a complete picture, and I need a thumbnail. I tried to get it by changing the image size.
public static async Task <InMemoryRandomAccessStream> Resize (StorageFile file, uint height, uint width)
{
var fileStream = await file.OpenAsync (FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync (fileStream);
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream ();
BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync (ras, decoder);
enc.BitmapTransform.ScaledHeight = height;
enc.BitmapTransform.ScaledWidth = width;
await enc.FlushAsync ();
ras.Seek (0);
return ras;
}
And there
BitmapDecoder decoder = await BitmapDecoder.CreateAsync (fileStream);
Exception "The image cannot be decoded" occurs with code 0x88982F61.
FileOpenPicker also does not display thumbnail images on the iPhone.
But standart Photos app for Metro shows all photos on iPhone without problems.
And this leads me to 2 question:
Does anyone have any suggestions to fix this problem?
Maybe, is there a function to retrieve all the thumbnails from device?