ScaleToFit(w,h)
将根据源图像的宽度/高度中的较大者按比例缩放图像。缩放多个图像时,除非尺寸的比例都相同,否则您最终会得到不同的尺寸。这是设计使然。
使用ScaleToFit(80,80)
:
- 如果你的源是一个正方形,
100x100
你会得到一个正方形80x80
- 如果你的源是一个矩形,
200x100
你会得到一个矩形80x40
- 如果你的源是一个矩形,
100x200
你会得到一个矩形40x80
无论结果如何,测量宽度和高度,至少有一个是您指定的尺寸之一。
我创建了一个创建随机大小图像的示例程序,它给了我图像中显示的预期输出(w=80,h=80,h=80,h=80,w=80)
private void test() {
//Output the file to the desktop
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF creation here, nothing special
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Create a random number generator to create some random dimensions and colors
var r = new Random();
//Placeholders for the loop
int w, h;
Color c;
iTextSharp.text.Image img;
//Create 5 images
for (var i = 0; i < 5; i++) {
//Create some random dimensions
w = r.Next(25, 500);
h = r.Next(25, 500);
//Create a random color
c = Color.FromArgb(r.Next(256), r.Next(256), r.Next(256));
//Create a random image
img = iTextSharp.text.Image.GetInstance(createSampleImage(w, h, c));
//Scale the image
img.ScaleToFit(80f, 80f);
//Add it to our document
doc.Add(img);
}
doc.Close();
}
}
}
}
/// <summary>
/// Create a single solid color image using the supplied dimensions and color
/// </summary>
private static Byte[] createSampleImage(int width, int height, System.Drawing.Color color) {
using (var bmp = new System.Drawing.Bitmap(width, height)) {
using (var g = Graphics.FromImage(bmp)) {
g.Clear(color);
}
using (var ms = new MemoryStream()) {
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
}
我认为您正在寻找的是按比例缩放图像的能力,但也有图像“是那个大小”,这意味着用清晰或可能的白色像素填充其余像素。请参阅此帖子以获取解决方案。