I would like to display an image file on the UI from the Assets. I managed to store the item as a StorageFile. How can I display it? I've tried to display it in a XAML <Image> tag's Source. Is it possible to covert StorageFile to Image?
string path = #"Assets\mypicture.png";
StorageFile file = await InstallationFolder.GetFileAsync(path);
Try this function
public async Task<Image> GetImageAsync(StorageFile storageFile)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
Image image = new Image();
image.Source = bitmapImage;
return image;
}
Try the following:
public async Task<BitmapImage> GetBitmapAsync(StorageFile storageFile)
{
BitmapImage bitmap = new BitmapImage();
IAsyncOperation<IRandomAccessStream> read = storageFile.OpenReadAsync();
IRandomAccessStream stream = await read;
bitmap.SetSource(stream);
return bitmap;
}
Call the function this way:
Image image = new Image();
image.Source = await GetBitmapAsync (file);
image.Source = new BitmapImage(new Uri("file://"+ storageFile.Path))
Related
We can load SVG from 1703 in UWP.
Can anyone provide a mechanism,
how to covert SVG to WriteableBitmap in C# UWP.
Unfortunately, there is no such api could covert SVG to WriteableBitmap image directly, Because when we convert file to WriteableBitmap we need use BitmapDecoder class like the following, but BitmapDecoder does not support svg type.
private static async Task<WriteableBitmap> OpenWriteableBitmapFile(StorageFile file)
{
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
WriteableBitmap image = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
image.SetSource(stream);
return image;
}
}
And currently we have a workaround that use RenderTargetBitmap to render your image control and convet RenderTargetBitmap to WriteableBitmap with following.
private async void RenderTargetBitmapToWriteableBitmap(UIElement element)
{
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(element);
var pixelBuffer = await bitmap.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
var wb = new WriteableBitmap((int)bitmap.PixelWidth, (int)bitmap.PixelHeight);
using (Stream stream = wb.PixelBuffer.AsStream())
{
await stream.WriteAsync(pixels, 0, pixels.Length);
}
}
First I declared
private MediaCapture _mediaCapture;
StorageFile capturedPhoto;
IRandomAccessStream imageStream;
Second I am capturing
var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));
var capturedPhoto = await lowLagCapture.CaptureAsync();
await lowLagCapture.FinishAsync();
Third I am setting the image source:
var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;
SoftwareBitmap softwareBitmapBGRB = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
await bitmapSource.SetBitmapAsync(softwareBitmapBGRB);
image.Source = bitmapSource;
How can i get imageStream? I used CaptureElement tool in xaml .
It's quite simple, the question is what do you want to do with that IRandomAccessStreem. Below is some code I think you'll need:
public void HandleImageFileOperations(StorageFile file)
{
if (file != null)
{
//converts the StorageFile to IRandomAccessStream
var stream = await file.OpenAsync(FileAccessMode.Read);
//creates the stream to an Image just in-case you want to show it
var image = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
image.SetSource(stream);
//creates the image into byte array just in-case you need it to store the image
byte[] bitmapImageBytes = null;
var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
bitmapImageBytes = new byte[stream.Size];
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(bitmapImageBytes);
}
}
My goal is to draw image "someImage.png", which is embedded resource, on WPF window, in overridden OnRender method:
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
base.OnRender(drawingContext);
drawingContext.DrawImage(ImageSource, Rect);
}
I found code to get my image from resources to Stream:
public BitmapSource GetSourceForOnRender()
{
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream("KisserConsole.someImage.png");
// What to do now?
return //BitmapSource
}
But how can i get or create BitmapSource now?
You can create a BitmapImage from the stream by setting its StreamSource property:
public BitmapSource GetSourceForOnRender()
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var bitmap = new BitmapImage();
using (var stream =
assembly.GetManifestResourceStream("KisserConsole.someImage.png"))
{
bitmap.BeginInit();
bitmap.StreamSource = stream;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
}
return bitmap;
}
That said, you would usually create a BitmapImage from a Resource File Pack URI, like e.g.
new BitmapImage(new Uri(
"pack://application:,,,/KisserConsole.someImage.png"));
You can try to use this:
Uri uri = new Uri( $"pack://application:,,,/YourAssemblyName;component/Resources/images/photo.png", UriKind.Absolute );
BitmapImage bitmap = new BitmapImage( uri );
Make sure the Build Action of the image file is set to Resource.
I'm developing a simple application in Windows 8 metro applications and I m trying to retrieve files from PicturesLibrary, the code I put is the following :
public async void Initialize()
{
IReadOnlyList<StorageFile> storageFiles = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var storageFile in storageFiles)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
Image image = new Image();
image.Source = bitmapImage;
Images.Add(image);
}
}
then I show these images using their ImageSource.
The problem that I am meeting is that sometimes it shows them all, somethimes one
or two , sometimes it deosn't show any image, I don't understand if this is because of the awaitable method GetFileAsync() or other things I may be missing.
Thanks in advance :)
I would guess it's just a timing issue, but doing a breakpoint or trace point in the foreach would tell for sure.
Try changing this to return Task and then await it in the caller of you can
I think your problem will be this line.
FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);
Awaiting inside a loop is likely going to give you some odd scope issues.
The first thing I would try is switching the first two lines of this loop around.
FileRandomAccessStream stream = (FileRandomAccessStream)await storageFile.OpenAsync(FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
It could be that the bitmapImage reference is being repointed on you. If this doesn't help though, you might need to look at the .ContinueWith method.
storageFile.OpenAsync(FileAccessMode.Read).ContinueWith(task => {
FileRandomAccessStream stream = (FileRandomAccessStream)task.Result;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
Image image = new Image();
image.Source = bitmapImage;
Images.Add(image);
});
Ok, I found the solution for this thanks to you guys , I had to rearrange the code little bit,
public async Task Initialize()
{
IReadOnlyList<StorageFile> storageFiles = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var storageFile in storageFiles)
{
var image = new Image();
image.Source = await GetBitmapImageAsync(storageFile);
Images.Add(image);
}
}
public async Task<BitmapImage> GetBitmapImageAsync(StorageFile storageFile)
{
BitmapImage bitmapImage = new BitmapImage();
IAsyncOperation<IRandomAccessStream> operation = storageFile.OpenAsync(FileAccessMode.Read);
IRandomAccessStream stream = await operation;
bitmapImage.SetSource(stream);
return bitmapImage;
}
then call all that in the OnNavigateTo event since the constructor can't be async
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
_imageList = new ImagesList();
await _imageList.Initialize();
foreach (var image in _imageList.Images)
{
Image img = new Image() { Source = image.Source };
img.Width = img.Height = 200;
img.Margin = new Thickness(20, 0, 20, 0);
img.ImageFailed += image_ImageFailed;
img.PointerEntered += img_PointerEntered;
img.PointerExited += img_PointerExited;
sp_MainStackPanel.Children.Add(img);
}
}
thanks again guys !
In my app i need to open a local image for cropping. I tried this by setting the path of the image as source to a BitmapImage but it raising an error. How i can read and assign that local image to BitmapImage in WP Mango.
private WriteableBitmap ReadLocalImage(string Uri)
{
StreamResourceInfo sri = null;
Uri uri = new Uri(Uri, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.CreateOptions = BitmapCreateOptions.None;
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
return wb;
}
use this method for reading local image.