我遇到了同样的问题:我的文件太大,因为照片被嵌入为 png 而不是 jpeg。我通过将包中的所有 png 文件转换为 jpeg 来修复它。我保持 URI 相同以避免更新对图像的引用,但这意味着 jpeg 的内部 URI 将以误导性的“.png”结尾。显然,如果您想选择要转换为 jpeg 的图像,这会变得更加复杂。
public static void ReplacePngsWithJpegs(Package package)
{
// We're modifying the enumerable as we iterate, so take a snapshot with ToList()
foreach (var part in package.GetParts().ToList())
{
if (part.ContentType == "image/png")
{
using (var jpegStream = new MemoryStream())
using (var image = System.Drawing.Image.FromStream(part.GetStream()))
{
image.Save(jpegStream, System.Drawing.Imaging.ImageFormat.Jpeg);
jpegStream.Seek(0, SeekOrigin.Begin);
// Cannot access Uri after part is removed, so store it
var uri = part.Uri;
package.DeletePart(uri);
var jpegPart = package.CreatePart(uri, "image/jpeg");
jpegStream.CopyTo(jpegPart.GetStream());
}
}
}
}