Resize image proportionally with MaxHeight and MaxWidth constraints
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Resizing image with MaxHeight and MaxWidth
An asp.Net Image has the same attributes of the Winforms Image.
You still can use Image1.Height and Image1.Width.
Just set the height & width to these attributes. check an example:
protected void Page_Load(System.Object sender, System.EventArgs e) {
if (!Page.IsPostBack) {
LoadImage();
}
}
private void LoadImage(){
Image1.ImageUrl = LoadURLFromDatabase(params);
Image1.Width = (int)(image.Width * ratio);
Image1.Height = (int)(image.Height * ratio);
}
Constrain image size to max height and max width according to aspect ratio
If we look at each dimension individually, its simple to see the math for adjustment.
MAX_DIMENSION = CURRENT_DIMENSION * ADJUSTMENT
// We need to figure out what the adjustment is, we have the other two values
// do some algebra and we get
ADJUSTMENT = MAX_DIMENSION / CURRENT_DIMENSION
The problem that arises is each dimension is going to have its own adjustment value which results in a stretched/compressed image (the aspect ration does not stay the same). So we need to pick just one of the adjustment values to use, but which one? The smallest of course, otherwise one of the dimensions will overflow.
// Calculate which adjustment is the smallest, width or height
// otherwise we'd overflow one of them.
let widthPercent = MAX_WIDTH / iw;
let heightPercent = MAX_HEIGHT / ih;
let smallestPercent = Math.min(widthPercent, heightPercent);
// This works for both scaling up and scaling down
return {
w: iw * smallestPercent,
h: ih * smallestPercent
}
Resizing image proportionally in ASP.NET C# by specifying either Height or Width
Although it seems like you should be able to copy and paste a snippet to do this, there are a ton of pitfalls you need to look out for if you're building your own image resizing system. It's better to use a proven, tested, and supported open-source library.
To resize to a file directly from HttpPostedFile, call
ImageBuilder.Current.Build(httpPostedFile, "img.jpg", new ResizeSettings("width=200&quality=90"));
To resize an existing file, call
ImageBuilder.Current.Build("orig.jpg", "img.jpg", new ResizeSettings("width=200&quality=90"));
The ImageResizing.Net library is free, and MIT-licensed (no worries about licensing problems).
Resizing with a max width/height while keeping the original ratio using Intervention Image in Laravel
I know I am somewhat late to the race, but I have the answer you are looking for:
$width = 600; // your max width
$height = 600; // your max height
$img = IMG::make($uploaded_file);
$img->height() > $img->width() ? $width=null : $height=null;
$img->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
});
An image of 1000x1000 would become 600x600.
An image of 2000x1000 would become 600x300. This would mean that the
highest of the two values becomes 600, while the other gets
constrained proportionally.
This is what this code does. Hope I can help someone.
How to resize images proportionally / keeping the aspect ratio?
Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});
Resize an image with height/width constraints and constant ratio
css properties max-width
and max-height
are what you need.
My guess is that it will resize itself if it reaches one of these.
I have used this alot in previous web projects.
But i havent used the combination of both yet.
EDIT: I've sais this in a comment, but setting both those properties does work in my tests. It keeps the ratio and resizes by the limit it reaches first. Do not set any width
or height
properties, these might cause problems
Algorithm to resize an image proportionally keeping it as close as possible to given dimensions
If you don't care about rounding errors
Let
ratio = min(image_width / reference_width, image_height / reference_height)
and return
image_width / ratio
image_height / ratio
If you do care about rounding errors
Find the greatest common divisor GCD
of image_width
and image_height
. The smallest image you can make with the exact same aspect ratio has dimensions
image_width' = image_width / GCD
image_height' = image_height / GCD
Every larger image with the exact same aspect ratio is an integer multiple of those. So, let
ratio_width = ceil(reference_width / image_width')
ratio_height = ceil(reference_heigth / image_heigth')
and
ratio = max(ratio_width, ratio_height)
then your result is
ratio * image_width'
ratio * image_height'
Related Topics
Can't Get Czech Characters While Generating a PDF
Accessing a Variable from Another Script C#
#If Debug VS. Conditional("Debug")
Unity Game Manager. Script Works Only One Time
Compiler Ambiguous Invocation Error - Anonymous Method and Method Group with Func<> or Action
How to Embed a Text File in a .Net Assembly
Intersection of Multiple Lists with Ienumerable.Intersect()
Change Wpf Controls from a Non-Main Thread Using Dispatcher.Invoke
How to Pass Command-Line Arguments to a Winforms Application
Why Is It Bad to Use an Iteration Variable in a Lambda Expression
How to Let an Asmx File Output JSON
Difference Between Equals/Equals and == Operator
How to Abort a Task Like Aborting a Thread (Thread.Abort Method)