简体   繁体   中英

How I can enable user to select image from gallery using xamarin media plugin and rename the image

I'm using xamarin media plugin; allowing user to select the image and rename the image.

Users are able to rename the photo when they take with camera. But how user can rename the image when when select from gallery using the xamarin media plugin.

I have below code to allow user select the image from the gallery. When user select image; I'm saving it in 'file' variable.

I would like to rename the file and keep it in same location.

    private async void Select_From_Gallery_Button_Clicked(object sender, EventArgs e)
    {
        await CrossMedia.Current.Initialize();
        if (!CrossMedia.Current.IsPickPhotoSupported)
        {
            await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
            return;
        }

        Stream stream = null;

        var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
        {



        });
//Display the path
await DisplayAlert("yes", file.Path, "OK");

I can see the full path of file. I would like to get name out of path and rename the image to different name

Your best option is simply to make a copy of the file with a different name.

First create your interface (in your Xamarin.Forms project)

public interface IFile {
    void Copy ( string fromFile, string toFile );
}

Then, implement the services in each platform.

Android:

[assembly: Xamarin.Forms.Dependency (typeof (FileImplementation))]
namespace File.Droid {
  public class FileImplementation : IFile
  {
      public FileImplementation() {}

      public void Copy(string fromFile, string toFile)
      {
            System.IO.File.Copy(fromFile, toFile);
      }

  }
}

iOS

[assembly: Xamarin.Forms.Dependency (typeof (FileImplementation))]
namespace File.iOS {
  public class FileImplementation : IFile
  {
      public FileImplementation() {}

      public void Copy(string fromFile, string toFile)
      {
            System.IO.File.Copy(fromFile, toFile);
      }

  }
}

Then, in your code call:

var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
        {



        });
DependencyService.Get<IFile>().Copy(file.Path, "YourName.png");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM