Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image's byte[] while keeping proportions?

In my ASP.Net MVC 4 application, I have a View that allows users to hover over an image to get a full-sized preview. It works well.

Currently, I have the image that the user hovers over set to a static width and height of 50 and 50, like so:

<img id="@Model.Value" class="image-preview" height="50" width="50" src="@Model.ImageString" />

@Model.ImageString is a value that gets created by this Action:

[HttpGet]
public string GetImageUrl(Guid fileId)
{
    var file = db.FetchedFiles
        .First(ff => ff.ID == fileId);

    return "data:image/*;base64," + Convert.ToBase64String(file.Data);
}

The above Action is what I'd like to modify. How can I output the Convert.ToBase64String(file.Data) as a thumbnail image with the same proportions as the original file?

Thanks in advance!

like image 571
keeehlan Avatar asked Feb 15 '23 13:02

keeehlan


1 Answers

I found inspiration somewhere on the web and ended up with this:

string ResizeImage(byte[] data)
{
    using (var ms = new MemoryStream(data))
    {
        var image = Image.FromStream(ms);

        var ratioX = (double)150 / image.Width;
        var ratioY = (double)50 / image.Height;

        var ratio = Math.Min(ratioX, ratioY);

        var width = (int)(image.Width * ratio);
        var height = (int)(image.Height * ratio);

        var newImage = new Bitmap(width, height);

        Graphics.FromImage(newImage).DrawImage(image, 0, 0, width, height);

        Bitmap bmp = new Bitmap(newImage);

        ImageConverter converter = new ImageConverter();

        data = (byte[])converter.ConvertTo(bmp, typeof(byte[]));

        return "data:image/*;base64," + Convert.ToBase64String(data);
    }
}
like image 67
keeehlan Avatar answered Feb 22 '23 00:02

keeehlan