C# iTextSharp:如何调整图像大小以适合固定大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9412504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:17:34  来源:igfitidea点击:

iTextSharp: How to resize an image to fit a fix size?

c#imageresizeitext

提问by Emanuel

I want to be able to resize an image to the dimension of 159x159 points, using iTextSharp 4.2.0, but the resulting image need to have exactly the dimensions specified.

我希望能够使用 iTextSharp 4.2.0 将图像大小调整为 159x159 点的尺寸,但生成的图像需要具有指定的尺寸。

I've tried this:

我试过这个:

Image image = Image.GetInstance(imagePath);
image.ScaleAbsolute(159f, 159f);

But the image is not a square. It keeps the aspect ratio.

但图像不是正方形。它保持纵横比。

Example: I have this image:

示例:我有这张图片:

enter image description here

在此处输入图片说明

And the result image should look loke this:

结果图像应该看起来像这样:

enter image description here

在此处输入图片说明

Thanks.

谢谢。

采纳答案by kuujinbo

The problem you describe is typically what happens when you try and add an Imagedirectly to a PdfPTableby calling AddCell(), which alwaysscales the image to fit the PdfPCell. So if you're adding the image to the Documentlike this:

您描述的问题通常是当您尝试通过调用将 aImage直接添加到 a时会发生什么,这总是缩放图像以适合. 因此,如果您将图像添加到这样的:PdfPTableAddCell()PdfPCellDocument

Image img = Image.GetInstance(imagePath);
img.ScaleAbsolute(159f, 159f);
PdfPTable table = new PdfPTable(1);
table.AddCell(img);
document.Add(table);

your ScaleAbsolute()call is ignored. To get the scaling you want:

你的ScaleAbsolute()电话被忽略了。要获得所需的缩放比例:

PdfPTable table = new PdfPTable(1);
table.AddCell(new PdfPCell(img));
document.Add(table);

回答by Pragnesh Mistry

PdfPCellhas property to fit image in cell so just set it to true.

PdfPCell具有在单元格中适合图像的属性,因此只需将其设置为 true。

  iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("/test.png");

  PdfPCell logocell = new PdfPCell(logo,true); //  **PdfPCell(Image,Boolean Fit)**