当ImageLocation不工作时,如何在c#中获取PictureBox的imageURL
本文关键字:获取 PictureBox imageURL ImageLocation 工作 | 更新日期: 2023-09-27 18:06:10
当ImageLocation不工作时,如何在windows窗体中获取图片框的图像URL ?
string filepath = picturebox.ImageLocation; // Returns null
如果您使用picturebox的ImageLocation属性来加载图像,那么您就得到了您想要的。否则,如果你通过图像属性加载它,那么你就不会从ImageLocation中获取,也不会从Image中获取。
你可以通过
string filepath = PictureBox.ImageLocation;
见http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.imagelocation.aspx
ImageLocation
PictureBox.ImageLocation
也许这篇文章能帮到你http://blogs.msdn.com/b/marcelolr/archive/2007/06/15/data-binding-a-winforms-picturebox-to-a-file-path-or-url.aspx
欢呼
听起来你需要:
Picturebox.ImageLocation
我终于找到了解决办法。当我们选择图像时,将Image
的路径存储在图片框的Tag
属性中。
pictureBox2.Image = new Bitmap(oOpenFileDialog.FileName);
pictureBox2.Tag = oOpenFileDialog.FileName;
并在需要时检索:
string Path = pictureBox2.Tag + string.Empty;
请记住,您必须将Tag
属性设置为null
。
将图像分配给PictureBox有一定的正确方法。我相信您会理解使用PictureBox背后的原因和逻辑。ImageLocation
当你得到一个Image.FromFile;您将被要求指定一个字符串,包含所选图像的文件:目录,文件名和扩展名。因此,一旦你选择/加载要加载的图像(假设你将使用OpenFileDialog);您必须将文件的完整路径设置为PictureBox。ImageLocation属性放在首位(这样您就可以在需要时检索它);只有这样(最好)你才能将图像加载到你的PictureBox中。
参见下面的例子:
// Dispose PictureBox Image (Prepare it to load another Image).
private void DisposeImage()
{
if (pictureBox.Image != null)
{
pictureBox.Image.Dispose();
pictureBox.Image = null;
pictureBox.ImageLocation = null;
pictureBox.Update();
}
}
// 1. Make sure that no Image is Loaded before Loading a new Picture.
// 2. Set the Image Location to PictureBox.ImageLocation
// 3. Load the Image.FromFile (Get the string from stored value).
private void SetImage(string imageFile)
{
// Clear any existant Image in PictureBox.
// [Defensive programming to prevent exceptions]
DisposeImage();
// Check if full path is valid (File Exists).
if File.Exists(imageFile))
{
// Store the Image location to variable.
pictureBox.ImageLocation = imageFile;
// Load the Image from stored variable.
pictureBox.Image = Image.FromFile(pictureBox.ImageLocation);
}
// Set an Image (representing "no image"); in case the Selected Image Does not exist or fails to load.
else { pictureBox.Image = Properties.Resources.NoImageAvailable; }
// Place your Image Configuration to Adjust to PictureBox Here.
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
}
如果你需要获取图片盒图像位置:
// Retrieve Current PictureBox Image Location (if any).
private string GetImageLocation()
{
// Set the default Image Location value (empty).
// This is usefull to check wether the string is empty or not.
// This can obviously be improved (I removed some unnecessary parts to suit this exmaple).
string fullPath = string.Empty;
// Make sure stored Image Location string is NOT Null or Empty.
if (!string.IsNullOrEmpty(pictureBox.ImageLocation))
{
// Assign the Image Location to the local variable (to be returned).
fullPath = pictureBox.ImageLocation;
}
return fullPath;
}
当你把这些写下来之后,你就明白了其中的逻辑,并且它最终变得非常简单。