Insert an image from file


#1

Hi,

Do you happen to have a sample of how to insert an image from file instead of a BLOB field in a database? I understand I would use MergeImageFieldEventArgs, but not quite sure how exactly.

Thank you.


#2

Hi,

All you need to do inside the MergeImageField event handler is to assign an image object to e.Image. Where you get the image object from is totally up to you.

This example shows how the image can be loaded from file if the field value contains full file name of the image:

private void HandleMergeImageFieldEvent(object sender, MergeImageFieldEventArgs e)
{
//Something that a user could do. Take field value and return image, stream of filename.
e.Image = System.Drawing.Image.FromFile(e.FieldValue.ToString());
}


#3

Thanks a lot. After some playing with it, I need to restate my question. I have an aspx file returning a binary stream for an image (created using Dundas Charts). In other words, I call page.aspx?Parameter=ParameterValue and get an image. However, I can’t supply an aspx file to the ImageFileName property - it does not like it. Nor can I use Drawing.Image.FromFile, for the same reason.

So, my question is: how do I read the content of page.aspx?Parameter=ParameterValue into a MemoryStream, if you happen to have an idea.

Thanks so much,

Anatoly


#4

I think you need to use WebRequest and WebResponse classes, download whole binary response into a MemoryStream and then you all set to load an image from it.

Check my other posts, seach for an example for WebResponse. It was for downloading .doc file, not an image, but it’s the same.


#5

You should also be able to use System.Net.WebClient class. The return value of OpenRead method can be passed to Image.FromStream. Make sure you call Stream.Close afterwards.

Abdim


#6

Thanks for both posts - both suggestions worked.

Anatoly


#7

For future reference, here are two working versions in VB, which will work either with an image file or anything providing binary stream for an image (an aspx in my case):

Version 1:

dim URL as string = “…” 'has to be an ABSOLUTE url
Dim myWebClient As New WebClient
Dim myStream As Stream = myWebClient.OpenRead(URL)
e.Image = Drawing.Image.FromStream(myStream) 'line 3
myStream.Close()

Version 2:

dim URL as string = “…” ‘has to be an ABSOLUTE url
Dim myRequest As WebRequest = WebRequest.Create(URL)

’ Return the response.
Dim myResponse As WebResponse = myRequest.GetResponse()

Dim responseData(myResponse.ContentLength) As Byte
Dim bytesRead As Integer = 0

Do While bytesRead < myResponse.ContentLength

Dim bytesToRead As Integer = CInt(myResponse.ContentLength - bytesRead)
bytesRead += myResponse.GetResponseStream().Read(responseData, bytesRead, bytesToRead)

Loop

myResponse.Close()

Dim MS As MemoryStream
MS = New MemoryStream(responseData)

e.ImageStream = MS