Retrieving Images from Resource folder in C# windows form application - c#

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
}
}

Related

unable to update zip file in Azure File Share/Blob

I am using Azure File share I want to create zip file only once but wants to update it multiple times (upload multiple files after once created).
is it possible to create .zip file only once and add more files in it later without **overriding **existing files in zip.?
when i tried to add more files in .zip it overrides existing files in zip with new file.
private static async Task OpenZipFile()
{
try
{
using (var zipFileStream = await OpenZipFileStream())
{
using (var zipFileOutputStream = CreateZipOutputStream(zipFileStream))
{
var level = 0;
zipFileOutputStream.SetLevel(level);
BlobClient blob = new BlobClient(new Uri(String.Format("https://{0}.blob.core.windows.net/{1}", "rtsatestdata", "comm/2/10029.txt")), _currentTenantTokenCredential);
var zipEntry = new ZipEntry("newtestdata")
{
Size = 1170
};
zipFileOutputStream.PutNextEntry(zipEntry);
blob.DownloadToAsync(zipFileOutputStream).Wait();
zipFileOutputStream.CloseEntry();
}
}
}
catch (TaskCanceledException)
{
throw;
}
}
private static async Task<Stream> OpenZipFileStream()
{
BlobContainerClient mainContainer = _blobServiceClient.GetBlobContainerClient("comm");
var blobItems = mainContainer.GetBlobs(BlobTraits.Metadata, BlobStates.None);
foreach (var item in blobItems)
{
if (item.Name == "testdata.zip")
{
BlobClient blob = new BlobClient(new Uri(String.Format("https://{0}.blob.core.windows.net/{1}", "rtsatestdata", "comm/testdata.zip")), _currentTenantTokenCredential);
return await blob.OpenWriteAsync(true
, options: new BlobOpenWriteOptions
{
HttpHeaders = new BlobHttpHeaders
{
ContentType = "application/zip"
}
}
);
}
}
}
private static ZipOutputStream CreateZipOutputStream(Stream zipFileStream)
{
return new ZipOutputStream(zipFileStream)
{
IsStreamOwner = false,
};
}
This is not possible in Azure storage. The workaround would be to download the zip, unzip it, add more files, re-zip it, and re-upload to storage.

C# how can I extract photos from a zip file faster and more efficiently without extracting them using ZipArchive

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

How to get drawable path?

public async Task<List<AppItem>> GetAndroidApps()
{
try
{
var apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
foreach(var item in apps)
{
string packageName = item.PackageName;
string appName = item.LoadLabel(Android.App.Application.Context.PackageManager);
var appIcon = item.LoadIcon(Android.App.Application.Context.PackageManager).ToString();
System.Diagnostics.Debug.WriteLine($"{appIcon}; {appName}; {packageName};");
}
return null;
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return null;
}
}
How I can get appIcon path to display it?
I can't get full path to other app icon...
Thank you!
Best wishes!
You could load the icon from the drawable resource identifier (in the package's resources) of this component's. And set the imagesource for imageview.
I use my App6 for example to load the icon. It works.
var apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
foreach (var item in apps)
{
string packageName = item.PackageName;
string appName = item.LoadLabel(Android.App.Application.Context.PackageManager);
if (packageName == "com.companyname.app6")
{
var appIcon = item.LoadIcon(Android.App.Application.Context.PackageManager).ToString();
var image = item.Icon;
imageView.SetImageResource(image);
}
//System.Diagnostics.Debug.WriteLine($"{appIcon}; {appName}; {packageName};");
}
Updated:
You could use the DependentService to do that.
I convet the resID of deawable to bitmap and then convert the bitmap to stream. At last, i set the image source form the stream in Xamarin.forms.
Create the interface in Xamarin.forms.
public interface GetIcon
{
byte[] GetIconFromApp();
}
Implementation in Android:
[assembly: Dependency(typeof(GetIconFromApp_Android))]
namespace App13.Droid
{
class GetIconFromApp_Android : GetIcon
{
public byte[] GetIconFromApp()
{
var apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
byte[] bitmapData=null;
foreach (var item in apps)
{
string packageName = item.PackageName;
string appName = item.LoadLabel(Android.App.Application.Context.PackageManager);
if (packageName == "com.companyname.app6")
{
var appIcon = item.LoadIcon(Android.App.Application.Context.PackageManager).ToString();
var imageID = item.Icon;
// Converting Drawable Resource to Bitmap
var bitmap = BitmapFactory.DecodeResource(Forms.Context.Resources, imageID);
//comver bitmap to byte
using (var stream = new MemoryStream())
{
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
}
}
return bitmapData;
}
}
}
Platform implementations with button click event.
private void Button_Clicked(object sender, EventArgs e)
{
var ImageByteArray = DependencyService.Get<GetIcon>().GetIconFromApp();
image.Source = ImageSource.FromStream(() => new MemoryStream(ImageByteArray, 0, ImageByteArray.Length));
}
Screenshot:

Error with assign StorageFile with CreateFileAsync in UWP

I'm suffered from making text files with UWP.
I've experienced how to make a text file in UWP.
but when I tried to make own my program, I got some problems with Creating File. I don't know where is the reason from. the lack of my knowledge about C# class p? or misuse of builtin Class(like storageFile etc...) function?
I made my application to read files from device and save as a another file.
but It doesn't work at all.
when I use break point to figure out what is problem.
Picture1. outputFile is setted as a null
you can see i.outputFile(type StorageFile) is setted as a null. but with my intent, it shouldn't be remained as a null.
because I set its(i's) outputFile with member function called "setOutFile(StorageFolder)". you can see in the picture above.
below is my source code which handle my ClassType. it stops when meet FileIO.WriteTextAsync ... because i.outPutFile is null.
public async Task<List<string>> DoRandom(FileLists fl, StorageFolder folder)
{
FileLists retLists = new FileLists();
List<string> encodingList = new List<string>();
foreach (UploadedFile i in fl)
{
// read stream from storagefile
Stream s = await i.originFile.OpenStreamForReadAsync();
// streamreader from stream
StreamReader sr = new StreamReader(s, Encoding.ASCII);
i.setOutFile(folder);
if (sr.CurrentEncoding == Encoding.ASCII)
{
encodingList.Add("ASCII " + i.outputName);
}
string str = await sr.ReadToEndAsync();
StringBuilder stringBuilder = new StringBuilder(str);
if (Option1)
{
doOption1(stringBuilder);
}
await FileIO.WriteTextAsync(i.outputFile, stringBuilder.ToString());
if (Option1);
};
return encodingList;
}
in Uploaded Class (you can just see setOutFile function).
class UploadedFile
{
public StorageFile originFile;
public StorageFile outputFile { get; set; }
public string inputName {get; private set; }
public string outputName {get; private set; }
public string fileSz{get; private set;}
public UploadedFile(StorageFile storageFile)
{
originFile = storageFile;
inputName = storageFile.Name;
}
public async Task GetFileSz()
{
var bp = await originFile.GetBasicPropertiesAsync();
this.fileSz = string.Format("{0:n0} Byte", bp.Size);
}
public async void setOutFile(StorageFolder folder)
{
var rand = new Random();
string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuilder result = new StringBuilder(13);
for (int i=0; i<13; i++)
{
result.Append(charset[rand.Next(charset.Length)]);
}
StringBuilder outputName = new StringBuilder();
outputName.Append(inputName.Substring(0, inputName.Length - 4));
outputName.Append("_");
outputName.Append(result);
outputName.Append(".txt");
this.outputName = outputName.ToString();
outputFile = await folder.CreateFileAsync(outputName.ToString(), CreationCollisionOption.ReplaceExisting);
for (int i = 0; i <= 10000; i++) // break point
i++;
}
when I insert a assignment(below) in constructor.
outputFile = storageFile;
it barely make a file in target directory with purposed fileName. but it has no data in it!!!..... I tried with below source Code but it has no data in it, either.
await FileIO.WriteTextAsync(i.outputFile, "constant String");
my app makes file with edited constructor, but it has no data in it.
I don't know what is my problem, C# Class syntax or ...what?
Thanks all of you, guys who commented on my posts.
I desperately tried to figure out what is problem, I met. I carefully read your comments and I think your advice is definitely good.
but the problem that I met was, Straightforwardly, sync,async- matter thing. I struggled with this problem with more than 5 hours, and I found the class's member function setOutfile has async function "StorageFoder.CreateFileAsync" and when the machine read that statement, It create asynchronously and begin to write some text(implemented in handler class) on It even It's not created.
...In myType Class, I changed my member function's type from async void to async Task.
public async Task setOutFile(StorageFolder folder)
{
var rand = new Random();
string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuilder result = new StringBuilder(13);
for (int i=0; i<13; i++)
{
result.Append(charset[rand.Next(charset.Length)]);
}
StringBuilder outputName = new StringBuilder();
outputName.Append(inputName.Substring(0, inputName.Length - 4));
outputName.Append("_");
outputName.Append(result);
outputName.Append(".txt");
this.outputName = outputName.ToString();
if (folder != null)
{
outputFile = await folder.CreateFileAsync(outputName.ToString(), CreationCollisionOption.ReplaceExisting);
}
}
and then in handler class member function, i just added await keyword before i.setOutFile(StorageFolder ..)
public async Task<List<string>> DoRandom(FileLists fl, StorageFolder folder)
{
FileLists retLists = new FileLists();
List<string> encodingList = new List<string>();
foreach (UploadedFile i in fl)
{
// read stream from storagefile
Stream s = await i.originFile.OpenStreamForReadAsync();
// streamreader from stream
StreamReader sr = new StreamReader(s, Encoding.ASCII);
await i.setOutFile(folder) ; // wait until setOutFile ends
if (sr.CurrentEncoding == Encoding.ASCII)
{
encodingList.Add("ASCII " + i.outputName);
}
string str = await sr.ReadToEndAsync();
StringBuilder stringBuilder = new StringBuilder(str);
if (Option1)
{
doOption1(stringBuilder);
}
await FileIO.WriteTextAsync(i.outputFile, stringBuilder.ToString());
if (Option1);
};
return encodingList;
}
and It works, thanks all you guys.

Convert StorageFile to WriteableBitmap WP8.1 Silverlight

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);
}
}

Categories

Resources