Looks like a problem of doing integer math. Might try doing using single precision variables.
Asp net core Dividing does not work
I am trying to resize a Image
the perfect size needs to be Width= 250px and Height= 200px
But because not all images have this Ratio
I need to do some math to make it fit
so for example Image Width = 1000px
and Height = 667px
I just need to (250 / 1000) * 667 = 166,75
so new Width = 250 and new Height = 167
But this does not work in Asp net core and I dont know why
string Headername = Guid.NewGuid().ToString() + "_" + dto.HeaderImg.FileName;
string filepath = Path.Combine(root, Headername);
Image image = Image.FromStream(TheFile.OpenReadStream(), true, true);
int newWidth = 250;
int newHeight = 200;
int OldWidth = image.Width;
int OldHeight = image.Height;
if (image.Width > image.Height)
newHeight = (newWidth / OldWidth) * OldHeight; // returns 0;
else if (image.Width < image.Height)
newWidth = (newHeight / OldHeight) * OldWidth; returns 0;
else if (image.Width == image.Height)
newHeight = 250;
var newImage = new Bitmap(newWidth, newHeight);
using var a = Graphics.FromImage(newImage);
a.DrawImage(image, 0, 0, newImage.Width, newImage.Height);
newImage.Save(filepath);
when i try to calculate in Asp net core, It always returns 0;
2 answers
Sort by: Most helpful
-
-
Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
2022-06-13T02:59:36.657+00:00 Hi @osyris ,
int newWidth = 250;
int newHeight = 200; int OldWidth = image.Width; int OldHeight = image.Height; if (image.Width > image.Height) newHeight = (newWidth / OldWidth) * OldHeight; // returns 0; else if (image.Width < image.Height) newWidth = (newHeight / OldHeight) * OldWidth; returns 0; else if (image.Width == image.Height) newHeight = 250;
If you set a break point to the above code, you can see that issue relates the integer division, the result is 0.
To solve this issue, you can try to change the number from the
int
type todecimal
type or use thefloat
type. Code like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion