I am developing this application where I am able to get all the pictures from picture library as StorageFile data type. now I want to change it to writeablebitmap, apply a sketch filter and show in image control. can someone please help me in changing the data type from StorageFile to writeablebitmap?
here is my code:
StorageFolderpicturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageFile> file = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(file.Count > 0)
{
foreach(StorageFile f in file)
{
// the code for changing the data type will go here
}
This code works for me.
if (file.Count > 0)
{
foreach (StorageFile f in file)
{
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
WriteableBitmap bmp = new WriteableBitmap((int)properties.Width, (int)properties.Height);
bmp.SetSource((await f.OpenReadAsync()).AsStream());
// Ready to go with bmp
}
}
Try this, it should work:
IReadOnlyList<IStorageFile> files = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
if(files.Count > 0)
{
var images = new List<WriteableBitmap>();
foreach(var f in files)
{
var bitmap = new WriteableBitmap(500, 500);
using (var stream = await f.OpenAsync(FileAccessMode.ReadWrite))
{
bitmap.SetSource(stream);
}
images.Add(bitmap);
}
}
Related
I have a xamarin app that reads photos without extracting them into a zip file.
When I click very quickly on the page where the photos should be displayed. Sometimes half doesn't show because the app hasn't been able to read them all yet.
Navigating after that page goes like this
public async void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
Content tappedStep = (Content)MyListView.SelectedItem;
int stepIndex = tappedStep.contentid;
string nextTitle = _protocol.name;
using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black))
{
loading = true;
if (loading)
{
Title = nextTitle;
}
await Navigation.PushAsync(new StepView(_protocol, Title, tappedStep.chaptertitle, stepIndex));
}
((ListView)sender).SelectedItem = null;
}
So if I want to navigate too quickly after the stepview, the photos are often not all there.
This is the code I use to read the photos in the zip file.
private string PathToZip()
{
string folderName = $"protocol-{_protocol.id}-{_protocol.versionnr}.zip";
string extractPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string zipPath = $"{$"{extractPath}"}/{$"{folderName}"}";
return zipPath;
}
private async Task GetImage()
{
try
{
PathToZip();
int currentIndex = GetCurrentIndex();
Content content = _protocol.contents[currentIndex];
string imageName = $"{content.contentid}.jpg";
using (ZipArchive archive = ZipFile.OpenRead(PathToZip()))
{
for (int i = 0; i < archive.Entries.Count; i++)
{
ZipArchiveEntry pictureEntry = archive.Entries[i];
if (pictureEntry.Name == imageName)
{
//for reading the image
byte[] buffer;
long length = pictureEntry.Length;
buffer = new byte[length];
pictureEntry.Open().Read(buffer, 0, (int)length);
myImage.Source = ImageSource.FromStream(() => new MemoryStream(buffer));
}
}
}
}
catch (Exception)
{
}
}
How can I make this more efficient so that if the app hasn't loaded everything yet, when I want to navigate to the next page, the app then waits for each page to be read?
Thanks in advance
I have canvas made from bitMap (photo) and my finger drawings in Xamarin Forms. I need to save it to memory device (perfectly it would be photo roll but could be just memory of device). For now (after googling few hours) i have something like this:
saveButt.Clicked += async(sender, args) =>
{
var newSurface = SKSurface.Create(
(int)canvasView.CanvasSize.Width,
(int)canvasView.CanvasSize.Height,
SKImageInfo.PlatformColorType,
SKAlphaType.Premul);
var canvas = newSurface.Canvas;
if (photoBitmap != null)
{
canvas.DrawBitmap(photoBitmap, new SKRect(0, 0, (float) canvasView.Width, (float) canvasView.Height));
}
foreach (SKPath path in completedPaths)
{
canvas.DrawPath(path, paint);
}
foreach (SKPath path in inProgressPaths.Values)
{
canvas.DrawPath(path, paint);
}
canvas.Flush();
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
};
I don't know how i can get access to memory or photo roll to save it.
#Edit
I tried use PCLStorage plugin to save it and for now it don't throw any exceptions or errors but still when i look through all folders i can't find any new folder or file with those names.
var snap = newSurface.Snapshot();
var pngImage = snap.Encode();
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
CreationCollisionOption.OpenIfExists);
IFile file = await folder.CreateFileAsync("image.png",
CreationCollisionOption.ReplaceExisting);
using (Stream s = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
pngImage.SaveTo(s);
}
I want to trim a music file(mp3) in my UWP win 10 app. I try using Naudio but it's not working in my app, so how can i do it ?
Anyone any ideas?
If you want to trim a mp3 file, you can use Windows.Media.Editing namespace, especially MediaClip class.
By default, this class is used for clipping from a video file. But we can also use this class to trim mp3 file by setting MediaEncodingProfile in MediaComposition.RenderToFileAsync method while rendering.
Following is a simple sample:
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
var pickedFile = await openPicker.PickSingleFileAsync();
if (pickedFile != null)
{
//Created encoding profile based on the picked file
var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(pickedFile);
var clip = await MediaClip.CreateFromFileAsync(pickedFile);
// Trim the front and back 25% from the clip
clip.TrimTimeFromStart = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
clip.TrimTimeFromEnd = new TimeSpan((long)(clip.OriginalDuration.Ticks * 0.25));
var composition = new MediaComposition();
composition.Clips.Add(clip);
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
savePicker.FileTypeChoices.Add("MP3 files", new List<string>() { ".mp3" });
savePicker.SuggestedFileName = "TrimmedClip.mp3";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
//Save to file using original encoding profile
var result = await composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise, encodingProfile);
if (result != Windows.Media.Transcoding.TranscodeFailureReason.None)
{
System.Diagnostics.Debug.WriteLine("Saving was unsuccessful");
}
else
{
System.Diagnostics.Debug.WriteLine("Trimmed clip saved to file");
}
}
}
I've this Xml :
<?xml version="1.0" encoding="utf-8" ?>
<GirlsTimes>
<Angie>00:00:00</Angie>
...
<Nicole>00:00:00</Nicole>
</GirlsTimes>
I've a textbox when you can put a time in format "hh:mm:ss" (TBAngie).
When the focus on this textbox was lost, I want to save the new value in the same Xml file :
private async void TBAngie_LostFocus(object sender, RoutedEventArgs e)
{
try
{
if (!checkContent(TBAngie.Text))
{
TBAngie.Text = string.Empty;
var dialog = new MessageDialog("Veuillez encodez un temps hh:mm:ss svp.");
await dialog.ShowAsync();
}
else
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Indent = true;
using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
string repMaxXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "XML/GirlsTimes.xml");
loadedData = XDocument.Load(repMaxXMLPath);
var items = from item in loadedData.Descendants("GirlsTimes")
where item.Element("Angie").Value != TBAngie.Text
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("Angie", TBAngie.Text);
}
loadedData.Save(xw);
}
}
}
catch (Exception ex)
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
}
}
Apparently the <Angie> node value was update well (I see the updated node in debug mode), but when I refresh the page (quit the current page and reload it), the value was not update. So I think my method to save the new xml was not good but I don't know why...
What I made wrong ? Thanks in advance.
EDIT
Just before loadedData.Save() I've made a .toString() and I've this :
<GirlsTimes>
<Angie>00:12:34</Angie>
...
<Nicole>00:00:00</Nicole>
</GirlsTimes>
The app's install directory is a read-only location. If you need to change file contents, copy it to Windows.Storage.ApplicationData.Current.LocalFolder. So, when your app loads the file, try the LocalFolder location first, if no file is there, read it from InstalledLocation.
Refer to this article for details.
Wouaouhhh, after many searchs and try, I've the solution :
This is my read method (I Know isn't the right way to use try/catch/finally...)) :
private async void GetGirlsTimes()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
try
{
StorageFile textFile = await localFolder.GetFileAsync("GirlsTimes.xml");
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
Stream s = textStream.AsStreamForRead();
loadedData = XDocument.Load(s);
}
}
catch
{
storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("AppData");
storageFile = await storageFolder.GetFileAsync("GirlsTimes.xml");
using (IRandomAccessStream writeStream = await storageFile.OpenAsync(FileAccessMode.Read))
{
Stream s = writeStream.AsStreamForRead();
loadedData = XDocument.Load(s);
}
}
finally
{
...//put the value from loadedData to my differents TextBoxes.
}
}
And this is My Write Method :
var items = from item in loadedData.Descendants("GirlsTimes")
where item.Element("Angie").Name == "Angie"
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("Angie", TBAngie.Text);
}
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = await localFolder.CreateFileAsync("GirlsTimes.xml", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (DataWriter textWriter = new DataWriter(textStream))
{
textWriter.WriteString(loadedData.ToString());
await textWriter.StoreAsync();
}
}
And then I can write/read/update my Xml. Thanks For the help. I Valid Your Answer Nox Noctis :)
I am developing project in C# windows application. I am new to this technology. I declared Image variable in one class and list in another class. I want to retrieve image from Resource folder and store it in list ten times. I wrote code like this but it is returning null.
class clsAddImage
{
public Image m_imgSampleImage;
}
class clsList
{
public List<clsAddImage> lstImage = new List<clsAddImage>();
}
class clsAddImageToList
{
public void AddImgMethod()
{
clsList objlist = new clsList();
int i;
for (i = 0; i < 10; i++)
{
clsAddImage objaddimg = new clsAddImage();
objlist.lstImage.Add(objaddimg);
}
foreach (clsAddImage addimg in objlist.lstImage)
{
string path = "C:\\Users\\c09684\\Documents\\Visual Studio 2010\\Projects\\WindowsFormsAddImage\\WindowsFormsAddImage\\Resources\\Chrysanthemum.jpg";
addimg.m_imgSampleImage = Image.FromFile(path);
}
}
}
public Form1()
{
InitializeComponent();
clsAddImageToList a = new clsAddImageToList();
a.AddImgMethod();
}
I assume that you refer to a Windows8 app? In that case you can not simply program a directory to retrieve information. The user has to choose a directory manually, which you can store for future use. However, you can have access to KnownFolders (for most you have to check Capabilities in the Package.appxmanifest, e.g. Pictures Library), see http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.knownfolders for the options.
With the following task you will be able to retrieve files from a directory, I hope this helps you solving your problem:
public async Task GetFilesFromDisk()
{
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StringBuilder outputText = new StringBuilder();
IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
var images = new List<BitmapImage>();
if (fileList != null)
{
foreach (StorageFile file in fileList)
{
string cExt = file.FileType;
if (cExt.ToUpper() == ".JPG")
{
Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
using (Windows.Storage.Streams.IRandomAccessStream filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
}
}
} // ForEach
}
}