JanKallman / EPPlus

Create advanced Excel spreadsheets using .NET
3.76k stars 1.18k forks source link

WMF and EMF being converted to PNG In ExcelPicture for PR #490 #496

Open aesalazar opened 5 years ago

aesalazar commented 5 years ago

When inserting the vector-based image formats WMF or EMF, EPPlus will store the images as PNGs. This is because at some point a call is made to Image.Save() which uses available ImageFormat's in the GDI. These do NOT include WMF or EMF so Image.Save() falls back to using the one for PNG.

The end result would be pixelation when stretched inside excel as well as a larger file size. Running this in DrawingTests.cs:

[TestMethod]
public void AddPicture_Wmf_StoresFormat()
{
    AddPicture_Assert("Vector Drawing.wmf", ImageFormat.Wmf);
}

public void AddPicture_Assert(string fileName, ImageFormat format)
{
    using (var pck = new ExcelPackage())
    {
        var workbook = pck.Workbook;
        var ws = workbook.Worksheets.Add("Sheet1");

        var pic = ws.Drawings.AddPicture("Pic4", new FileInfo(Path.Combine(_clipartPath, fileName)));
        pic.From.Row = 0;
        pic.From.Column = 0;

        pic.To.Row = 30;
        pic.To.Column = 23;

        using (var zip = new ZipArchive(new MemoryStream(pck.GetAsByteArray()), ZipArchiveMode.Read))
        {
            var found = false;

            foreach (var entry in zip.Entries)
            {
                if (entry.Name != $"1{fileName}")
                    continue;

                found = true;
                var stream = entry.Open();
                var drawing = Image.FromStream(stream);

                Assert.AreEqual(format, drawing.RawFormat);
            }

            Assert.IsTrue(found, "Image was not found in zip.");
        }
    }
}

Gives this result:

'Assert.AreEqual failed. Expected:<Wmf>. Actual:<[ImageFormat: b96b3cae-0728-11d3-9d7b-0000f81ef32e]>. '

The GUID listed is for PNG. To fix, the existing FileStream should be used.

Here is a PR with the proposed changes which will allow the 7 new tests (including the one above) to pass: #490

JanKallman commented 4 years ago

Thanks for your detailed description. I have fixed the underlaying problem in EPPlus version 5. I could sadly not use the PR, but the functionality is the same. In version 5 I have rewritten the image handling with a package common picture store.