C# 使用OpenXMLSDK调整DocX中现有图像的大小

C# 使用OpenXMLSDK调整DocX中现有图像的大小,c#,openxml,docx,openxml-sdk,C#,Openxml,Docx,Openxml Sdk,已获取带有图像占位符的模板docx,该占位符已替换为正确的图片 private void SetImagePartData(ImagePart imagePart, byte[] data) { if (imagePart != null) { using (var writer = new BinaryWriter(imagePart.GetStream())) { writer.Write(data);

已获取带有图像占位符的模板docx,该占位符已替换为正确的图片

private void SetImagePartData(ImagePart imagePart, byte[] data)
{
    if (imagePart != null)
    {
        using (var writer = new BinaryWriter(imagePart.GetStream()))
        {
            writer.Write(data);
        }
    }
}

但它保留了占位符的大小。如何将其更改为实际图像大小?字节数组是从服务器上的图像中提取的,因此大小是已知的。

如果您指的是带有占位符的内容控件,您可以在需要时使用以下代码:

//Get SdtElement (can be a block, run... so I use the base class) with corresponding Tag
SdtElement block = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>()
  .FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag);

//Get First drawing Element and get the original sizes of placeholder SDT
//I use SDT placeholder size as maximum size to calculate picture size with correct ratios
Drawing sdtImage = block.Descendants<Drawing>().First();
double sdtWidth = sdtImage.Inline.Extent.Cx;
double sdtHeight = sdtImage.Inline.Extent.Cy;
double sdtRatio = sdtWidth / sdtHeight;

*Calculate final width/height of image*

//Resize picture placeholder
sdtImage.Inline.Extent.Cx = finalWidth;
sdtImage.Inline.Extent.Cy = finalHeight;

//Change width/height of picture shapeproperties Transform
//This will override above height/width until you manually drag image for example
sdtImage.Inline.Graphic.GraphicData
    .GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
    .ShapeProperties.Transform2D.Extents.Cx = finalWidth;
sdtImage.Inline.Graphic.GraphicData
    .GetFirstChild<DocumentFormat.OpenXml.Drawing.Pictures.Picture>()
    .ShapeProperties.Transform2D.Extents.Cy = finalHeight;
//Get-SdtElement(可以是块,运行…所以我使用基类)和相应的标记
SdtElement block=doc.MainDocumentPart.Document.Body.subjects()
.FirstOrDefault(sdt=>sdt.SdtProperties.GetFirstChild()?.Val==contentControlTag);
//获取第一个图形元素并获取占位符SDT的原始尺寸
//我使用SDT占位符大小作为最大大小,以正确的比率计算图片大小
绘图sdtImage=block.subjects().First();
double sdtWidth=sdtImage.Inline.Extent.Cx;
double sdtHeight=sdtImage.Inline.Extent.Cy;
双斜线=双斜线/右斜线;
*计算图像的最终宽度/高度*
//调整图片占位符的大小
sdtImage.Inline.Extent.Cx=最终宽度;
sdtImage.Inline.Extent.Cy=最终重量;
//更改图片形状的宽度/高度属性变换
//例如,在手动拖动图像之前,这将覆盖高度/宽度
sdtImage.Inline.Graphic.GraphicData
.GetFirstChild()
.ShapeProperties.Transform2D.Extents.Cx=最终宽度;
sdtImage.Inline.Graphic.GraphicData
.GetFirstChild()
.ShapeProperties.Transform2D.Extents.Cy=最终高度;

但如果您也只是在word文档中使用图像,则可以使用它。您只需找到正确的
绘图
元素,该元素包含对imagepart的引用。然后,您可以使用代码的底部来调整图像大小。调整
Transform2D
x和y以及
Inline
x和y非常重要,否则图像大小将不会更改。

可能重复我没有插入图像。只要更改它并调整大小GIF如果您查看文章中更接近代码的部分(不仅仅是标题),您就会找到问题的答案。一旦将绘图元素放置在段落中,如何在imagepart中找到它的引用?