Image resizing can be done with C# and many 3rd party plugins. So how to size without using any plugin? These operations may seem a bit complicated, so a class we will create in the business layer can do all our work. Now let's look at this class and how to use it.
In the class we will create, we will have methods such as image resizing, image resizing to a certain width, image cropping, adding watermark to the image, adjusting image transparency and saving the image.
public Bitmap ResizeImage(Image image, int width, int height)
{
if (image.Width <= width)
{
width = image.Width;
}
if (image.Height <= height)
{
height = image.Height;
}
Bitmap bmpt = new Bitmap(width, height);
Graphics grt = Graphics.FromImage(bmpt);
grt.CompositingQuality = CompositingQuality.Default;
grt.SmoothingMode = SmoothingMode.Default;
grt.InterpolationMode = InterpolationMode.Bicubic;
grt.PixelOffsetMode = PixelOffsetMode.Default;
grt.DrawImage(image, 0, 0, width, height);
return bmpt;
}
public Bitmap ResizeImageFixedWidth(Image image, int width)
{
int srcWidth = image.Width;
int srcHeight = image.Height;
int thumbWidth = 0;
int thumbHeight = 0;
if (srcHeight > srcWidth)
{
double horan = (srcWidth * 100) / srcHeight;
thumbHeight = width;
thumbWidth = Convert.ToInt32((thumbHeight * horan) / 100);
}
else if (srcWidth > srcHeight)
{
double woran = (srcHeight * 100) / srcWidth;
thumbWidth = width;
thumbHeight = Convert.ToInt32((thumbWidth * woran) / 100);
}
else if (srcHeight == srcWidth)
{
thumbHeight = width;
thumbWidth = width;
}
Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.Default;
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Bicubic;
gr.PixelOffsetMode = PixelOffsetMode.Default;
Rectangle imageRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, imageRectangle, rectDestination, GraphicsUnit.Pixel);
gr.Dispose();
return bmp;
}
You can resize an uploaded image or an image to be uploaded with the ResizeImage method we will create. We will give an example using an image that will be uploaded now.
Bitmap resizedImage = ResizeImage(Image.FromStream(Request.Files[0].InputStream), 1024, 800);
An image we resize in this way may have bad results. The reason for this is the size and resolution of the image. If the image has dimensions of 600x1000 (i.e. vertical image), the correct size will not appear. So, what action should be taken to get an accurate result? For this, it would be better to use a method where we will give a fixed width and it will adjust the height itself. This method is as follows.
Bitmap resizedImage = ResizeImageFixedWidth(Image.FromStream(Request.Files[0].InputStream), 1024);
When we resize the image to a fixed width of 1024, there will be no problem even with a 600x1000 image.
public Bitmap CropImage(Image image, int x, int y, int width, int height)
{
Rectangle rectDestination = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(rectDestination.Width, rectDestination.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.Default;
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Bicubic;
gr.PixelOffsetMode = PixelOffsetMode.Default;
gr.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), rectDestination, GraphicsUnit.Pixel);
return bmp;
}
You can crop the image to the desired size in C# using the method you see above. When cropping images, attention should be paid to image dimensions and resolution, as in resizing. If we give an example of image cropping:
var croppedImage = CropImage(
Image.FromStream(Request.Files[0].InputStream)
, x, y, 500, 500);
If we look at the x and y coordinates in the CropImage method, their meanings are as follows:
x: It refers to the horizontal position of the image in the x coordinate.
y: It refers to the vertical position of the image in the y coordinate.
x = 0; y = 0; , it will perform the cutting process starting from the top left part of the image.
public static Bitmap WatermarkImage(Bitmap image, Bitmap watermark)
{
using (Graphics imageGraphics = Graphics.FromImage(image))
{
watermark.SetResolution(imageGraphics.DpiX, imageGraphics.DpiY);
int x = (image.Width - watermark.Width) / 2;
int y = (image.Height - watermark.Height) / 2;
Image _watermark = SetImageOpacity(watermark, .5f);
imageGraphics.DrawImage(_watermark, x, y, _watermark.Width, _watermark.Height);
}
return image;
}
public static Image SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix
{
//set the opacity
Matrix33 = opacity
};
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception)
{
return null;
}
}
You can use the WatermarkImage method above to make watermarks with C#. The first parameter of this method refers to the image to be watermarked, and the second parameter refers to the watermark image. You can use the following codes for an example of the watermark process;
Bitmap watermarkImage = new Bitmap(Image.FromFile(Server.MapPath("~/assets/AlfaLogo.png")));
Bitmap watermarkedImage = WatermarkImage(ResizeImageFixedWidth(Image.FromStream(Request.Files[0].InputStream), 1200), watermarkImage);
In general, image resizing, cropping and adding watermarks with C# are as follows. You can do these operations more easily with 3rd party plugins. The most used among these plugins are as follows:
For more plugins, you can use the Nuget package installation tool.
Here's how you can create the class we use for the examples.
public class ImageProcess
{
public Bitmap ResizeImage(Image image, int width, int height)
{
if (image.Width <= width)
{
width = image.Width;
}
if (image.Height <= height)
{
height = image.Height;
}
Bitmap bmpt = new Bitmap(width, height);
Graphics grt = Graphics.FromImage(bmpt);
grt.CompositingQuality = CompositingQuality.Default;
grt.SmoothingMode = SmoothingMode.Default;
grt.InterpolationMode = InterpolationMode.Bicubic;
grt.PixelOffsetMode = PixelOffsetMode.Default;
grt.DrawImage(image, 0, 0, width, height);
return bmpt;
}
public Bitmap ResizeImageFixedWidth(Image image, int width)
{
int srcWidth = image.Width;
int srcHeight = image.Height;
int thumbWidth = 0;
int thumbHeight = 0;
if (srcHeight > srcWidth)
{
double horan = (srcWidth * 100) / srcHeight;
thumbHeight = width;
thumbWidth = Convert.ToInt32((thumbHeight * horan) / 100);
}
else if (srcWidth > srcHeight)
{
double woran = (srcHeight * 100) / srcWidth;
thumbWidth = width;
thumbHeight = Convert.ToInt32((thumbWidth * woran) / 100);
}
else if (srcHeight == srcWidth)
{
thumbHeight = width;
thumbWidth = width;
}
Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.Default;
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Bicubic;
gr.PixelOffsetMode = PixelOffsetMode.Default;
Rectangle imageRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, imageRectangle, rectDestination, GraphicsUnit.Pixel);
gr.Dispose();
return bmp;
}
public void CropImageAndSave(Image image, string url, int x, int y, int width, int height)
{
Rectangle rectDestination = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(rectDestination.Width, rectDestination.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.Default;
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Bicubic;
gr.PixelOffsetMode = PixelOffsetMode.Default;
gr.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), rectDestination, GraphicsUnit.Pixel);
bmp.Save(HttpContext.Current.Server.MapPath(url), image.RawFormat);
bmp.Dispose();
image.Dispose();
}
public Bitmap CropImage(Image image, int x, int y, int width, int height)
{
Rectangle rectDestination = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(rectDestination.Width, rectDestination.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.Default;
gr.SmoothingMode = SmoothingMode.Default;
gr.InterpolationMode = InterpolationMode.Bicubic;
gr.PixelOffsetMode = PixelOffsetMode.Default;
gr.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), rectDestination, GraphicsUnit.Pixel);
return bmp;
}
public static Bitmap WatermarkImage(Bitmap image, Bitmap watermark)
{
using (Graphics imageGraphics = Graphics.FromImage(image))
{
watermark.SetResolution(imageGraphics.DpiX, imageGraphics.DpiY);
int x = (image.Width - watermark.Width) / 2;
int y = (image.Height - watermark.Height) / 2;
Image _watermark = SetImageOpacity(watermark, .5f);
imageGraphics.DrawImage(_watermark, x, y, _watermark.Width, _watermark.Height);
}
return image;
}
public static Image SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix
{
//set the opacity
Matrix33 = opacity
};
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception)
{
return null;
}
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
public static void SaveJpeg(string path, Image image)
{
ImageCodecInfo encoder = GetEncoder(ImageFormat.Jpeg);
if (encoder != null)
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 50L);
image.Save(path, encoder, encoderParameters);
}
else
{
image.Save(path);
}
}
}
As we come to the end of this article, we wish everyone good luck. Stay well.
We help you with your business's most critical issues and opportunities. How about getting permanent change and results together?