Jan Solo
Jan Solo

Reputation: 193

Rotate image (byte array) in datatable

I have a datatable set as itemsource for a datagrid (datagrid showing several columns of the datatable). All columns except one have text, the last column holds an image as a byte array. The picture-column is bound to an image control, which shows the image from the selected line in the datagrid. The images the datatable holds can be collected from a disk-location or a database. Eventually, they will all be saved in the database.

I have a button, which should rotate the shown image 90° clockwise, and save it again (as byte array) in the datatable on the exact same row (and column).

I tried about a kazillion ways to do this, but no luck whatsoever. Can someone please help me rotating and saving this picture?

Upvotes: 3

Views: 8245

Answers (2)

fuchs777
fuchs777

Reputation: 1002

untested but should do the trick (might necessary be to load the image to a bitmap)

using (var memoryStream = new MemoryStream(byteArray))
{
    var rotateImage = Image.FromStream(memoryStream);
    rotateImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
    rotateImage.Save(memoryStream, rotateImage.RawFormat);
    byteArray = memoryStream.ToArray();
}

edit: for some reason I had forgotten to save the image back to the stream... fixed that

Upvotes: 5

Arie
Arie

Reputation: 5373

It's tested. I dont know about Image.Save() method though. There may be issues with quality of the new image (depending on image format of the input image)

    public static Image GetImageFromDB(byte[] tab)
    {
         if (tab == null) return null;

        try
        {
            MemoryStream ms = new MemoryStream(tab);
            if (ms != null)
            {
                Image im = Image.FromStream(ms, true);
                // or: Image.FromFile(imagepath);
                im.RotateFlip(RotateFlipType.Rotate90FlipNone);
                ms.Dispose();

                im.Save(savedImagePath));
                return im;
            }
        }
        catch (Exception)
        {
        }

        return null;
    }

Upvotes: 0

Related Questions