I have a PictureBox in .Net that displays images from a folder "Photos" using the following code on a click event:
PictureBox1.Image = Nothing 'Clearing PictureBox1
Dim bmPhotos as new Bitmap("C:\Photos\ImageName.gif")
PictureBox1.Image = bmPhotos
I want to replace "ImageName" in the file path with the name of the last captured image programatically. Is there a way to find out the name of the image that was added last to the "Photos" folder?
Thank you.
If the last created file is what you need, you can find it this way:
Dim file = System.IO.Directory.GetFiles("path") _
.OrderByDescending(Function(f) New System.IO.FileInfo(f).CreationTime) _
.FirstOrDefault()
You can also use GetFiles("path", "*.gif") to limit the result between gif files.
Also you can add some criteria after GetFiles, to limit the file types to be between specific file types, for example:
.Where(Function(f) New String() {".gif", ".png"}.Contains(System.IO.Path.GetExtension(f)))
Then you can show the image this way:
Me.PictureBox1.ImageLocation = file
Or
Me.PictureBox1.Load(file)
Related
I want to add an image as a resource in my project so that I can reference it for programmatically inserting into a range in a spreadsheet.
I added the image by right-clicking the project and selecting Add > Existing Item...
I hoped that the image (.png file) would then be available using this code:
var logoRange = _xlSheet.Range[
_xlSheet.Cells[1, LOGO_FIRST_COLUMN],
_xlSheet.Cells[5, LOGO_LAST_COLUMN]];
//System.Drawing.Bitmap logo =
//ReportRunner.Properties.Resources.pa_logo_notap.png;
System.Drawing.Image logo =
ReportRunner.Properties.Resources.pa_logo_notap.png;
_xlSheet.Paste(logoRange, logo);
...but using either Bitmap or Image, I get, "'ReportRunner.Properties.Resources' does not contain a definition for 'pa_logo_notap'"
This seemed like sensible code based on what I read here, but it seems that the image has to be explicitly marked as a resource for this to work. How do I accomplish that?
UPDATE
I tried this:
System.Drawing.Image logo = (System.Drawing.Image)ReportRunner.Properties.Resources.ResourceManager.GetObject("pa_logo_notag.png");
_xlSheet.Paste(logoRange, logo);
...but not only did I get a confirmation msg about the item being pasted not being the same size and shape as the place where it was being inserted, and did I really want to do that, it also inserted some seemingly unrelated text ("avgOrderAmountCell.Style") instead of the image.
UPDATE 2
Okay, I tried this:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Drawing.Image logo = (System.Drawing.Image)myAssembly.GetName().Name + ".pa_logo_notap.png";
Clipboard.SetDataObject(logo, true);
_xlSheet.Paste(logoRange, logo);
...but get, "Cannot convert type 'string' to 'System.Drawing.Image' on the second line of that code.
UPDATE 3
This works:
private System.Drawing.Image _logo;
. . .
_logo = logo; // logo (the image) is passed in an overloaded constructor
. . .
var logoRange = _xlSheet.Range[
_xlSheet.Cells[1, LOGO_FIRST_COLUMN], _xlSheet.Cells[6,
LOGO_LAST_COLUMN]];
Clipboard.SetDataObject(_logo, true);
_xlSheet.Paste(logoRange, _logo);
...but I'm not crazy about it, because I'm using an image that is on a form, and passing the image to this class's constructor. Passing images around seems kind of goofy when it should be possible to store the image as a resource and just load the resource. I still haven't gotten that methodology to work, though...
UPDATE 4
I reckon I'll just stick with what I've got (in Update 3), kludgy as it is, because this:
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream =
myAssembly.GetManifestResourceStream(myAssembly.GetName().Name +
"pa_logo_notap.png");
Bitmap bmp = new Bitmap(myStream);
Clipboard.SetDataObject(bmp, true);
_xlSheet.Paste(logoRange, bmp);
...fails with, "Value of 'null' is not valid for 'stream'"
You have change the build action of the image to be embedded resource.
Then you can reference by doing:
UPDATED
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream( myAssembly.GetName().Name + ".images.pa_logo_notap.png");
Bitmap bmp = new Bitmap(myStream);
My method is to open Resources.resx under Properties. You'll see all your resources laid out on screen.
Click on the downarrow next to 'Add Resource' and you'll see the option Add Existing File. Choose your image name.
I am just learning c# and have been struggling to work with URIs in WPF. I've googled around a fair bit but not having much luck.
Essentially I'm trying to have a BitmapImage object stored as a property in a Car object. I then want to display the BitmapImage in an Image control on a WPF form.
The app is a simple app (it's for a Uni assignment), so no database, etc.
I have two methods of doing this. The first is that I'm preloading Car data from a text file, including the filename of the JPG I want to load. I have included the JPG in a directory called Files which is off the main directory where my source code and class files are. I have set the JPG file to 'Content' and 'Always copy'. When I run a Debug, it copies the Files directory and the JPG to the debug\bin directory.
My code creates a BitmapImage by referring to the JPG using a URI as follows;
BitmapImage myImage = new BitmapImage (new Uri("Files/" + Car.Imagefilename, UriKind.Relative);
Car.Image = myImage;
ImageControl.Source = myImage;
If I step through this code in the debugger, it sometimes works and displays the image, but most of the time it doesn't.
My second method is when a user creates a new Car. This method always works. In this one, I use a file dialog box (dlg) to select the image and use an absolute path.
BitmapImage myImage = new BitmapImage (new Uri(dlg.Filename, UriKind.Absolute);
Car.Image = myImage;
ImageControl.Source = myImage;
So....I can't work out why the first method doesn't work. I think it's got something to do with the relative reference, but I can't work out how to syntax that properly to work. I've tried using "pack:,,,", I've tried adding "component", I've tried an '#' before the "pack". I can't seem to find something that explains this simply.
Apologies if this is straight forward but it's doing my head in! Appreciate any pointers.
If the image files are located in a "Files" folder of your Visual Studio project, you should set their Build Action to Resource (and Copy to Output Directory to Do not copy), and load them by a Resource File Pack URI:
var image = new BitmapImage(new Uri("pack://application:,,,/Files/" + Car.Imagefilename));
Car.Image = image;
ImageControl.Source = image;
There is no need to copy the files anywhere. Images are loaded directly from the assembly.
First try to load the image file using its absolute path. For example if the images are stored in c:\projects\yourproject\files, then try using something like
BitmapImage myImage = new BitmapImage (new Uri("c:/projects/yourproject/files/carname.jpg", UriKind.Absolute);
If it works, what you are facing is an path calculation issue.
At this point you may either calculate the Absolute with reference to your executable using AppDomain.CurrentDomain.BaseDirectory at runtime or use App.Config to store the path and reference it from there.
Cheers
I am working on windowes form application..in show button event i wrote code like this:
Me.PictureBox1.Load("C:/Signature.tif")
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
Me.PictureBox1.BorderStyle = BorderStyle.Fixed3D
then save button click i wrote code like this:
Dim exittime As String = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Dim ms As New MemoryStream
Dim byt() As Byte
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
byt = ms.GetBuffer
Dim sqlstr As String = "Update Visitorlogo_tbl set signimage=#pic,exittime='" & exittime & "',status=2 where PassNo='" & txtvisitorid.Text & "'"
Dim cmd1 As New SqlCommand(sqlstr, con.connect)
cmd1.Parameters.Add("#pic", SqlDbType.Image)
cmd1.Parameters("#pic").Value = byt
cmd1.ExecuteNonQuery()
con.disconnect()
PictureBox1.Image = Nothing
If System.IO.File.Exists("C:/Signature.tif") Then
System.IO.File.Delete("C:/Signature.tif")
End If
while saving image image got saving,,but after that i want to delete image from that path.. while coming to this line : System.IO.File.Delete("C:/Signature.tif") am getting error: The process cannot access the file 'C:\Signature.tif' because it is being used by another process
Possible the problem is here.
Me.PictureBox1.Load("C:/Signature.tif")
try this
Me.PictureBox1.Image = new Bitmap("C:\Signature.tif");
UPDATED:
PictureBox1.Load() method will load the file from given location and stores the file path in PictureBox.ImageLocation property. with this method, application will open that image and lock so, other user cannot modify or read it.
PictureBox1.Image = new Bitmap("filePath"); will create the another image object from given file path and it will not lock down the original one. This method will not load the original image from given file location. So, the PictureBox1.ImageLocation property will not be set here. How you can access that image and modify it.
The PictureBox will keep the file open. Therefore you can use the fix suggested by #Shell to release the file after reading the contents. This behavior is by design of the PictureBox.
http://support.microsoft.com/kb/309482
Here is a workaround adapted from the knowledge base article
Using fs as New System.IO.FileStream("C:\Signature.tif", IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
End Using
As the error message suggests the image is open by another process. Have you got the image open in a graphics program for example?
Do you have another instance of your application running in the background that has locked the image for reading?
If so close the other programs.
I am working on C# project i need to get the images from Images directory using relative path. I have tried
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + #"\Images\logo.png";
var logoImage = new LinkedResource(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)+#"\Images\logo.png")
But no luck with these...
I have made the images to be copied to output directory when the program is running but it doesn't pickup those images.
If you are using LinkedResource() in C# it is most likely not to pickup your relative URI or the file location.
You can use some extra piece of code
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var logoimage = Path.Combine(outPutDirectory, "Images\\logo.png");
string relLogo = new Uri(logoimage).LocalPath;
var logoImage = new LinkedResource(relLogo)
Now it will pickup your relative path, convert this to absolute path in memory and it will help you get the images.
First, add those image file to your project (create an Image folder is a good idea)
Second, select the image in your solution manager, and view the property window.
And then, change the "copy to output folder" to "always" or "copy when update".
PS. My IDE is Trad. Chinese so I can not ensure the correct keywords in your language.
I would make sure that the Images directory is in the output folder.
I usually use Assembly.GetExecutingAssembly().Location to get the location of my dll.
However, for images, I usually use the Resources page/collection in the project's Properties page. Here is more information about it. Putting the image in the project's Resource would automatically give you an easy way to access it.
For more information about GetExecutingAssembly: MSDN Page
if u want to display images in your folder using your application use an array and put all pictures in ur folder into array. then you can go forward and backward.
string[] _PicList = null;
int current = 0;
_PicList = System.IO.Directory.GetFiles("C:\\Documents and Settings\\Hasanka\\
Desktop\\deaktop21052012\\UPEKA","*.jpg");
// "*.jpg" will select all
//pictures in your folder
String str= _PicList[current];
DisplayPicture(str);
private void DisplayPicture(string str)
{
//throw new NotImplementedException();
BitmapImage bi = new BitmapImage(new Uri(str));
imagePicutre.Source = bi; // im using Image in WPF
//if u r using windows form application it must be a PictureBox i think.
label1.Content = str;
}
I have an application with a tool bar and an Image Collection. The problem is that I do not have the original images and I need to create another tool bar with some of the same buttons. Is there a way to save the Images Collection from the tool bar to a file?
I tried extracting the images from a resource file but I do not know which one has the images stored in.
Although I did not find an answer for my question, I managed to get the images by reading the tool bar image list and saving each one to a file according to the given image key.
for (int x = 0; x < this.imageListToolbar3small.Images.Count; ++x)
{
Image temp = this.imageListToolbar.Images[x];
temp.Save(this.imageListToolbar.Images.Keys[x] + ".png");
}
This came from an answer to this question: How to Export Images from an Image List in VS2005?
I just added the code after the InitializeComponent call and saved all images in debug mode. I did not needed to run the full application.
If anyone does have a better idea or a small application to retrieve images from a tool bar using only the resource file, that would be appreciated. I will not mark as an answer since it is more a workaround.
I use this approach:
foreach (ToolBarButton b in toolBar.Buttons)
{
//can be negative, for separators, because separators don't have images
if (b.ImageIndex >= 0)
{
Image i = toolBar.ImageList.Images[b.ImageIndex];
i.Save(b.ImageIndex + ".png");
}
}
I needed to recover images from a private ImageList member of a Control. I used the following code (Sorry, it's VB but s/b easy to refactor)
Dim cntrl = New TheClassWithThePrivateImageList
Dim pi As Reflection.PropertyInfo, iml As System.Windows.Forms.ImageList, propName = "ThePropertyName"
pi = cntrl.GetType.GetProperty(propName, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
iml = CType(pi.GetValue(cntrl), System.Windows.Forms.ImageList)
For Each key In iml.Images.Keys
Dim image As Drawing.Image = iml.Images.Item(key)
image.Save($"{propName}_{key}")
Next