Reputation: 505
I let users upload a banner with a minimum width of 400px. This image will then get a wide of 1110px. I try to upload images with the following sizes: 960x390, 410x410, 784x250. When i upload 784x250, the image get the same size 784x250 not the width, 1110px.
I use this:
int Height;
using (var Bmp = new Bitmap(str))
{
if (Bmp.Width < 400)
{
throw;
}
if (Bmp.Height < 150)
{
throw;
}
Height = Bmp.Height;
}
if (Height > 300)
{
Height = 300;
}
str.Position = 0;
var ImageData = str.StreamToByteArray();
var Settings = "width=1110;height="+ Height + ";format=jpg;mode=crop;"
var Setting = new ResizeSettings(Settings);
using (var Out = new MemoryStream())
{
using (var In = new MemoryStream(ImageData))
{
In.Seek(0, SeekOrigin.Begin);
var I = new ImageJob(In, Out, Setting)
{
CreateParentDirectory = false
};
I.Build();
}
Out.Position = 0;
// Upload to blob
}
(str contains a stream with the image)
I want the image to be 1110px wide and max 300px high. Whats wrong?
Upvotes: 1
Views: 402
Reputation: 16468
ImageResizer does not upscale images unless you specifically ask for it via scale=both
or scale=canvas
. Upscaling is typically undesired.
Also, you can pass the stream directly to ImageJob and simplify your code significantly.
str.Seek(0, SeekOrigin.Begin);
var Out = new MemoryStream(8096);
new ImageJob(str, Out, new Instructions("width=1110;height="+ Height + ";format=jpg;mode=crop;scale=both")).Build();
Out.Seek(0, SeekOrigin.Begin);
Upvotes: 2
Reputation: 3509
The other sizes you tested each have a Bmp.Height > 300
which means the image requires to be cropped.
However when using an image size 784x250, the image doesn't require to be cropped. So you'll never re-size the image.
Assuming you wish to keep the image proportionally correct, you should first re-size the image to match the wanted width and afterwards crop the exceeding height if necessary.
var image = new Bitmap(str);
var ratio = (double)1110 / image.Width;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
var bmp = new Bitmap(newImage);
if(bmp.Height > 300){
//Resize again using crop, like you did in your original code.
}
Upvotes: 1