Imports System.Windows.Media.Imaging
Imports System.Windows.Data

Public Class ConversorBytes_ImageSource
  Implements IValueConverter
  ' Byte() a ImageSource (origen --> destino)
  Private Function Convert(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
    If targetType.FullName = "System.Windows.Media.ImageSource" Then
      If value Is Nothing Then Return Nothing

      ' Obtener las dimensiones y la imagen
      Dim bytesWHImagen As Byte() = DirectCast(value, Byte())
      Dim w As Byte() = BitConverter.GetBytes(0)
      Dim h As Byte() = BitConverter.GetBytes(0)
      Array.Copy(bytesWHImagen, 0, w, 0, 4)
      Array.Copy(bytesWHImagen, 4, h, 0, 4)
      Dim width As Integer = BitConverter.ToInt32(w, 0)
      Dim height As Integer = BitConverter.ToInt32(h, 0)

      Dim bytesImagen As Byte() = New Byte(bytesWHImagen.Length - 9) {}
      Array.Copy(bytesWHImagen, 8, bytesImagen, 0, bytesWHImagen.Length - 8)

      Return New WriteableBitmap(width, height).FromByteArray(bytesImagen)
    End If
    Return Nothing
  End Function

  ' ImageSource a Byte() (destino --> origen)
  Private Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
    If targetType.FullName = "System.Byte[]" Then
      If value Is Nothing Then Return Nothing

      Dim wbm As WriteableBitmap = TryCast(value, WriteableBitmap)
      ' Añadir las dimensiones antes de la imagen
      Dim bytesImagen As Byte() = wbm.ToByteArray()
      Dim bytesWHImagen As Byte() = New Byte(bytesImagen.Length + 7) {}
      Dim w As Byte() = BitConverter.GetBytes(wbm.PixelWidth)
      Dim h As Byte() = BitConverter.GetBytes(wbm.PixelHeight)
      Array.Copy(w, 0, bytesWHImagen, 0, 4)
      Array.Copy(h, 0, bytesWHImagen, 4, 4)
      bytesImagen.CopyTo(bytesWHImagen, 8)

      If wbm IsNot Nothing Then Return bytesWHImagen
    End If
    Return Nothing
  End Function
End Class
