I have a problem while trying to scale the image. The problem occurs when the image I'm trying to scale (the original) is smaller than the size I'm trying to scale.
For example, an image with a width of 850 pixels and a height of 700 pixels, which will scale to 950 pixels in width and height. The image seems to scale correctly, but it is not drawn correctly on my bitmap. The code for scaling the image will follow. The width sent to ScaleToFitInside is the width and height that try to scale to 950 pixels in my example.
public static Image ScaleToFitInside(Image image, int width, int height) {
Image reszied = ScaleToFit(image, width, height);
Bitmap bitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(0, 0, width, height);
g.FillRectangle(Brushes.White, rect);
int x = (int)(((float)width - (float)reszied.Width) / 2);
int y = (int)(((float)height - (float)reszied.Height) / 2);
Point p = new Point(x, y);
g.DrawImageUnscaled(reszied, p);
foreach (PropertyItem item in image.PropertyItems) {
bitmap.SetPropertyItem(item);
}
}
return bitmap;
}
public static Image ScaleToFit(Image image, int maxWidth, int maxHeight) {
int width = image.Width;
int height = image.Height;
float scale = Math.Min(
((float)maxWidth / (float)width),
((float)maxHeight / (float)height));
return (scale < 1) ? Resize(image, (int)(width * scale), (int)(height * scale)) : image;
}
public static Image Resize(Image image, int width, int height) {
Bitmap bitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
foreach (PropertyItem item in image.PropertyItems) {
bitmap.SetPropertyItem(item);
}
}
return bitmap;
}
, , , , "" .
: 2000x2000 ( ). .
, , " ", . , , 2000x2000 .
:
width = 2000; = 2000;
resized.Width 1000 resized.Height 737 ( ).
x = (2000-1000)/2 = 500; y = (2000-737)/2 = 631.
, -, , - , .
.