martes, octubre 07, 2008

Conversores

Con la siguiente clase lo que se pretende es, poder convertir tipos de datos, entre arreglos de bytes e imagen. esto es para poder transmitirlos o guardarlos en una base de datos.



Imports System.IO
Imports System.Text
Imports System.Drawing


Public Class FuncsAndUtils
   Public Shared Function ArrayToStream(ByVal buffer() As Byte) As Stream
     Dim Flujo As Stream = New MemoryStream(buffer)
     Return Flujo
   End Function

   Public Shared Function ArrayToBitmap(ByVal Buffer() As Byte) As Bitmap
      Return StreamToBitmap(ArrayToStream(Buffer))
    End Function

   Public Shared Function StreamToArray(ByVal Flujo As Stream) As Byte()
       Dim streamLength As Integer = Convert.ToInt32(Flujo.Length)
       Dim fileData(streamLength) As Byte
       ' Read the file into a byte array
       Flujo.Read(fileData, 0, streamLength - 1)
       Flujo.Close()
       Return fileData
    End Function


    Public Shared Function StreamToBitmap(ByVal Flujo As Stream) As Bitmap
       Try
          Return New Bitmap(Flujo)
       Catch ex As Exception
          Throw ex
       End Try
    End Function



   Public Shared Function BitmapToArray(ByVal bmp As Bitmap) As Byte()
      Dim stream As New System.IO.MemoryStream()
       bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)
       stream.Position = 0
       Dim data(stream.Length) As Byte
       stream.Read(data, 0, stream.Length)
       Return data
    End Function

    Public Shared Function StringToArray(ByVal valor As String) As Byte()
       Return (New UnicodeEncoding).GetBytes(valor)
    End Function

    Public Shared Function BitmapToStream(ByVal bmp As Bitmap) As Stream
       Dim stream As New System.IO.MemoryStream()
       bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)
       stream.Position = 0
       Return stream
    End Function

    Public Shared Function ArrayToString(ByVal valor() As Byte) As String
       Return New UnicodeEncoding().GetString(valor)
    End Function



End Class

No hay comentarios.: