Set Image.Source to file in external storage in Xamarin.Forms -
i have picture of item in external storage (that saved intent in app). want display picture in image
view in shared project.
image.source
takes object of imagesource
type. tried imagesource.fromfile
, imagesource.fromstream
, imagesource.fromuri
. result image not displayed (no error or exception). validated path file correct first opening file.open
1 line above.
what correct way of displaying pictures normal storage, not assets/resources/etc?
this code does not work:
var path = "/storage/emulated/0/pictures/6afbd8c6-bb1e-49d3-838c-0fa809e97cf1.jpg" //in real app path taken db var image = new image() {aspect = aspect.aspectfit, widthrequest = 200, heightrequest = 200}; image.source = imagesource.fromfile(path);
your xamarin forms pcl don't know uri android beacuse platform specific, so:
imagesource.fromfile(path);
won't work.
in case handling platform specific features, loading image android. suggest approach:
create interface on xamarin forms pcl like:
public interface iphoto { task<stream> getphoto (); }
then in android implement interface , register implementation in dependencyservice
:
[assembly: xamarin.forms.dependency(typeof(photoimplementation))] namespace xpto { public class photoimplementation : java.lang.object, iphoto { public async task<stream> getphoto() { // open photo , put in stream return var memorystream = new memorystream(); using (var source = system.io.file.openread(path)) { await source.copytoasync(memorystream); } return memorystream; } } }
in xamarin forms pcl code image:
var image = imagesource.fromstream ( () => await dependencyservice.get<iphoto>().getphoto());
for more detail can consult this.
note1: work on ios if implement interface iphoto too.
note2: there exist helpful library kind of features xamarin-forms-labs called camera.
update (shared project solution)
as requested in comments, use in shared project instead of pcl this.
1 - place iphotointerface
in shared project.
2 - implement interface in android/ios project:
public class photoimplementation : iphoto { public async task<stream> getphoto() { // open photo , put in stream return. } }
3 - use in 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
namespace of solution , droid/ios
projects android , ios.
Comments
Post a Comment