PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

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

 May 06, 2022     arrays, asp.net-mvc-4, c#, image, thumbnails     No comments   

Issue

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!


Solution

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);
    }
}


Answered By - keeehlan
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing