Compartir a través de


Insertar una imagen a partir de un archivo

Puede escribir un objeto binario grande (BLOB) en una base de datos como datos binarios o de caracteres, dependiendo del tipo de campo del origen de datos. BLOB es un término genérico que hace referencia a los tipos de datos text, ntexty image, que suelen contener documentos e imágenes.

Para escribir un valor BLOB en la base de datos, emita la instrucción INSERT o UPDATE correspondiente y pase el valor BLOB como parámetro de entrada (vea Configuración de parámetros y tipos de datos de parámetros). Si el BLOB se almacena como texto, como un campo text de SQL Server, puede pasar el BLOB como un parámetro de cadena. Si el BLOB se almacena en formato binario, como un campo image de SQL Server, puede pasar una matriz de tipo byte como parámetro binario.

Ejemplo

En el ejemplo de código siguiente se agrega información de empleado a la tabla Employees de la base de datos Northwind. Una foto del empleado se lee de un archivo y se agrega al campo Photo de la tabla, que es un campo de imagen.

Public Shared Sub AddEmployee( _
  lastName As String, _
  firstName As String, _
  title As String, _
  hireDate As DateTime, _
  reportsTo As Integer, _
  photoFilePath As String, _
  connectionString As String)

  Dim photo() as Byte = GetPhoto(photoFilePath)

  Using connection As SqlConnection = New SqlConnection( _
    connectionString)

  Dim command As SqlCommand = New SqlCommand( _
    "INSERT INTO Employees (LastName, FirstName, Title, " & _
    "HireDate, ReportsTo, Photo) " & _
    "Values(@LastName, @FirstName, @Title, " & _
    "@HireDate, @ReportsTo, @Photo)", connection)

  command.Parameters.Add("@LastName",  _
    SqlDbType.NVarChar, 20).Value = lastName
  command.Parameters.Add("@FirstName", _
    SqlDbType.NVarChar, 10).Value = firstName
  command.Parameters.Add("@Title", _
    SqlDbType.NVarChar, 30).Value = title
  command.Parameters.Add("@HireDate", _
    SqlDbType.DateTime).Value = hireDate
  command.Parameters.Add("@ReportsTo", _
    SqlDbType.Int).Value = reportsTo

  command.Parameters.Add("@Photo", _
    SqlDbType.Image, photo.Length).Value = photo

  connection.Open()
  command.ExecuteNonQuery()

  End Using
End Sub

Public Shared Function GetPhoto(filePath As String) As Byte()
  Dim stream As FileStream = new FileStream( _
     filePath, FileMode.Open, FileAccess.Read)
  Dim reader As BinaryReader = new BinaryReader(stream)

  Dim photo() As Byte = reader.ReadBytes(stream.Length)

  reader.Close()
  stream.Close()

  Return photo
End Function
public static void AddEmployee(
  string lastName,
  string firstName,
  string title,
  DateTime hireDate,
  int reportsTo,
  string photoFilePath,
  string connectionString)
{
  byte[] photo = GetPhoto(photoFilePath);

  using (SqlConnection connection = new SqlConnection(
    connectionString))

  SqlCommand command = new SqlCommand(
    "INSERT INTO Employees (LastName, FirstName, " +
    "Title, HireDate, ReportsTo, Photo) " +
    "Values(@LastName, @FirstName, @Title, " +
    "@HireDate, @ReportsTo, @Photo)", connection);

  command.Parameters.Add("@LastName",
     SqlDbType.NVarChar, 20).Value = lastName;
  command.Parameters.Add("@FirstName",
      SqlDbType.NVarChar, 10).Value = firstName;
  command.Parameters.Add("@Title",
      SqlDbType.NVarChar, 30).Value = title;
  command.Parameters.Add("@HireDate",
       SqlDbType.DateTime).Value = hireDate;
  command.Parameters.Add("@ReportsTo",
      SqlDbType.Int).Value = reportsTo;

  command.Parameters.Add("@Photo",
      SqlDbType.Image, photo.Length).Value = photo;

  connection.Open();
  command.ExecuteNonQuery();
  }
}

public static byte[] GetPhoto(string filePath)
{
  FileStream stream = new FileStream(
      filePath, FileMode.Open, FileAccess.Read);
  BinaryReader reader = new BinaryReader(stream);

  byte[] photo = reader.ReadBytes((int)stream.Length);

  reader.Close();
  stream.Close();

  return photo;
}

Consulte también