well i try a lot of things but i don't really understand everything of save in localstorage. I know how its work since the camera, but i don't know how to make it with inkManager. If you're any ideas ?
This is my code to save where the user wants, but i would like to "auto-save" in localstorage :
private async void save_Button(object sender, RoutedEventArgs e)
{
if (_inkManager.GetStrokes().Count > 0)
{
try
{
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = ".jpg";
save.FileTypeChoices.Add("JPG", new string[] { ".jpg" });
StorageFile filesave = await save.PickSaveFileAsync();
IOutputStream ab = await filesave.OpenAsync(FileAccessMode.ReadWrite);
if (ab != null)
await _inkManager.SaveAsync(ab);
// await save.CopyAsync(ApplicationData.Current.LocalFolder, "merge1.jpg");
if (save != null)
{
Clipboard.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appdata:///local/merge1.jpg"));
}
}
catch (Exception)
{
}
}
}
The solution is pretty easy finally :
StorageFile myMerge = await ApplicationData.Current.LocalFolder.CreateFileAsync("myimg.png");
IOutputStream ac = await myMerge.OpenAsync(FileAccessMode.ReadWrite);
if (ac != null)
await _inkManager.SaveAsync(ac);
Related
I am implementing OCR in xamarin forms. I am using TesseractApi following Tesseract OCR for Xamarin (part 1), xocr and MediaPlugin. The implementation is straightforward from saved/captured image, but I am looking is to perform OCR from the frames not from the saved pic.
private async void Button_Clicked(object sender, EventArgs e)
{
if (
!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("No Upload", "Picking photo is not supported!", "OK");
return;
}
if (!_tesseractApi.Initialized)
await _tesseractApi.Init("eng");
var photo = await TakePic(); //capture picture
if (photo != null)
{
var tessResult = await _tesseractApi.SetImage(photo);
if (tessResult)
{
recognizedTextLabel.Text = _tesseractApi.Text;
}
}
}
private async Task<Stream> TakePic()
{
var file = await CrossMedia.Current.PickPhotoAsync();
if (file != null)
{
//show stream in image - this is for test only
img.Source = ImageSource.FromStream(() =>
{
return file.GetStream();
});
//return stream for ocr reading
return file.GetStream();
}
return null;
}
I started a windows form application which imports images from files and store them and specify a radio button to each one.
it have a button with the name 'Lock'
so if user select one radio button and then press the button the app should change the lock screen image and then Lock the screen.
But I don't know how to set the image and lock the screen.
I googled later and the answer about the LockScreen.blabla didn't work for me because I can't do using windows.system.userprofile;
If some one get me the assembly i will do the thing.
there is the events:
private void rB_CheckedChanged(object sender, EventArgs e)
{
MyRadioButton radioButton = sender as MyRadioButton;
pictureBox1.Image = radioButton.Image;
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
foreach (Control control in FindForm().Controls)
{
if (control.GetType() == typeof(MyRadioButton))
{
MyRadioButton mrb = control as MyRadioButton;
if (mrb.Checked == true)
{
mrb.Image = pictureBox1.Image;
}
}
}
}
}
private void btnLock_Click(object sender, EventArgs e)
{
//should set the lock screen background
LockScreen.LockScreen.SetImageFileAsync(imagefile);//shows error 'the name lock screen does not exist
}
I have made a UWP application to use the LockScreen class provided by windows.userProfile.dll And the event's changed to:
private Dictionary<string, string> Images = new Dictionary<string, string>();
private async void btnLock_Click(object sender, RoutedEventArgs e)
{
string path;
if (Images.TryGetValue(selectedRadioButton.Name, out path))
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
await LockScreen.SetImageFileAsync(file);
try
{
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("http://localhost:8080/lock/");
HttpStringContent content = new HttpStringContent(
"{ \"pass\": \"theMorteza#1378App\" }",
UnicodeEncoding.Utf8,
"application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw ex;
}
}
}
private async void btnBrowse_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
using (var imageStream = await file.OpenReadAsync())
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(imageStream);
image.Source = bitmapImage;
}
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
await file.CopyAsync(storageFolder, selectedRadioButton.Name+file.FileType,NameCollisionOption.ReplaceExisting);
addOrUpdate(selectedRadioButton.Name, Path.Combine(storageFolder.Path, selectedRadioButton.Name + file.FileType));
save();
}
}
private async void rb_Checked(object sender, RoutedEventArgs e)
{
RadioButton rb = sender as RadioButton;
selectedRadioButton = rb;
btnBrowse.IsEnabled = true;
string path;
if (Images.TryGetValue(rb.Name, out path))
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
using (var imageStream = await file.OpenReadAsync())
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(imageStream);
image.Source = bitmapImage;
}
}
}
private void addOrUpdate(string key, string image)
{
if (Images.Keys.Contains(key))
{
Images.Remove(key);
Images.Add(key, image);
}
else
{
Images.Add(key, image);
}
}
private async void save()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await storageFolder.CreateFileAsync("sample.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, JsonConvert.SerializeObject(Images));
}
private async void load()
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt");
string fileText = await FileIO.ReadTextAsync(sampleFile);
try
{
Images = JsonConvert.DeserializeObject<Dictionary<string, string>>(fileText);
}
catch (Exception)
{
}
}
and you can see in the lock button click event there is a request to a web server cause you cannot directly lock the screen in a UWP app and you can follow the rest of your question in my next answer to the question "why I can't directly lock screen in UWP app?and how to do so?".
I'm developing a C#/Xaml UWP text editing app that uses the RichEditBox control for editing text files from. However, I've noticed when I load larger files (~1mb and above, perhaps even less) that the control struggles in a couple of key areas: 1) it takes a while to load the contents of the file and 2) once it finally has, scrolling is very jerky and input into the file is neither smooth nor responsive.
The closest answer I've come across is this (what it describes is exactly the problem I'm having) but it doesn't appear to be applicable to a UWP app.
EDIT:
When I open a file, the noteworthy code to share is:
_currentFile.Content = await readFile(file);
_currentFile._richeditbox.Document.SetText(TextSetOptions.None, _currentFile.Content);
This is the readFile() function, which was helped via https://social.msdn.microsoft.com/Forums/sqlserver/en-US/0f3cd056-a2e3-411b-8e8a-d2109255359a/uwpc-reading-ansi-text-file?forum=wpdevelop:
private async Task<string> readFile(StorageFile file)
{
string charSet = null;
try
{
await Task.Run(() =>
{
try
{
using (FileStream fs = System.IO.File.OpenRead(file.Path))
{
Ude.CharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
charSet = cdet.Charset;
}
}
catch (Exception ex)
{
}
});
}
catch (Exception e)
{
}
Classes.File._lastEncoding = charSet;
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string content = "";
if (charSet == "windows-1252")
{
content = Encoding.GetEncoding("iso-8859-1").GetString(fileContent, 0, fileContent.Length);
}
else if (charSet == "UTF-16LE")
{
content = Encoding.Unicode.GetString(fileContent, 0, fileContent.Length);
}
else if (charSet == "UTF-16BE")
{
content = Encoding.BigEndianUnicode.GetString(fileContent, 0, fileContent.Length);
}
else
{
content = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
}
return content;
}
When debugging, there's absolutely no delay when the readFile() function is called; it gets executed very quickly.
I've tried loading a 1.14mb text file. It takes some time to load, and when it does although the scrollbar height indicates all of it has loaded, it actually doesn't display any text from line 2098 onwards (there are 3,771 lines in total); it stops at this line consistently even on subsequent reloads.
See picture:
As you can also see the last line that is visible gets mashed up with the line above it.
For reference, the file I'm having the problems with can be downloaded from here (but to be clear it's a problem with all text files of a similar size, and possibly much less even): http://mtrostyle.net/appytext/testfile.txt.
Yes, I get the same result in my side when I load you provide txt file. I has been reporting this issue to related team. Currently, one workaround to show the file is that render the text in the WebView control. And the set import and export for the WebView. For more you could refer to WebView.
<body>
<textarea id="input" style="width:100%; height:400px;"></textarea>
<script type="text/javascript">
function SetText(text) {
document.getElementById('input').textContent = text;
}
function SaveText() {
var note = document.getElementById('input').textContent;
window.external.notify(note);
}
</script>
</body>
MainPage.xaml
<WebView x:Name="MyWebView" Source="ms-appx-web:///HomePage.html" Height="400" />
MainPage.xaml.cs
public MainPage()
{
this.InitializeComponent();
MyWebView.ScriptNotify += MyWebView_ScriptNotify;
}
private void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
var saveText = e.Value.ToString();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileOpenPicker open =
new Windows.Storage.Pickers.FileOpenPicker();
open.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
open.FileTypeFilter.Add(".rtf");
open.FileTypeFilter.Add(".txt");
Windows.Storage.StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
var Content = await readFile(file);
string[] args = { Content };
await MyWebView.InvokeScriptAsync("SetText", args);
}
}
private async Task<string> readFile(StorageFile file)
{
string charSet = null;
try
{
await Task.Run(async () =>
{
try
{
using (var fs = await file.OpenAsync(FileAccessMode.Read))
{
var tem = fs.AsStream();
Ude.CharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(tem);
cdet.DataEnd();
charSet = cdet.Charset;
}
}
catch (Exception ex)
{
}
});
}
catch (Exception e)
{
}
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string content = "";
if (charSet == "windows-1252")
{
content = Encoding.GetEncoding("iso-8859-1").GetString(fileContent, 0, fileContent.Length);
}
else if (charSet == "UTF-16LE")
{
content = Encoding.Unicode.GetString(fileContent, 0, fileContent.Length);
}
else if (charSet == "UTF-16BE")
{
content = Encoding.BigEndianUnicode.GetString(fileContent, 0, fileContent.Length);
}
else
{
content = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
}
return content;
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
await MyWebView.InvokeScriptAsync("SaveText", null);
}
I have a PCL type app and I'm using the Xam.Plugin.Media plugin. I need it to ensure a user submits a photo from the camera before they can continue.
To do this I show the camera page from a button click event and I want to ensure that in case the user cancels out of this that the app launches the camera again, this would repeat until a photograph is stored.
Currenty my app falls in the onActivityResumed method of the MainApplication file when the user cancels out of the camera
Attached photo of my code, My code.
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
}
file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
PhotoSize = PhotoSize.Small,
});
//IsRunning = true;
if (file != null)
{
ImageSource = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
}
IsRunning = false;
}
Aside from the fact that it is usually a bit of a UX issue to force a user into anything nowadays, the question still has some merits.
this is the approach that I would consider, it involves recursion.
private async void TakePicture()
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
}
file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
PhotoSize = PhotoSize.Small,
});
//IsRunning = true;
if (file != null)
{
ImageSource = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
}
else
{
// Recursion - I believe that this would continue until the file is not null, then it would carry on.
TakePicture();
}
IsRunning = false;
}
I can't say I use recursion that often, but I think it might do the trick here.
i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}
Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}
i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete
/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}