I started messing around with C# earlier and I thought that I would look at porting some of my VB.net code. It’s actually really easy to just start writing C# code after knowing a little bit of .NET and Java. From what I have seen so far it’s kind of like the bastard child between the two. I’m still picking up on the small changes but hopefully the book I ordered will fill in the gaps.
public class smartPictureBox : System.Windows.Forms.PictureBox
{
private string m_strPath;
// the default constructor
public smartPictureBox()
{
// we just need to set the size
this.Width = 100;
this.Height = 100;
}
public string path {
get
{
// just return the path
return m_strPath;
}
set
{
// set the path
m_strPath = value;
// load the image
loadImage();
}
}
private void loadImage(){
// check to see if the file is valid
if (!System.IO.File.Exists(m_strPath))
{
// set the error
this.BackgroundImageLayout = ImageLayout.Zoom;
this.BackgroundImage = this.ErrorImage;
return;
}
try
{
// load the raw information
Image objRaw = System.Drawing.Image.FromFile(m_strPath);
// the new width and height
int newWidth = 0;
int newHeight = 0;
// calculate the aspect ratio
float ratio = (float)objRaw.Width / (float)objRaw.Height;
// check to see if this landscape
if (ratio > 1)
{
newWidth = this.Width;
newHeight= (int)((float)this.Width / ratio);
}
else
{
newWidth = (int)((float)this.Height * ratio);
newHeight = this.Height;
}
// create the new image
Image objNew = new System.Drawing.Bitmap(newWidth, newHeight);
// get the handle to the drawing interface
System.Drawing.Graphics objGraphics = System.Drawing.Graphics.FromImage(objNew);
// resize the image
objGraphics.DrawImage(objRaw, 0, 0, objNew.Width, objNew.Height);
// set the image
this.BackgroundImage = objNew;
// dispose of the raw file
objRaw.Dispose();
objGraphics.Dispose();
this.BackgroundImage = objNew;
} catch(System.Exception ex) {
// there was an error
MessageBox.Show(ex.Source);
this.BackgroundImage = this.ErrorImage;
}
}
}
2 users commented in " A Picture Box That Remebers It’s Path In C# "
Follow-up comment rss or Leave a TrackbackHi!!
Good code, but in this line:
Image objRaw = System.Drawing.Image.FromFile(m_strPath);
break an Exception OutOfMemoryException, the file that I try load only occuped 30Kb, but the problem not is the memory, the problem is the file format, Image.FromFile not accepts raw format!
any idea?
P.D. Sorry for my English, I’m from Spain.
Regards.
I have run into this problem with some of my files. It mostly occurs with files that the .net framework doesn’t support naively. My only suggestion is to write a function that will process the file format in question.
Leave A Reply