I want to load image from the database into a picture box using LoadAsync and a MemoryStream
I have images in the database that I want to load asynchronously into a picture box. How would I do this? Right now I have:
byte[] byteBLOBData = new byte[0];
byteBLOBData = (byte[])ds.Tables["magazine_images"].Rows[c - 1]["image"];
MemoryStream stmBLOBData = new MemoryStream(byt开发者_开发技巧eBLOBData);
pictureBox1.Image = Image.FromStream(stmBLOBData);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
labelMsg.Text = "Picture loaded successfully.";
And I want to do:
pictureBox1.LoadAsync("What should I put here?");
I'm using MySQL database and visual studio 2010 C#
Don't load the bytes into the image, that'll defeat the purpose of what you're trying to achieve... (note this is a quick-n-dirty to get the image into a temporary file... there's a lot of additional considerations here, not the least of which would be to delete the temporary file when you're done)
byte[] byteBLOBData = (byte[])ds.Tables["magazine_images"].Rows[c - 1]["image"];
string tempImageFileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".jpg");
using( FileStream fileStream = new FileStream(tempImageFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite) ) {
using( BinaryWriter writer = new BinaryWriter(fileStream) ) {
writer.Write(byteBLOBData);
}
}
pictureBox1.LoadCompleted += LoadCompleted;
pictureBox1.WaitOnLoad = false;
pictureBox1.LoadAsync(tempImageFileName);
...
private static void LoadCompleted( object sender, AsyncCompletedEventArgs e ) {
if( e.Error != null ) {
// will get this if there's an error loading the file
} if( e.Cancelled ) {
// would get this if you have code that calls pictureBox1.CancelAsync()
} else {
// picture was loaded successfully
}
}
also see the LoadProgressChanged
event
精彩评论