Search code examples
c#arraysimageconverterspdfsharp

Byte[ ] too large to convert to System.Drawing.Image?


I'm trying to save an Image from a Byte[], and I keep getting kicked out with ArgumentException : Parameter is not valid. I'm wondering if the Byte[] is too large to convert. Is there a limit?

Code:

private XImage[] GetImagesFromURL(List<string> lstCutSheetURLs)
{
    int itr = lstCutSheetURLs.Count;
    XImage[] m_imgCutSheets = new XImage[itr];

    using (var webClient = new WebClient())
    {
        for (int i = 0; i < itr; i++)
        {
            var imageBytes = webClient.DownloadData(lstCutSheetURLs[i]);
            if (imageBytes != null && imageBytes.Length > 0)
            {
                MemoryStream ms = new MemoryStream();
                ImageConverter converter = new ImageConverter();

                //
                //THIS IS WHERE IT BREAKS EVERY TIME
                Image img = (Image)converter.ConvertFrom(imageBytes);
                //

                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                m_imgCutSheets[i] = XImage.FromStream(ms);
            }
        }
    }

    return m_imgCutSheets;
}

The Byte[] ends up holding 458,330 indexes. Is that way too many? Is there a better way to get images from websites? I've been looking all over trying to find things out, and now I'm here.

Any articles / advice / answers are greatly appreciated! Thanks.


Solution

  • PDF files are vector files. It seems that the ImageConverter class cannot handle PDF files (judging from your self-answer; PDF files are much more than images and it makes sense that ImageConverter does not try to convert them). If it could, it would still fundamentally change the PDF content from vector to raster, losing the scalability and possibly leading to larger files.

    The best you can do to add pages from one PDF file to another is using the XPdfForm class. You can use the form object in calls to DrawImage like you draw raster images to PDF.

    Code snippet:
    XPdfForm form = XPdfForm.FromFile(filename);

    Sample code on the PDFsharp site:
    http://pdfsharp.net/wiki/TwoPagesOnOne-sample.ashx

    JPG files are another special case your code should take care of. Converting JPG to PNG is possible, but makes no sense. PNG is a lossless format, JPG has losses but drastically reduces the file size. Converting from JPG to PNG leads in most cases to a larger file with JPEG artefacts.

    IMHO it is OK to use ImageConverter for other types beside PDF and JPG. It could be a good validation to see whether files are complete.
    Since XImage.FromStream can handle several image formats (PNG, BMP, GIF, TIFF, JPG), this may not really add functionality beside the validation.

    While this does not really answer the question in your title, this is general advice on PDFsharp image handling/PDF image handling and you asked for related advice in your question.