Upload image from the project

2

I have a project developed from a console application in Visual C #, in which it sends emails, being the text in html format.

Today I put an image inside this html as follows:

"<img src='" + "http://www.site.com.br/logotipo.png" + "' width='300' height='70'></img>"

I would like to change this, taking this link, leaving the image in the project, and from there load the image. how could I be doing this?

    
asked by anonymous 22.11.2017 / 12:36

1 answer

1

You can convert to a base64 string and place it in src of the image:

I will consider that you have a System.Drawing.Image .

First, convert to a byte array ( byte[] ):

    /// <summary>
    /// Converte um objeto System.Drawing.Image em um array de bytes
    /// </summary>
    /// <param name="foto">System.Drawing.Image</param>
    /// <returns>byte[]</returns>
    public static byte[] ConvertImageToByte(System.Drawing.Image foto, System.Drawing.Imaging.ImageFormat format )
    {
        if (foto != null)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                foto.Save(stream, format);
                //stream.Flush();
                byte[] pic = stream.ToArray();
                return pic;
            }
        }
        else return null;
    }

-Using the function:

 System.Drawing.Image imagem = .... Origem da sua imagem;

 byte[] bImage = ConvertImageToByte(imagem,System.Drawing.Imaging.ImageFormat.Png);

Then, convert byte[] to string :

 string base64String = Convert.ToBase64String(bImage , 0, bImage.Length);

Then put it in the html:

string html = "<img class=""plan-cover"" src=""data:image/png;base64," + base64String + """>";

Obs. If you need to set the image size (smaller than the original), it makes sense to resize the Image object and not html . The amount of data sent will be only what is needed.

    
22.11.2017 / 13:13