is there a way to convert a UWP WriteableBitmap to a XamarinForms Image? Trying a simple convert ends up with "cannot implicitly convert type WriteableBitmap to Xamarin Forms Image".
Do I have to convert it before to a base64 string? Or how would you handle that?
thanks
You could find FromStream method in the Xamarin.Forms.ImageSource. For your requirement, you could get stream of WriteableBitmap form uwp project via DependencyService. And converter it to ImageSource in the PCL.
Example:
Interface
public interface IStreamToImage
{
Task GetStreamFormUWP(Action<Stream> StreamBlock);
}
implement
public async Task GetStreamFormUWP(Action<Stream> StreamBlock)
{
await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => {
.......
using (Stream stream = MyBitmap.PixelBuffer.AsStream()){
await stream.WriteAsync(sourcePixels, 0, sourcePixels.Length);
StreamBlock(stream);
}
});
}
Usage
await DependencyService.Get<IStreamToImage>().GetStreamFormUWP( (stream) =>
{
image.Source = ImageSource.FromStream(() => stream);
});
Related
I have a camera plugin in NativeScript 6.0 that returns a ByteArray under Android when taking a picture. How do I load this into an ImageSource? I cannot load it directly or the app will crash.
You can load a ByteArray using the ImageSource.fromData() method. However, under Android, ImageSource will only accept an input stream:
const input = new java.io.ByteArrayInputStream(myByteArray);
const imageSource = new ImageSource();
imageSource.fromData(input).then(() => {
stuff();
});
I'm getting a .PNG image file from an API like so
public static async Task<CachedImage> GetImage(string UserID)
{
var URL = "assumeThisUrlPointsToServer"
HttpClient client = new HttpClient();
Stream stream = await client.GetStreamAsync(URL);
return new CachedImage { Source = ImageSource.FromStream(() => stream) };
}
and I am getting a file back and I am displaying it like so
<ffimageloading:CachedImage HeightRequest="52" Margin="13,0,16,0" Source="{Binding SourceOfReturnedCachedImage}"/>
Unfortunately, this is not working (blank). How do I get it to work?
Additional details : if I change it to an Image instead of CachedImage, then it works.
Now the funny thing is that if i specify a URI instead of downloading a file, like so,
return new CachedImage { Source = ImageSource.FromUri('http://www.website.com/image.png')};
Then it (CachedImage) works!
Stream is disposed after every image load, you must modify your code to:
public static async Task<CachedImage> GetImage(string UserID)
{
var URL = "assumeThisUrlPointsToServer"
HttpClient client = new HttpClient();
return new CachedImage { Source = ImageSource.FromStream(() => {
return await client.GetStreamAsync(URL);
})};
}
So xamarin provides a simple way to view images, you can just give the url of the image as the source of image/cachedimage so
<ffimageloading:CachedImage HeightRequest="52" Margin="13,0,16,0" Source="{Binding ImageURL}"/>
Where ImageURL is the URL I was downloading the image from
I have a picture of item in external storage (that was saved by intent in my app). I want to display this picture in Image view in my shared project.
Image.Source takes object of ImageSource type. I tried ImageSource.FromFile, ImageSource.FromStream and even ImageSource.FromUri. The result is always that image is not displayed (no error or exception). I validated that the path to file is correct by first opening it with File.Open one line above.
What is the correct way of displaying pictures from normal storage, not from assets/resources/etc?
This code does not work:
var path = "/storage/emulated/0/Pictures/6afbd8c6-bb1e-49d3-838c-0fa809e97cf1.jpg" //in real app the path is taken from DB
var image = new Image() {Aspect = Aspect.AspectFit, WidthRequest = 200, HeightRequest = 200};
image.Source = ImageSource.FromFile(path);
Your Xamarin Forms PCL don't know what its a URI from Android beacuse its platform specific, so:
ImageSource.FromFile(path);
won't work.
In that case you are handling platform specific features, that is loading an image from Android.
I suggest this approach:
Create an interface on Xamarin Forms PCL like:
public interface IPhoto
{
Task<Stream> GetPhoto ();
}
Then in Android you implement that interface and register the implementation in DependencyService:
[assembly: Xamarin.Forms.Dependency(typeof(PhotoImplementation))]
namespace xpto
{
public class PhotoImplementation : Java.Lang.Object, IPhoto
{
public async Task<Stream> GetPhoto()
{
// Open the photo and put it in a Stream to return
var memoryStream = new MemoryStream();
using (var source = System.IO.File.OpenRead(path))
{
await source.CopyToAsync(memoryStream);
}
return memoryStream;
}
}
}
In the Xamarin Forms PCL code get the image:
var image = ImageSource.FromStream ( () => await DependencyService.Get<IPhoto>().GetPhoto());
For more detail you can consult this.
NOTE1: This will work on iOS if you implement the interface IPhoto too.
NOTE2: There exist a helpful library for this kind of features from Xamarin-Forms-Labs called Camera.
UPDATE (Shared Project solution)
As requested in the comments, to use this in a Shared Project instead of PCL we could do this.
1 - Place the IPhotoInterface in the Shared Project.
2 - Implement the interface in Android/iOS project:
public class PhotoImplementation : IPhoto
{
public async Task<Stream> GetPhoto()
{
// Open the photo and put it in a Stream to return.
}
}
3 - Use it in the Shared Project:
IPhoto iPhotoImplementation;
#if __ANDROID__
iPhotoImplementation = new shared_native.Droid.GetPicture();
#elif __IOS__
iPhotoImplementation = new shared_native.iOS.GetPicture();
#endif
var image = ImageSource.FromStream ( () => await iPhotoImplementation.GetPhoto());
NOTE: shared_native is the namespace of my solution and Droid/iOS are the projects for Android and iOS.
I am new to xamarin.in my project open gallery for select image for this i have used IMediaPicker interface.my code as below:
IMediaPicker mediaPicker;
ImageSource imageSource;
async void OnTapEntertainer(object sender, EventArgs args)
{
await TakePicture();
}
private async Task TakePicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
Imgmn.Source = imageSource;
}
I got mediaPicker is null value in this code.Please help me to solve this issue.
I have added capability required for perform function.
To use MediaPicker item from XLabs please double check you have comleted all the items below:
Add a reference to XLabs.IoC to all of your projects (PCL, Android, iOS, etc.)
Initialize Resolver using the following code snippet:
var resolverContainer = new SimpleContainer();
resolverContainer.Register<IMediaPicker, MediaPicker>()
.Register<IDependencyContainer>(t => resolverContainer);
Resolver.SetResolver(resolverContainer.GetResolver());
Put this code before Xamarin.Forms.Forms.Init method for each platform in your solution.
Use var mediaPicker = Resolver.Resolve<IMediaPicker>(); to get the instance.
As per the comments following process resolves the issue:
Add Dependency Service class in .Droid library project to resolve IMediaPicker as given in example and use [assembly:Xamarin.Forms.Dependency(typeof(MediaPicker))] Reference
I have svg xml that i can convert to ImageSource or FileImageSource by using XamSVG library in the PCL project of my xamarin.forms.
I want to convert the ImageSource / FileImageSource to byte array (to get the bitmap).
Is this possible ?
ImageSource doesn't expose any mechanism to retrieve the original image source. Instead, you will need to manually keep a reference to the original source you use to create the image.
I've found the solution.
StreamImageSource streamImageSource = (StreamImageSource) some image source...
System.Threading.CancellationToken cancellationToken = System.Threading.CancellationToken.None;
Task<Stream> task = streamImageSource.Stream(cancellationToken);
Stream stream = task.Result;
Another solution:
public static byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Stream and MemoryStream are System.IO classes.
Then use it like this:
byte[] TargetImageByte = ReadFully(_data.Source);
_data.source is MediaFile type.