gotmike
gotmike

Reputation: 1615

How to add an image from URL to Excel Worksheet via C#

Here is the goal:

1) Get image from URL, in this case Google Static Maps API

enter image description here

2) Insert this image into an Excel Worksheet. I am okay if I have to create (or use an existing) shape and set the background to the image. I am also okay inserting at specific cells. I can define the image size via the Google Static Maps API (see URL above) so it will always be known.


I am not entirely clear on how to do this WITHOUT saving the file directly to the file system first.

I currently have code like this which gets the image in a MemoryStream format:

public static MemoryStream GetStaticMapMemoryStream(string requestUrl, string strFileLocation)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                throw new Exception(String.Format(
                "Server error (HTTP {0}: {1}).",
                response.StatusCode,
                response.StatusDescription));

            using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
            {
                Byte[] lnByte = reader.ReadBytes(1 * 700 * 500 * 10);
                using (FileStream lxFS = new FileStream(strFileLocation, FileMode.Create))
                {
                    lxFS.Write(lnByte, 0, lnByte.Length);
                }

                MemoryStream msNew = new MemoryStream();
                msNew.Write(lnByte, 0, lnByte.Length);
                return msNew;
            }
        }
    }
    catch (Exception e)
    {
        System.Windows.Forms.MessageBox.Show(e.Message);
        return null;
    }

}

Note that in the middle of the above code, I write the image to the file system as well. I'd like to avoid this part if at all possible.

At any rate, my code can create a rectangle, call the above sequence which saves the image, and then grab the image and populate the background of the rectangle:

Excel.Shape shapeStaticMap = wsNew2.Shapes.AddShape(Office.MsoAutoShapeType.msoShapeRectangle, 0, 0, 700, 500);

string strFileLocation = @"C:\Temp\test.jpg";

MemoryStream newMS = GetStaticMapMemoryStream(strStaticMapUrl, strFileLocation);

shapeStaticMap.Fill.UserPicture(strFileLocation);

So the real problem here is that I'd like to skip the "write to file and then grab from file" back-and-forth. It seems like an unnecessary step, and I anticipate that it will also get messy with file permissions and what-not.

UPDATE

Okay, so I basically gave up and left it using a local file. That worked for a while, but now I'm trying to re-work this code to grab an image from a different source where I don't know the image size in advance. The method above requires me to know the SIZE of the image in advance. How do I modify the code above to use any image size dynamically?

Upvotes: 0

Views: 1172

Answers (1)

gabba
gabba

Reputation: 2880

Use this version of GetStaticMapMemoryStream:

    public static MemoryStream GetStaticMapMemoryStream(string requestUrl)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));

                var responseStream = response.GetResponseStream();
                var memoryStream = new MemoryStream();

                responseStream.CopyTo(memoryStream);
                memoryStream.Position = 0;

                return memoryStream;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return null;
        }
    }

Upvotes: 1

Related Questions