Loading an ASP.Net MVC Image Resizing by Scaling or Filling

The user will be able to upload the image. If the image is larger than the specified size, I want to reduce it to that size. Obviously, it does not have to exactly match the coefficients, the width will be the size of the key, so the height will be variable.

If the image size is smaller than the specified size, I would like to create a new image in the given size with a background of a certain color, and then center the downloaded image into it, so the result will be the original with paddded color.

Any code examples or links that were highly rated

+4
c # image asp.net-mvc
source share
2 answers

Here's a piece of code that I quickly knocked down that changed it based on width. I am sure you can understand how to add background color to the bitmap. This is not complete code, but just an idea of ​​how to do things.

public static void ResizeLogo(string originalFilename, string resizeFilename) { Image imgOriginal = Image.FromFile(originalFilename); //pass in whatever value you want for the width (180) Image imgActual = ScaleBySize(imgOriginal, 180); imgActual.Save(resizeFilename); imgActual.Dispose(); } public static Image ScaleBySize(Image imgPhoto, int size) { int logoSize = size; float sourceWidth = imgPhoto.Width; float sourceHeight = imgPhoto.Height; float destHeight = 0; float destWidth = 0; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; // Resize Image to have the height = logoSize/2 or width = logoSize. // Height is greater than width, set Height = logoSize and resize width accordingly if (sourceWidth > (2 * sourceHeight)) { destWidth = logoSize; destHeight = (float)(sourceHeight * logoSize / sourceWidth); } else { int h = logoSize / 2; destHeight = h; destWidth = (float)(sourceWidth * h / sourceHeight); } // Width is greater than height, set Width = logoSize and resize height accordingly Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight, PixelFormat.Format32bppPArgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, (int)destWidth, (int)destHeight), new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; } 
+10
source share

You can simply load the file into a raster object:

http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx

Then just check the width of the object. For the second part of your problem, I would recommend using a tool like ImageMagick

http://www.imagemagick.org/script/index.php

to precisely resize the first image or create a background image and combine the two images together.

0
source share

All Articles