c# how to load pictures from picture library, WP8.1 Silverlight - c#

This code takes photos with name face1.jpg, face2.jpg and so on from picture library and shows them. now the problem is that it works for first 9 pictures then it stops. but it is supposed to go through all the pictures in the gallery
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageFile> file = await picturesFolder.GetFilesAsync(CommonFileQuery.OrderByDate);
string fname;
int picSize = 150;
int i = 0;
WriteableBitmap wv = new WriteableBitmap(picSize, picSize);
WriteableBitmap mypic = new WriteableBitmap(picSize, picSize);
if (file.Count > 0)
{
foreach (StorageFile f in file)
{
fname = "face" + i + ".jpg";
if (f.Name == fname)
{
i = i + 1;
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
WriteableBitmap wb = new WriteableBitmap((int)properties.Width, (int)properties.Height);
wb.SetSource((await f.OpenReadAsync()).AsStream());
reSize(wb, wv);
FilterWriteableBitmap(wv, mypic);
img.Source = mypic;
}
}
}
when I try to take photo directly mean when I write if(f.Name=="face10.jpg") then it works but inside the loop it stops at face9.

Change
int i = 0;
to
int i = 1;
Assuming there are 10 files in that folder the foreach will go through 10 times but the first time it will look for face0.jpg and only ever get to face9.jpg.

Related

Read more than one file

I am writing a pdf to word converter which works perfectly fine for me. But I want to be able to convert more than one file.
What happens now is that it read the first file and does the convert process.
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
var doc = application.Documents.Add();
string path = #"C:\Users\Test\Desktop\pdfToWord\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\pdfToWord\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\pdfToWord\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\Test\Desktop\pdfToWord\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
if (inline.Height > inline.Width)
{
inline.ScaleWidth = 250;
inline.ScaleHeight = 250;
}
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
}
}
I thought that with my foreach that problem should not occur. And yes there are more than one pdf in this folder
The line
var doc = application.Documents.Add();
is outside the foreach loop. So you only create a single word document for all your *.pdf files.
Move the above line inside the foreach loop to add a new word document for each *.pdf file.

retrieving a matched name video in MediaElement control WPF

i want to play the video which name is entered in text box. But it does not play the exact video it plays the first video present in folder. any help please..
Code
String vid_name = data.Text;
string complete_name = vid_name.ToLower() + ".mp4";
string root = System.IO.Path.GetDirectoryName("D:/abc");
string[] supportedExtensions = new[] { ".mp4" };
var files = Directory.GetFiles(Path.Combine(root, "Videos"), "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));
List<VideosDetail> videos = new List<VideosDetail>();
VideosDetail id;
foreach (var file in files)
{
id = new VideosDetail()
{
Path = file,
FileName = Path.GetFileName(file),
Extension = Path.GetExtension(file)
};
FileInfo fi = new FileInfo(file);
id.FileName = fi.Name;
id.Size = fi.Length;
videos.Add(id);
if (id.FileName == complete_name)
{
VideoList.ItemsSource = videos; //**Problem comes here
}
else
{
MessageBox.Show("no such video is available. ");
}
}
Since videos is a List, the line
VideoList.ItemsSource = videos;
Points to all the videos in the folder (up to the one that actually matches the filename you entered). Hence, the unwanted result.
You should probably pass the index of the video in your list, something like:
player.Source = videos[x];
Hope this helps!

The process cannot access the file because it is being used by another process error while moving image

I've a folder named testPhotos with some images. Based on the image creation date, I want to create a new folder by image creation year and then move the image to that folder.
For example, testPhotos has image named 01.jpg which was created on 2011. So I want to create a folder named 2011 inside testPhotos like testPhotos\2011 and move image to that folder. While doing this I am getting The process cannot access the file because it is being used by another process. error while moving image from one folder to another.
Code:
private void button1_Click(object sender, EventArgs e)
{
var creationDate = new DateTime();
var dateList = new List<String>();
var fileName = String.Empty;
var sourceFolder = #"C:\My Stuff\Test Porjects\testPhotos";
String[] images = Directory.GetFiles(sourceFolder);
if (images.Count() > 0)
{
foreach (var imagePath in images)
{
fileName = Path.GetFileName(imagePath);
creationDate = GetDateTakenFromImage(imagePath);
var date = creationDate.GetDateTimeFormats()[5].Replace("-", "/");
if (!String.IsNullOrEmpty(date))
{
var year = date.Substring(0, 4);
var destinationFolder = sourceFolder + "\\" + year;
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
String fileToMove = sourceFolder+ "\\" + fileName;
String moveTo = destinationFolder + "\\" + fileName;
File.Move(fileToMove, moveTo);
}
}
}
}
}
private DateTime GetDateTakenFromImage(string path)
{
Image myImage = Image.FromFile(path);
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
Any ideas?
This looks like a missing dispose on the image, try with the following:
private DateTime GetDateTakenFromImage(string path)
{
using (Image myImage = Image.FromFile(path))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = new Regex(":").Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
}

Create, read and manage audio playlist in c#

I am new to C# and currently I am trying to make an audio player using BASS library. Right now I am creating the playlist using INI files like below:
[songs]
1=c:\lamfao.mp3
2=c:\test.mp3
[total_songs]
total=2
Everything is fine, but loading this type of INI file and showing it in ListView consumes a lot of time. Also there's no way to delete a song from this INI files. Hence, I am looking for help regarding loading and creating the playlists in C#. What I wanted to do is create a playlist with songs path and if possible with ID3 information like Album, Artist and Genre.
Also like other media players, for example WinAMP or MediaMonkey, they take no time to display the playlist, how this can be achieved. I am trying to show the playlist in ListView with Type=Details.
Is it possible to avoid the insertion of duplicate song in playlist?
Here's the current code which I am using to read INI files.
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
string name = "";
string album = "";
string artist = "";
string path = "";
if (File.Exists(CurrentPlaylistLocation))
{
this.progressBar1.Visible = true;
IniFile ini = new IniFile(CurrentPlaylistLocation); // INI Reading class in C# using Win32 API wrapper
string Total = ini.IniReadValue("Total_Files", "Total");
int items = Convert.ToInt32(Total);
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = items;
this.progressBar1.MarqueeAnimationSpeed = 100;
this.progressBar1.Style = ProgressBarStyle.Blocks;
int total = 0;
listView1.BeginUpdate();
for (int i = 1; i <= items; i++)
{
path = ini.IniReadValue("songs", Convert.ToString(i));
if(File.Exists(path))
{
// When user deletes a song from playlist, I add a .ignore in the last of song path
// so, check if a song is deleted by user, if deleted then do not add it
if (System.IO.Path.GetExtension(path).ToLower() != ".ignore")
{
PlayerEngine.GetTrackData(path, out name, out artist, out album); // Get META tag using Taglib sharp
lvi = new ListViewItem();
lvi.Text = name;
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = album;
lvi.SubItems.Add(lvsi);
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = artist;
lvi.SubItems.Add(lvsi);
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = path;
lvi.SubItems.Add(lvsi);
this.listView1.BeginUpdate();
this.listView1.Items.Add(lvi);
this.listView1.EndUpdate();
total++;
this.progressBar1.Value = (i);
}
}
}
listView1.EndUpdate();
PlayerEngine.TotalTrackInTempPlaylist = listView1.Items.Count-1; // update the total number of songs loaded in player engine class
this.progressBar1.Visible = false;
MessageBox.Show("Playlist loading completed!");
Thanking you

Auto Copying multiple images and show tile notifications?

This is my code for Windows 8 metro apps, in which I copy 1 image from the local folder to my app storage folder and then it shows a tile notification. Please help me to auto copy all images from Picture Library and then these images shown in tile notifications.
i don't know how to access or copy all images from Picture Library... no user interface for copy images.
public sealed partial class BlankPage : Page
{
string imageRelativePath = String.Empty;
public BlankPage()
{
this.InitializeComponent();
CopyImages();
}
public async void CopyImages()
{
FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
picker.CommitButtonText = "Copy";
StorageFile file = await picker.PickSingleFileAsync();
StorageFile newFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(file.Name);
await file.CopyAndReplaceAsync(newFile);
this.imageRelativePath = newFile.Path.Substring(newFile.Path.LastIndexOf("\\") + 1);
IWideTileNotificationContent tileContent = null;
ITileWideImage wideContent = TileContentFactory.CreateTileWideImage();
wideContent.RequireSquareContent = false;
wideContent.Image.Src = "ms-appdata:///local/" + this.imageRelativePath;
wideContent.Image.Alt = "App data";
tileContent = wideContent;
tileContent.RequireSquareContent = false;
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileContent.CreateNotification());
}
}
1st give the path of images folder and then make a list of these images through IReadOnlyList, and set loop on copy images to end, after that just set timer on TileUpdateManager. and it will work.
to enumerate files in PicturesLibrary:
// from my sample app "MetroContractSample" http://metrocontractsample.codeplex.com/documentation
var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".jpg", ".png", ".bmp", ".gif", }) { FolderDepth = FolderDepth.Deep, };
StorageFileQueryResult query = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
var fileInfoFactory = new FileInformationFactory(query, ThumbnailMode.SingleItem);
IReadOnlyList<FileInformation> fileInfoList = await fileInfoFactory.GetFilesAsync();
NOTE: You have to declare the Capability for PicturesLibrary in Package.appxmanifest.

Categories