Reduce Image size C#
Here is a simple C# program that can be used to minimize the size of an image:
using System;
using System.IO;
using System.Drawing;
namespace ImageResizer
{
class Program
{
static void Main(string[] args)
{
string filePath = "C:/path/to/myimage.jpg";
int newWidth = 640;
int newHeight = 480;
// Load the image from file
Image originalImage = Image.FromFile(filePath);
// Calculate the new size of the image
Size newSize = GetNewSize(originalImage.Width, originalImage.Height, newWidth, newHeight);
// Create a new bitmap with the new size
Bitmap resizedImage = new Bitmap(newSize.Width, newSize.Height);
// Draw the original image onto the bitmap with the new size
using (Graphics g = Graphics.FromImage(resizedImage))
{
g.DrawImage(originalImage, 0, 0, newSize.Width, newSize.Height);
}
// Save the resized image to a new file
resizedImage.Save("C:/path/to/resized_image.jpg");
}
static Size GetNewSize(int originalWidth, int originalHeight, int newWidth, int newHeight)
{
int finalWidth;
int finalHeight;
// Calculate the new width and height based on the aspect ratio
if (originalWidth > originalHeight)
{
finalWidth = newWidth;
finalHeight = (int)(originalHeight * ((float)newWidth / (float)originalWidth));
}
else
{
finalWidth = (int)(originalWidth * ((float)newHeight / (float)originalHeight));
finalHeight = newHeight;
}
return new Size(finalWidth, finalHeight);
}
}
}
This program loads an image from a file, calculates a new size for the image based on the specified width and height, creates a new bitmap with the new size, and draws the original image onto the bitmap. The resized image is then saved to a new file.
The GetNewSize function is used to calculate the new size of the image based on the aspect ratio of the original image so that the resulting image is not distorted.
Comments
Post a Comment