質問

I am using SQL Server and VB.NET WebAPI. I am currently returning data using the javascript serializer to return JSON in an API that is being consumed by an android application. I would like to include in the data an image that is being stored in the database. I have all the database stuff written and it's returning the data I just do not have a clue how to include the image as part of the data in the API.

役に立ちましたか?

解決

I would normally not store images in my database, but put the images on some web server, and store the link to these images. In that case all you have to do is give the url of the image in the json object you return.

However, in case that you do want to store image, what you do is a base64 encoding of the image (or basically any other resource, such as pdf files, Word docs, etc.)
The following code is taken from here:

Create base64 string from image:

Public Shared Function ImageToBase64String(ByVal image As Image, _
                                         ByVal imageFormat As ImageFormat)
    Using memStream As New MemoryStream
        image.Save(memStream, imageFormat)
        Dim result As String = Convert.ToBase64String(memStream.ToArray())
        memStream.Close()
        Return result
    End Using
End Function

And Visa Versa

Public Shared Function ImageFromBase64String(ByVal base64 As String)
     Using memStream As New MemoryStream(Convert.FromBase64String(base64))
         Dim result As Image = Image.FromStream(memStream)
         memStream.Close()
         Return result
     End Using
End Function

Since the result is a normal string (albeit, a really long string) you can just add it to you json object as a string, and decode it again on the client side :)
(almost) Every language has some encode en decode from base64 library.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top