I'm working on a project that on the click of a button a random image for a folder I specified will appear in a specific picturebox.
Here's what I have already:
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
Random r = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(r.Next(3).ToString() + ".jpg");
}
}
Now how can i add a relative path to this? My hardcoded path is c:/users/ben/documents/visualstudio/projects/projectnet/resources/pictures.
Thanks in advance!
You could try this in your button1_Click handler:
string imageFileName = r.Next(3).ToString() + ".jpg";
string basePath = #"c:\users\ben\documents\visualstudio\projects\projectnet\resources\pictures";
pictureBox1.Image = Image.FromFile(Path.Combine(basePath, imageFileName);
As mentioned in the comments to your question it is a good idea to read your base directory from an external source, i.e. app.config, if you intend to run your application on a computer other than your own.
Related
I want to create an QrCode using IronBarCode, and then save it as a Stream or Byte[].
However both methods expect the file to be saved prior to creation:
var absolute = Request.Scheme + "://" + Request.Host + url;
var qrcode = IronBarCode.QRCodeWriter.CreateQrCode(absolute);
qrcode.AddAnnotationTextAboveBarcode(device.Name);
qrcode.AddBarcodeValueTextBelowBarcode(absolute);
var f = qrcode.ToJpegStream();
var y = qrcode.ToJpegBinaryData();
ToJpegStream() and ToJpegBinaryData expects the absolute string to be an actual file path. I want to create a QrCode and save it as a Byte[] or Stream, however the error thrown is "The filename, directory name, or volume label syntax is incorrect."
AddBarcodeValueTextBelowBarcode method parameter for string is FontPath. That is why it was trying to find the font file that does not exist.
string absolute = "https://ironsoftware.com/";
string Name = "Product URL:";
//Add Annotation(text) below the generated barcode
var qrcode = QRCodeWriter.CreateQrCode(absolute);
qrcode.AddAnnotationTextBelowBarcode(Name);
qrcode.ToJpegBinaryData();
//Add Barcode value below the generated barcode
var qrcode = QRCodeWriter.CreateQrCode(absolute);
qrcode.AddBarcodeValueTextBelowBarcode();
qrcode.ToJpegBinaryData();
The below image is FontPath. FontPath is actually the directory path that actually lead to the Font file.
//This will add Barcode value into QRCode
.AddBarcodeValueTextBelowBarcode()
If you want to add absolute path to the QRCode you should use
//This will add your text to Barcode
.AddAnnotationTextBelowBarcode(absolute)
For more information on how to use the method please refer to the API reference:
https://ironsoftware.com/csharp/barcode/object-reference/api/IronBarCode.GeneratedBarcode.html#IronBarCode_GeneratedBarcode_AddBarcodeValueTextBelowBarcode
The issue mentioned isn't reproducible with the code provided. The code below is adapted from your code and the from the example. It's been tested.
Create a new Windows Forms App (.NET Framework)
Download/install NuGet package: Barcode
Add a Button to Form1 (name: btnCreateQRCode)
Add a PictureBox to Form1 (name: pictureBox1)
Add using directives:
using IronBarCode;
using System.IO;
Form1.cs:
public partial class Form1 : Form
{
private byte[] _qrCode = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private byte[] CreateBarCode(string url, string annotationText)
{
//create new instance
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCode(url);
qrCode.AddAnnotationTextAboveBarcode(annotationText);
qrCode.AddBarcodeValueTextBelowBarcode(url);
byte[] qrCodeBytes = qrCode.ToJpegBinaryData();
return qrCodeBytes;
}
private void btnCreateQRCode_Click(object sender, EventArgs e)
{
_qrCode = CreateBarCode("https://www.google.com/search?q=how+to+search", "How To Search");
using (MemoryStream ms = new MemoryStream(_qrCode))
{
pictureBox1.Image = Image.FromStream(ms);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //fit to size
pictureBox1.Refresh();
}
}
}
Resources:
Create QR Code
What I tried but not working :
At the bottom of windowMain.xaml.cs I added two new methods for saving and loading :
private void SaveFile(string contentToSave, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName);
File.WriteAllText(saveFilePath, contentToSave);
}
private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}
Then for saving in two places :
private void btnRadarFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxRadarFolder.Text, "radarpath");
textBoxRadarFolder.Text = dlg.SelectedPath;
}
}
private void btnSatelliteFolder_Click(object sender, RoutedEventArgs e)
{
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == true)
{
SaveFile(textBoxSatelliteFolder.Text, "satellitepath");
textBoxSatelliteFolder.Text = dlg.SelectedPath;
}
}
And for loading at the top :
public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath");
But it does nothing no errors no exceptions it's just not loading anything back to the textboxes when running the application and I selected folders first but nothing.
Update :
Saving is working fine.
The problem is with the loading :
At the top I'm doing when running the application :
public MainWindow()
{
InitializeComponent();
LoadFile(textBoxRadarFolder.Text, "radarpath.txt");
LoadFile(textBoxSatelliteFolder.Text, "satellitepath.txt");
But then at the bottom in the LoadFile method I see that the control text to load the content to is empty for some reason even if I entered both textboxes.text to read back it's empty :
The variable loadTo is empty and it should be the textBoxes of the radar and satellite. Why loadTo is empty ?
private void LoadFile(string loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo = File.ReadAllText(saveFilePath);
}
}
This is working I just wonder in case the control in the LoadFile is not TextBox but let's say for example RichTextBox ?
It's working now for my needs but what if I wanted to make the LoadFile method something more generic for any control that have text property content like RichTextBox or Label ? Now I'm using TextBox.
LoadFile(textBoxRadarFolder, "radarpath.txt");
LoadFile(textBoxSatelliteFolder, "satellitepath.txt");
And
private void LoadFile(TextBox loadTo, string fileName)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, fileName); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
loadTo.Text = File.ReadAllText(saveFilePath);
}
}
I am trying to make a program for the car retail firm I work at. When people deliver their cars, a guy has to take pictures of the damages with a Lenovo miix.
The program I've made so far is not smart enough.
It goes like, you write the numberplate in a box, then create a folder with the text from the box.
Then you start the camera, take a picture and save it, and manually have to find the folder and name the file.
Is there a way I can make it smarter with just 2 buttons, one to start the camera and another one to take the picture, and then it automatically saves it in a folder named as the numberplate, and files named 1,2,3,4 and so on.jpg ?
this is my code so far:
namespace Europcar_skade_camera
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
cam.Start();
}
private void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bit = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bit;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = #"C:\tmp\";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void nummerplade_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(#"c:\tmp\" + nummerplade.Text);
}
}
}
Something like this:
Instead of using a SaveFileDialog, you could just create the file path based on the number plate value like this:
var filePath = System.IO.Path.Combine(#"c:\tmp", nummerplade.Text, fileNumber + ".jpeg");
The fileNumber var is the number of files allready in the folder + 1.
var fileNumber = Directory.GetFiles(...).Length + 1
string numberPlate = "21323412";
string path = #"C:\tmp\";
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
You also mentioned that you want incremental names, there are many ways of doing it, personally i'd prefer large hashed name of file like so:
//generate GUID and convert to string.
string filename = Guid.NewGuid().ToString();
//to save picturebox image in folder and use ImageFormat.Your desired format
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg);
But if you want to stick with incremental names:
// you get last name in the folder:
//it gets last filename in folder but with path
var lastFilePath = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
//we remove path from filename and convert it to int.
int lastIndex = Int32.Parse(Path.GetFileNameWithoutExtension(lastFilePath));
//then we increment it by 1
int newName = lastIndex + 1;
//and save it
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
With GUID finally it should look something like this:
string numberPlate = "21323412";
string path = #"C:\tmp\";
private void button2_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
string filename = Guid.NewGuid().ToString();
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
}
I am developing a desktop application using wpf.I will need to store some pictures and show them after.I need a textbox with the link to the database,and that will be saved in a database.They told me that the best approach is to save a image path to the database,not the image itself.
Is that better then blob?I can't find any example with the path on the new,only with blob...
You can save image to the database as a link, but beforehand rename it to GUID to ensure uniqueness of reference you will be storing
/this is my code , and you can save an image into datebase/
namespace WpfApp1
{
public partial class saveImage : Window
{
public saveImage()
{
InitializeComponent();
}
OpenFileDialog Op = new OpenFileDialog();
private void Button_Click(object sender, RoutedEventArgs e)
{
Op.Title = "image selection";
Op.Filter = "JPG(.jpg)|*.jpg|PNG(.png)|*.png|JPEG(.jpeg)|*.jpeg";
if (Op.ShowDialog() == true)
{
img1.Source = new BitmapImage(new Uri(Op.FileName));
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
PersonAccountingdbEntities db = new PersonAccountingdbEntities();
tbl_Setting set = new tbl_Setting();
set.Image1 = File.ReadAllBytes(Op.FileName);
db.tbl_Setting.Add(set);
db.SaveChanges();
MessageBox.Show("image has been saved");
}
}
}
Right now my code takes the entire text file and just places it all into one text box. What I am trying to figure out how to do is have it place each line of the file into each separate text box.
namespace HomeInventory2
{
public partial class Form1 : Form
{
public Form1(string prepopulated)
{
InitializeComponent();
textBoxAmount.Text = prepopulated;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void submitButton_Click(object sender, EventArgs e)
{
CreateInventory create = new CreateInventory();
create.ItemAmount = textBoxAmount.Text;
create.ItemCategory = textBoxCategories.Text;
create.ItemProperties = textBoxValue.Text;
create.ItemValue = textBoxValue.Text;
InventoryMngr invtryMngr = new InventoryMngr();
invtryMngr.Create(create);
}
}
Assuming that the order of the lines is always the same and that each TextBox belongs to a line:
IEnumerable<String> lines = File.ReadLines(path);
textBoxAmount.Text = lines.ElementAtOrDefault(0);
textBoxCategories.Text = lines.ElementAtOrDefault(1);
textBoxValue.Text = lines.ElementAtOrDefault(2);
...
Enumerable.ElementAtOrDefault<TSource> Method
Returns the element at a specified index in a sequence or a default
value if the index is out of range (null in this case).
You could use System.IO.File.ReadAllLines(string filename).
What this does is reads each line of the file into a String array.
You could then do something like:
using System.IO;
//Namespace, Class Blah Blah BLah
String[] FileLines = File.ReadAllLines("Kablooey");
textBox1.Text = FileLines[0];
textbox2.Text = FileLines[1];
And so on. I hope this helps :)