Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c# extraction of images from .pptx file

I have the following code for image extraction from .pptx file:

  public static void GetImages()
    {
        var doc = PresentationDocument.Open(@"D:Peak SourcingWorkppt_testxx.pptx", true);

        var presentationPart = doc.PresentationPart;

        var slidePart = presentationPart.GetPartsOfType<SlidePart>().First();

        var imagePart = slidePart.GetPartsOfType<ImagePart>().First();

        var stream = imagePart.GetStream();

        var img = Image.FromStream(stream);

        img.Save(@"D:Peak SourcingWorkppt_test	est-output.png");

    }

The code works, but is extracts just some random image from .ppt file. How to extract all images in order?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like it is not a random image but the first one. Try to iterate over presentationPart.GetPartsOfType<SlidePart>() and slidePart.GetPartsOfType<ImagePart>() using foreach loop.

edit:

here is working code for all images. it generates random file name:

 public static void GetImages()
        {
            var doc = PresentationDocument.Open(@"E:DevStuffConsoleApplication1ConsoleApplication1inDebug	est.pptx", true);
        var presentationPart = doc.PresentationPart;

        foreach (var slide in presentationPart.GetPartsOfType<SlidePart>())
        {
            foreach (var image in slide.GetPartsOfType<ImagePart>())
            {
                if (image != null)
                {
                    var stream = image.GetStream();

                    var img = Image.FromStream(stream);
                    img.Save(@"E:DevStuffConsoleApplication1ConsoleApplication1inDebug" + System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), "jpg"));
                }
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...