Save C# Image Object into Oracle BLOB

How to save Image in C# bytes into Oracle BLOB and use it later

Some of my friends requested me to make a tutorial about the Oracle database and C#. This time, I’d like to share about how to Save Image or Picture from C# Object into Oracle BLOB Type. It’s very easy if you know the trick.

To make the tutorial simple, let’s assume a table with 1 field. It’ll be used to store a collection of photos.

CREATE TABLE PHOTO 
(
  PHOTO_BIN BLOB 
);

Next, open or create a new C# project. Add Oracle.ManagedDataAccess NuGet package to your project.

Install-Package Oracle.ManagedDataAccess

Somewhere in one of your C# classes, create a function to read an image as an array of bytes. Use the following code to achieve that. This array of bytes will be used as the BLOB value in Oracle Database.

private async Task<byte[]> GetImageBytesAsync(string imagePath)
{
    byte[] imageBytes = null;
    using (var stream = new FileStream(imagePath, FileMode.Open))
    {
        imageBytes = new byte[stream.Length];
        await stream.ReadAsync(imageBytes, 0, (int)stream.Length);
    }
    return imageBytes;
}

Finally, use the following code to insert an image into Oracle Database. It’s done simply by creating a database connection and doing insert command as usual. The difference is, you need to define the insert value parameter as OracleDbType.Blob.

private async Task AddPhotoToDatabaseAsync(string imagePath)
{
    var connectionString =
        "Data Source=localhost;Persist Security Info=True;" +
        "User ID=username;Password=password;Unicode=True";

    using (var conn = new OracleConnection(connectionString))
    {
        await conn.OpenAsync();

        var query = "INSERT INTO PHOTO VALUES(:blobtodb)";

        using (var cmd = new OracleCommand(query, conn))
        {
            cmd.CommandType = CommandType.Text;

            var param = cmd.Parameters.Add(
                "blobtodb",
                OracleDbType.Blob);
            param.Direction = ParameterDirection.Input;
            param.Value = await GetImageBytesAsync(imagePath);

            await cmd.ExecuteNonQueryAsync();
        }
    }
}

That’s all I can write today. Hope this tutorial can be useful and solve your problem. Thanks for reading.

Subscribe to Go Do Dev

Get the latest posts delivered right to your inbox.

Delivered by FeedBurner or subscribe via RSS with Feedly!