Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / ASP.NET / Web Services / December 2004

Tip: Looking for answers? Try searching our database.

Returning a Bitmap Object from a WebMethod

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
rlcavebmg - 06 Dec 2004 17:19 GMT
I am new to Web Services and .NET development, and I have a question.

I am writing a service that will create a bitmap image and return it to the
client.  First, I wrote a method that looked like this:

public System.Drawing.Bitmap CreateImage() {...}

When I tried to create the web reference in my client program, I got an
error message stating that the System.Drawing.Bitmap object could not be
serialized because it does not have a public default constructor.  Then I
changed the method to something like this:

public bool CreateImage(ref System.Drawing.Bitmap bitmap) {...}

Unfortunately, this resulted in the same error message.

The help for the Bitmap class indicates that it has been declared with the
[serializable] attribute, which leads me to believe that what I am doing
should work.  Alas, it does not.

Does anyone know what I need to do to make this work, or have a sample
program that does something similar?

Thanks,

Bob
Drew Marsh - 06 Dec 2004 17:48 GMT
> I am new to Web Services and .NET development, and I have a question.
>
[quoted text clipped - 5 lines]
> Does anyone know what I need to do to make this work, or have a sample
> program that does something similar?

Yeah, you can't just return a Bitmap for a bunch of reasons. What you'll
need to do is get the bytes of the bitmap and return them using Base64 encoding.
It might look a little something like this:

<codeSnippet language="C#">
[WebMethod]
[return:XmlElement("imageData", DataType="base64Binary")]
public byte[] CreateImage()
{
 using(Bitmap image = new Bitmap(100, 100))
 using(Graphics imageGraphics = Graphics.FromImage(image))
 {
   imageGraphics.FillRectangle(Brushes.Red, 0, 0, image.Width, image.Height);
   imageGraphics.DrawRectangle(Pens.Blue, 0, 0, image.Width, image.Height);
               
   using(MemoryStream stream = new MemoryStream())      
   {
     image.Save(stream, ImageFormat.Png);

     stream.Flush();

     return stream.ToArray();
   }
 }
}
</codeSnippet>

As you can see I've decorated the result of the method with an XmlElementAttribute
with the DataType base64Binary which instructs the XmlSerializer to serialize
the byte array into an element named "imageData" whose contents is base64
encoded. This is not the most efficient way to acheive this since you need
to encode/decode the bytes, but is probably the most cross platform compatible.
If you're using WSE on both ends you might want to consider using DIME, which
will allow you to basically send just the raw bytes, but that's something
I'm not all that experienced with personally.

HTH,
Drew
rlcavebmg - 06 Dec 2004 19:53 GMT
> >...snipped for brevity...

Drew,

Thanks.  That was very helpful.

On the client side,  it looks like I ought to be able to do something like
the following snippet to get the data into a Bitmap object:

byte[] byteArray = CreateImage();
MemoryStream stream = new MemoryStream(byteArray);
Bitmap bitmap = new Bitmap(stream);

Is this correct?

Cheers,

Bob
Drew Marsh - 06 Dec 2004 20:01 GMT
> On the client side,  it looks like I ought to be able to do something
> like the following snippet to get the data into a Bitmap object:

Duh, yeah, I shoulda just included my test client side code for you. Here,
this was on a test winforms app as part of a button click. It just gets the
image and draws it on the form:

<codeSnippet language="C#">
Service1 service = new Service1();

byte[] imageBytes = service.CreateImage();

using(MemoryStream stream = new MemoryStream(imageBytes, false))
using(Image image = Image.FromStream(stream))
{
 this.CreateGraphics().DrawImage(image, 0, 0);
}
</codeSnippet>

HTH,
Dre
Dilip Krishnan - 10 Dec 2004 02:25 GMT
Hello Drew,
   Ideally you should try using Dime attachments.
http://msdn.microsoft.com/msdnmag/issues/02/12/DIME/default.aspx

HTH
Regards,
Dilip Krishnan
MCAD, MCSD.net
dkrishnan at geniant dot com
http://www.geniant.com

>> On the client side,  it looks like I ought to be able to do something
>> like the following snippet to get the data into a Bitmap object:
[quoted text clipped - 16 lines]
> HTH,
> Drew
Bahadir Cambel - 20 Dec 2004 15:06 GMT
Could you please write an example of a web application doing the same job..
Because I am dealing with the same issue , tranferring byte[] from the
WebService, but I couldnt find any method to transform this data into a
WebControls.Image object.
Thanks a lot ,
Bahadir Cambel

> > On the client side,  it looks like I ought to be able to do something
> > like the following snippet to get the data into a Bitmap object:
[quoted text clipped - 17 lines]
> HTH,
> Drew
Cor Ligthert - 20 Dec 2004 15:57 GMT
Hi,

I saw this question by accident, does this sample I once made fit the
problem?
As database is a very easy dataset file used on the serverside.

\\\needs a picturebox and 4 buttons on a windowform
Private ds As New DataSet
Private abyt() As Byte
Private fo As New OpenFileDialog
Private sf As New SaveFileDialog
Private Sub Button1_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles Button1.Click
       'Reading a picture from disk and put it in a bytearray
       If fo.ShowDialog = DialogResult.OK Then
           Dim fs As New IO.FileStream(fo.FileName, _
          IO.FileMode.Open)
           Dim br As New IO.BinaryReader(fs)
           abyt = br.ReadBytes(CInt(fs.Length))
           br.Close()
           'just to show the sample without a fileread error
           Dim ms As New IO.MemoryStream(abyt)
           Me.PictureBox1.Image = Image.FromStream(ms)
       End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal _
   e As System.EventArgs) Handles Button2.Click
       'writing a picture from a bytearray to disk
       If sf.ShowDialog = DialogResult.OK Then
           Dim fs As New IO.FileStream(sf.FileName, _
               IO.FileMode.CreateNew)
           Dim bw As New IO.BinaryWriter(fs)
           bw.Write(abyt)
           bw.Close()
       End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal _
   e As System.EventArgs) Handles Button3.Click
       'writing a bytearray to a webservice dataset
       Dim ws As New localhost.DataBaseUpdate
       ws.SetDataset(abyt)
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, _
   ByVal e As System.EventArgs) Handles Button4.Click
       'reading a picture from a webservice dataset
       Dim ws As New localhost.DataBaseUpdate
       abyt = ws.GetByte
       Dim ms As New IO.MemoryStream(abyt)
       Me.PictureBox1.Image = Image.FromStream(ms)
   End Sub
End Class
////
\\\\Webservice
<WebMethod()> _
   Public Function GetByte() As Byte()
       Dim ds As New DataSet
       ds.ReadXml("C:\wsblob.xml")
       Return CType(ds.Tables(0).Rows(0)(0), Byte())
   End Function
   <WebMethod()> _
      Public Sub SetDataset(ByVal abyte As Byte())
       Dim ds As New DataSet
       ds.Tables.Add(New DataTable("Photo"))
       ds.Tables(0).Columns.Add(New DataColumn("Sample"))
       ds.Tables(0).Columns(0).DataType = GetType(System.Byte())
       ds.Tables(0).Rows.Add(ds.Tables(0).NewRow)
       ds.Tables(0).Rows(0)(0) = abyte
       ds.WriteXml("C:\wsblob.xml", XmlWriteMode.WriteSchema)
   End Sub
////

I hope this helps a little bit?

Cor
"rlcavebmg" <rlcavebmg@discussions.microsoft.com>

>I am new to Web Services and .NET development, and I have a question.
>
[quoted text clipped - 23 lines]
>
> Bob

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.