Mono for Android Save into Gallery's Directory - c#

Im trying to save into SD card and if is not available into save it into Internal memory on the Gallery, but always showing on the Galley directory. But this code is not saving it or how can i do to show it into Gallerys Directory.
string nameFile = file + ".png";
//Check wether the sd card is available or not
string state = Android.OS.Environment.ExternalStorageState;
bool isExternalStorageAvailable = false;
bool isExternalStorageWritable = false;
string path = null;
if(Android.OS.Environment.MediaMounted.Equals(state))
{
isExternalStorageAvailable = isExternalStorageWritable = true;
//var path = Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic);
path = Android.OS.Environment.ExternalStorageDirectory.ToString();
Toast.MakeText(this, "Saved in SDCard", ToastLength.Short).Show();
}
else if(Android.OS.Environment.MediaMountedReadOnly.Equals(state))
{
isExternalStorageAvailable = true;
isExternalStorageWritable = false;
}
else
{
//path = Android.OS.Environment.DataDirectory;
path = Android.OS.Environment.DirectoryPictures;
Toast.MakeText(this, "Saved in Internal Memory ", ToastLength.Short).Show();
}
//Create a Bitmap screen capture
Android.Graphics.Bitmap bitmap;
View view = v.RootView;
view.DrawingCacheEnabled = true;
bitmap = Android.Graphics.Bitmap.CreateBitmap(view.DrawingCache);
view.DrawingCacheEnabled = false;
System.IO.FileStream fs = null;
try
{
fs = new System.IO.FileStream(path + "/" + nameFile, System.IO.FileMode.OpenOrCreate);
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, fs);
if(isExternalStorageAvailable == true && isExternalStorageWritable == true)
{
//SendBroadcast(new Intent(Intent.ActionMediaMounted, Android.Net.Uri.Parse(path + "/" + nameFile)));
MyMediaConnectorClient client = new MyMediaConnectorClient(path + "/" + nameFile);
MediaScannerConnection scanner = new MediaScannerConnection(this, client);
client.SetScanner(scanner);
scanner.Connect();
}
else
{
Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver, bitmap, nameFile, v.Id.ToString());
}
fs.Flush();
}
catch(FileNotFoundException e)
{
Log.Error("File Not Found Exception", e.ToString());
}
catch(IOException e)
{
Log.Error("IOException", e.ToString());
}
finally
{
if (fs != null)
fs.Close();
dialog.Dismiss();
}

Related

How can I save a User's uploaded image to a temp file that I can access later, but gets deleted after that

I've created an image uploader for users to upload/crop their profile pics. When a user uploads a file, it gets saved to a file that gets accessed immediately after for them to crop it.
I've tried using Path.GetTempPath() as well as Path.GetTempFileName(), but my cropper was unable to locate the file locations for some reason.
Any suggestions are greatly appreciated.
UPDATE: So I added File.Delete(filePath) to the end of btnCropClick, but I get an error saying The process cannot access the file because it is being used by another process. How can I "release" that file to be deleted instantly ?
Below is the code for where a user uploads their orignal image of choice
protected void btnUploadClick(object sender, EventArgs e)
{
//Upload Original Image Here
String UploadFileName = "";
String UploadFilePath = "";
if (fileUploader.HasFile)
{
String ext = Path.GetExtension(fileUploader.FileName).ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
UploadFileName = "orig_" + Guid.NewGuid().ToString() + ext;
UploadFilePath = Path.Combine(Server.MapPath("images/OriginalImages"), UploadFileName);
try
{
fileUploader.SaveAs(UploadFilePath); //TODO: Need to make this a temp file that gets "destroyed" later
imgUpload.ImageUrl = "images/OriginalImages/" + UploadFileName;
panCrop.Visible = true;
}
catch (Exception ex)
{
lblMsg.Text = "Error! Please Try Again. ";
}
}
else
{
lblMsg.Text = "Invalid File Type Selected. | Please Choose .jpg, .jpeg, or .png file only.";
}
}
else
{
lblMsg.Text = "Please Click 'Choose File' & Select An Image To Upload";
}
}
And here is the code for the cropper (Not sure anything in here needs to be changed, but I'll include it anyway for context & relevancy
protected void btnCropClick(object sender, EventArgs e)
{
//Crop Image Here & Save
String fileName = Path.GetFileName(imgUpload.ImageUrl);
String filePath = Path.Combine(Server.MapPath("images/OriginalImages"), fileName);
String cropFileName = "";
String cropFilePath = "";
if (File.Exists(filePath))
{
System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
Rectangle CropArea = new Rectangle(
Convert.ToInt32(X.Value),
Convert.ToInt32(Y.Value),
Convert.ToInt32(W.Value),
Convert.ToInt32(H.Value)
);
try
{
Bitmap bitMap = new Bitmap(CropArea.Width, CropArea.Height);
using (Graphics g = Graphics.FromImage(bitMap))
{
g.DrawImage(orgImg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), CropArea, GraphicsUnit.Pixel);
Bitmap resized = new Bitmap(bitMap, new Size(200, 200)); //Resize image to save as 200x200
cropFileName = "crop_" + fileName; //+UserID so each fileName is unique
cropFilePath = Path.Combine(Server.MapPath("images/CroppedImages"), cropFileName);
resized.Save(cropFilePath); //Where final, cropped image is saved
imgHeadshot.ImageUrl = "images/CroppedImages/" + cropFileName;
}
}
catch (Exception ex)
{
throw;
}
panCrop.Visible = false;
}
}
Was able to dispose of the original file by adding:
orgImg.Dispose();
bitMap.Dispose();
File.Delete(filePath);
to the end of btnCropClick method.

C# Monitoring desktop screen from a Windows service

I have just written the C# Code that is recording the screenshot of the desktop.It works on Winforms but not works in windows service.
My code as below:
public partial class ScreenCapture : ServiceBase
{
bool rec = false;
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
UInt32 frameCount = 0;
VideoFileWriter writer;
int width = SystemInformation.VirtualScreen.Width;
int height = SystemInformation.VirtualScreen.Height;
AForge.Video.ScreenCaptureStream streamVideo;
Stopwatch stopWatch = new Stopwatch();
public ScreenCapture()
{
InitializeComponent();
writer = new VideoFileWriter();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyLog");
}
eventLog1.Source = "MySource";
this.CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
string folderName = #"C:\LoginLog";
if (changeDescription.Reason == SessionChangeReason.SessionLogon)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logon");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
else if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logoff");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionLock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Lock");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Unlock");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
base.OnSessionChange(changeDescription);
}
private void StartRec(string path)
{
if (rec == false)
{
rec = true;
frameCount = 0;
string time = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ssff");
string compName = Environment.UserName;
string fullName = path + "\\" + compName.ToUpper() + "_" + time;
try
{
writer.Open(
fullName + ".mp4",
width,
height,
10,
VideoCodec.MPEG4, 1000000);
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception StartRec: " + ex.Message);
}
DoJob();
}
}
private void DoJob()
{
try
{
Rectangle screenArea = Rectangle.Empty;
foreach (System.Windows.Forms.Screen screen in
System.Windows.Forms.Screen.AllScreens)
{
screenArea = Rectangle.Union(screenArea, screen.Bounds);
}
streamVideo = new ScreenCaptureStream(screenArea);
streamVideo.NewFrame += new NewFrameEventHandler(video_NewFrame);
streamVideo.Start();
stopWatch.Start();
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception DoJob: " + ex.Message);
}
}
private void video_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
try
{
if (rec)
{
frameCount++;
writer.WriteVideoFrame(eventArgs.Frame);
}
else
{
stopWatch.Reset();
Thread.Sleep(500);
streamVideo.SignalToStop();
Thread.Sleep(500);
writer.Close();
}
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception Video New Frame: " + ex.Message);
}
}
}
And the service can save a .mp4 file, but it cannot open it.I think windows service can not capture desktop screen.
Can anybody help me how to solve this problem?
thanks in advance.
You need to set windows service run under interactive account,
To do so you need to go to properties of service got to logon tab and login by
your windows account.

c# and serial port

I'm trying to do an application in c #, which sends a text file through a serial port to a machine.
all good and beautiful if the machine is put in download mode.
if the operator forgets to put the machine on download mode .... here comes the problem, I have a writetimout exception.
I would like to use this exception or anything else to resume the process and my program will try to reload the file into the machine.
below is my code
private void incarca_button_Click(object sender, EventArgs e)
{
string open_folder = cale_txt.Text.Replace(Environment.NewLine, "");
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = open_folder;
if (theDialog.ShowDialog() == DialogResult.OK)
{
var onlyFileName = System.IO.Path.GetFileName(theDialog.FileName);
piesa_lbl.Hide();
piesa_txt.Hide();
SerialPort cnc_com = new SerialPort(com);
cnc_com.BaudRate = Int32.Parse(bit);
parity = parity.ToString();
cnc_com.Parity = (Parity)Enum.Parse(typeof(Parity), parity);
cnc_com.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stop_bit);
cnc_com.DataBits = Int32.Parse(data_bit);
cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
cnc_com.Encoding = Encoding.ASCII;
cnc_com.ReadTimeout = 500;
cnc_com.WriteTimeout = 500;
cnc_com.ReadBufferSize = 1000000;
cnc_com.WriteBufferSize = 1000000;
//cnc_com.DtrEnable = true;
//cnc_com.RtsEnable = true;
try
{
cnc_com.Open();
}
catch (UnauthorizedAccessException) { }
catch (System.IO.IOException) { }
catch (ArgumentException) { }
using (StreamReader sr = new StreamReader(open_folder + #"\" + onlyFileName))
{
while (sr.Peek() >= 0)
{
try
{
cnc_com.WriteLine(sr.ReadLine());
//cnc_com.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flow_control);
}
catch(TimeoutException wtout)
{
MessageBox.Show("Masina nu este pregatita\nReincarcati programul");
cnc_com.Close();
cnc_com = null;
}
}
}
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
}
}
I would like this piece of code to be executed only if the file was passed successfully to the machine
piesa_txt.Show();
piesa_lbl.Show();
piesa_txt.Focus();
//cale_txt.Text = "";
cnc_com.DiscardOutBuffer();
cnc_com.DiscardInBuffer();
cnc_com.Close();
cnc_com = null;
thank you

DataGridView and copy image

I met one problem when I tried to copy file.
Error description
I worked with DataGridView and PictureBox.
Deguber of VS 2015 stopped me at
FileStream fs = File.Open(file, FileMode.Open);
in function CopyFile. I cant understand what's wrong i did.
This is some code (C#, .NET 4.5.1) from main form:
static string CopyFile(string file, string to)
{
FileInfo fileInfo = new FileInfo(file);
byte tmp = 0;
string temp = to + "\\" + fileInfo.Name;
FileStream newFile = File.Open(temp, FileMode.Create);
try
{
FileStream fs = File.Open(file, FileMode.Open);
for (int i = 0; i < fileInfo.Length; i++)
{
tmp = (byte)fs.ReadByte();
newFile.WriteByte(tmp);
}
fs.Close();
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Не вдалося найти файл.");
}
newFile.Close();
return temp;
}
private void WriteNewUserToFile(User item, string pathToFile)
{
StreamWriter sw = new StreamWriter(File.Open(#pathToFile, FileMode.Append, FileAccess.Write));
sw.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}",
item.Id,
item.Image,
item.FirstName,
item.LastName,
item.Email,
item.Phone));
sw.Close();
}
private void btnAddUser_Click(object sender, EventArgs e)
{
AddUserForm dlg = new AddUserForm();
if (dlg.ShowDialog() == DialogResult.OK)
{
User item = dlg.NewUser;
item.Image = CopyFile(item.Image, "images");
WriteNewUserToFile(item, "data/users.dat");
users.Add(item);
//this.AddNewDataGridRow(item);
}
}
And some code of AddNewUserForm:
public User NewUser
{
get { return newUser; }
set { newUser = value; }
}
private void btnImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txtImage.Text = dlg.FileName;
try
{
picboxImage.Image = Image.FromFile(txtImage.Text);
}
catch
{
picboxImage.Image = Image.FromFile(#"images\NoImg.bmp");
}
}
}
private void btnApply_Click(object sender, EventArgs e)
{
NewUser = new User
{
Id = Convert.ToInt32(txtId.Text),
LastName = txtLastName.Text,
FirstName = txtFirstName.Text,
Email = txtEmail.Text,
Phone = txtPhone.Text,
Image = txtImage.Text
};
this.DialogResult = DialogResult.OK;
}
If somebody need all project/code, click here (download VS project).
When you set the Image for the PictureBox using the following code, the call keeps the file handle open. So when you try to open the file again you encounter the exception.
picboxImage.Image = Image.FromFile(txtImage.Text);
According to this accepted answer, when the file handle is closed is unpredictable, in some cases, the handle won't be closed even if you explicitly close the Image.
So you may use the technique in that answer like this, to ensure the file handle is closed properly.
picboxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(txtImage.Text)));

Tesseract Init() method C3

I am using Tesseract 2 with c# .net 4.5
Whenever code reaches to OCR.InIt() method, it comes out of code and program stops execution.
Even Catch block does not hold the code.
Please let me know how to check the problem.
Bitmap image = new Bitmap(ofd_OpenPhoto.FileName);
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
ocr.Init("C:\\tessnet2\\tesseract-ocr\\tessdata", "eng", false);
Please let me know, how to use Init() method, Should I remove null?
private void btn_Browse_Click(object sender, EventArgs e)
{
ofd_OpenPhoto.Multiselect = false;
ofd_OpenPhoto.RestoreDirectory = true;
ofd_OpenPhoto.SupportMultiDottedExtensions = false;
ofd_OpenPhoto.FileName = "";
ofd_OpenPhoto.Title = "Select Photo";
ofd_OpenPhoto.Filter = "Photo Files (*.jpg)|*.jpg";
DialogResult result = ofd_OpenPhoto.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string file_name;
if (ofd_OpenPhoto.FileName != null)
{
try
{
file_name = ofd_OpenPhoto.FileName.Substring(ofd_OpenPhoto.FileName.LastIndexOf("\\") + 1);
txt_PhotoPath.Text = file_name.Substring(0, file_name.LastIndexOf("."));
Emgu.CV.Image<Bgr, Byte> img_o = new Emgu.CV.Image<Bgr, byte>(ofd_OpenPhoto.FileName);
pb_PhotoViewer_O.Image = img_o.ToBitmap();
if (pb_PhotoViewer_O.Image != null)
{
try
{
Bitmap image = new Bitmap(ofd_OpenPhoto.FileName);
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
ocr.Init(#"C:\\Program Files (x86)\\Tesseract-OCR", "eng", false);
List<tessnet2.Word> result1 = ocr.DoOCR(image, Rectangle.Empty);
txt_ExtractedNumber.Text = result1.ToString();
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
//e.Message();
}
}
}
}
This is my code.
Thanks.
If you write ocr.Init("C:\\tessnet2\\tesseract-ocr\\tessdata", "eng", false);
then at C:\tessnet2\tesseract-ocr\tessdata directory you must have next files:
eng.DangAmbigs
eng.freq-dawg
eng.inttemp
eng.normproto
eng.pffmtable
eng.unicharset
eng.user-words
eng.word-dawg
Also you must check that an Windows system environment variable ( TESSDATA_PREFIX ) is deleted

Categories

Resources