C#'ta resim boyutunu değiştirmek için System.Drawing namespace'ini kullanabilirsiniz. İşte birkaç farklı yöntem:
Hangi yöntemi seçerseniz seçin, resim boyutlandırma işlemlerinde kalite ve performans arasında bir denge kurmanız önemlidir.
1. Temel Resim Boyutu Değiştirme
C#:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
2. Orantılı Boyutlandırma
C#:
public static Bitmap ResizeImageProportional(Image image, int maxWidth, int maxHeight)
{
double ratioX = (double)maxWidth / image.Width;
double ratioY = (double)maxHeight / image.Height;
double ratio = Math.Min(ratioX, ratioY);
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
return ResizeImage(image, newWidth, newHeight);
}
3. Kullanım Örneği
C#:
// Kaynak resmi yükle
using (Image originalImage = Image.FromFile("input.jpg"))
{
// Yeni boyutları belirle
int newWidth = 800;
int newHeight = 600;
// Resmi boyutlandır
Bitmap resizedImage = ResizeImage(originalImage, newWidth, newHeight);
// Kaydet
resizedImage.Save("output.jpg", ImageFormat.Jpeg);
// Veya orantılı boyutlandırma
Bitmap proportionalImage = ResizeImageProportional(originalImage, 800, 600);
proportionalImage.Save("output_proportional.jpg", ImageFormat.Jpeg);
}
Notlar:
- System.Drawing genellikle Windows ortamında çalışır. Cross-platform uygulamalar için ImageSharp veya SkiaSharp gibi kütüphaneleri düşünebilirsiniz.
- Büyük resimlerle çalışırken bellek yönetimine dikkat edin (using bloklarını kullanın).
- Kalite ayarlarını ihtiyacınıza göre değiştirebilirsiniz (daha hızlı ama daha düşük kalite veya tam tersi).
ImageSharp Kullanımı (Cross-platform için)
C#:
// SixLabors.ImageSharp kütüphanesi gerektirir (NuGet'ten yükleyin)
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
public static void ResizeImageSharp(string inputPath, string outputPath, int width, int height)
{
using (var image = Image.Load(inputPath))
{
image.Mutate(x => x.Resize(width, height));
image.Save(outputPath);
}
}
Hangi yöntemi seçerseniz seçin, resim boyutlandırma işlemlerinde kalite ve performans arasında bir denge kurmanız önemlidir.